services.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. // Package server implements the core tunnel functionality of a Psiphon server.
  20. // The main function is RunServices, which runs one or all of a Psiphon API web server,
  21. // a tunneling SSH server, and an Obfuscated SSH protocol server. The server configuration
  22. // is created by the GenerateConfig function.
  23. package server
  24. import (
  25. "fmt"
  26. "math/rand"
  27. "os"
  28. "os/signal"
  29. "runtime"
  30. "runtime/debug"
  31. "sync"
  32. "syscall"
  33. "time"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/packetman"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  42. "github.com/shirou/gopsutil/v4/cpu"
  43. )
  44. // RunServices initializes support functions including logging and GeoIP services;
  45. // and then starts the server components and runs them until os.Interrupt or
  46. // os.Kill signals are received. The config determines which components are run.
  47. func RunServices(configJSON []byte) (retErr error) {
  48. loggingInitialized := false
  49. defer func() {
  50. if retErr != nil && loggingInitialized {
  51. log.WithTraceFields(LogFields{"error": retErr}).Error("RunServices failed")
  52. }
  53. }()
  54. rand.Seed(int64(time.Now().Nanosecond()))
  55. config, err := LoadConfig(configJSON)
  56. if err != nil {
  57. return errors.Trace(err)
  58. }
  59. err = InitLogging(config)
  60. if err != nil {
  61. return errors.Trace(err)
  62. }
  63. loggingInitialized = true
  64. support, err := NewSupportServices(config)
  65. if err != nil {
  66. return errors.Trace(err)
  67. }
  68. startupFields := buildinfo.GetBuildInfo().ToMap()
  69. startupFields["GODEBUG"] = os.Getenv("GODEBUG")
  70. log.WithTraceFields(startupFields).Info("startup")
  71. waitGroup := new(sync.WaitGroup)
  72. shutdownBroadcast := make(chan struct{})
  73. errorChannel := make(chan error, 1)
  74. tunnelServer, err := NewTunnelServer(support, shutdownBroadcast)
  75. if err != nil {
  76. return errors.Trace(err)
  77. }
  78. support.TunnelServer = tunnelServer
  79. if config.RunPacketTunnel {
  80. packetTunnelServer, err := tun.NewServer(&tun.ServerConfig{
  81. Logger: CommonLogger(log),
  82. SudoNetworkConfigCommands: config.PacketTunnelSudoNetworkConfigCommands,
  83. GetDNSResolverIPv4Addresses: support.DNSResolver.GetAllIPv4,
  84. GetDNSResolverIPv6Addresses: support.DNSResolver.GetAllIPv6,
  85. EnableDNSFlowTracking: config.PacketTunnelEnableDNSFlowTracking,
  86. EgressInterface: config.PacketTunnelEgressInterface,
  87. DownstreamPacketQueueSize: config.PacketTunnelDownstreamPacketQueueSize,
  88. SessionIdleExpirySeconds: config.PacketTunnelSessionIdleExpirySeconds,
  89. AllowBogons: config.AllowBogons,
  90. })
  91. if err != nil {
  92. return errors.Trace(err)
  93. }
  94. support.PacketTunnelServer = packetTunnelServer
  95. }
  96. if config.RunPacketManipulator {
  97. packetManipulatorConfig, err := makePacketManipulatorConfig(support)
  98. if err != nil {
  99. return errors.Trace(err)
  100. }
  101. packetManipulator, err := packetman.NewManipulator(packetManipulatorConfig)
  102. if err != nil {
  103. return errors.Trace(err)
  104. }
  105. support.PacketManipulator = packetManipulator
  106. }
  107. support.discovery = makeDiscovery(support)
  108. // After this point, errors should be delivered to the errors channel and
  109. // orderly shutdown should flow through to the end of the function to ensure
  110. // all workers are synchronously stopped.
  111. if config.RunPacketTunnel {
  112. support.PacketTunnelServer.Start()
  113. waitGroup.Add(1)
  114. go func() {
  115. defer waitGroup.Done()
  116. <-shutdownBroadcast
  117. support.PacketTunnelServer.Stop()
  118. }()
  119. }
  120. if config.RunPacketManipulator {
  121. err := support.PacketManipulator.Start()
  122. if err != nil {
  123. select {
  124. case errorChannel <- err:
  125. default:
  126. }
  127. } else {
  128. waitGroup.Add(1)
  129. go func() {
  130. defer waitGroup.Done()
  131. <-shutdownBroadcast
  132. support.PacketManipulator.Stop()
  133. }()
  134. }
  135. }
  136. err = support.discovery.Start()
  137. if err != nil {
  138. select {
  139. case errorChannel <- err:
  140. default:
  141. }
  142. } else {
  143. waitGroup.Add(1)
  144. go func() {
  145. defer waitGroup.Done()
  146. <-shutdownBroadcast
  147. support.discovery.Stop()
  148. }()
  149. }
  150. if config.RunLoadMonitor() {
  151. waitGroup.Add(1)
  152. go func() {
  153. waitGroup.Done()
  154. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  155. defer ticker.Stop()
  156. logNetworkBytes := true
  157. logCPU := true
  158. previousNetworkBytesReceived, previousNetworkBytesSent, err := getNetworkBytesTransferred()
  159. if err != nil {
  160. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Error(
  161. "failed to get initial network bytes transferred")
  162. // If getNetworkBytesTransferred fails, stop logging network
  163. // bytes for the lifetime of this process, in case there's a
  164. // persistent issue with /proc/net/dev data.
  165. logNetworkBytes = false
  166. }
  167. // Establish initial previous CPU stats. The previous CPU stats
  168. // are stored internally by gopsutil/cpu.
  169. _, err = getCPUPercent()
  170. if err != nil {
  171. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Error(
  172. "failed to get initial CPU percent")
  173. logCPU = false
  174. }
  175. for {
  176. select {
  177. case <-shutdownBroadcast:
  178. return
  179. case <-ticker.C:
  180. var networkBytesReceived, networkBytesSent int64
  181. if logNetworkBytes {
  182. currentNetworkBytesReceived, currentNetworkBytesSent, err := getNetworkBytesTransferred()
  183. if err != nil {
  184. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Error(
  185. "failed to get current network bytes transferred")
  186. logNetworkBytes = false
  187. } else {
  188. networkBytesReceived = currentNetworkBytesReceived - previousNetworkBytesReceived
  189. networkBytesSent = currentNetworkBytesSent - previousNetworkBytesSent
  190. previousNetworkBytesReceived, previousNetworkBytesSent =
  191. currentNetworkBytesReceived, currentNetworkBytesSent
  192. }
  193. }
  194. var CPUPercent float64
  195. if logCPU {
  196. recentCPUPercent, err := getCPUPercent()
  197. if err != nil {
  198. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Error(
  199. "failed to get recent CPU percent")
  200. logCPU = false
  201. } else {
  202. CPUPercent = recentCPUPercent
  203. }
  204. }
  205. // In the rare case that /proc/net/dev rx or tx counters
  206. // wrap around or are reset, networkBytesReceived or
  207. // networkBytesSent may be < 0. logServerLoad will not
  208. // log these negative values.
  209. logServerLoad(
  210. support, logNetworkBytes, networkBytesReceived, networkBytesSent, logCPU, CPUPercent)
  211. }
  212. }
  213. }()
  214. }
  215. if config.RunPeriodicGarbageCollection() {
  216. waitGroup.Add(1)
  217. go func() {
  218. waitGroup.Done()
  219. ticker := time.NewTicker(config.periodicGarbageCollection)
  220. defer ticker.Stop()
  221. for {
  222. select {
  223. case <-shutdownBroadcast:
  224. return
  225. case <-ticker.C:
  226. debug.FreeOSMemory()
  227. }
  228. }
  229. }()
  230. }
  231. // The tunnel server is always run; it launches multiple
  232. // listeners, depending on which tunnel protocols are enabled.
  233. waitGroup.Add(1)
  234. go func() {
  235. defer waitGroup.Done()
  236. err := tunnelServer.Run()
  237. select {
  238. case errorChannel <- err:
  239. default:
  240. }
  241. }()
  242. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  243. // to complete, as it may be sleeping while running a "block" or
  244. // CPU profile.
  245. signalProcessProfiles := make(chan struct{}, 1)
  246. go func() {
  247. for {
  248. select {
  249. case <-signalProcessProfiles:
  250. outputProcessProfiles(support.Config, "")
  251. case <-shutdownBroadcast:
  252. return
  253. }
  254. }
  255. }()
  256. // In addition to the actual signal handling here, there is
  257. // a list of signals that need to be passed through panicwrap
  258. // in 'github.com/Psiphon-Labs/psiphon-tunnel-core/Server/main.go'
  259. // where 'panicwrap.Wrap' is called. The handled signals below, and the
  260. // list there must be kept in sync to ensure proper signal handling
  261. // An OS signal triggers an orderly shutdown
  262. systemStopSignal := make(chan os.Signal, 1)
  263. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  264. // SIGUSR1 triggers a reload of support services
  265. reloadSupportServicesSignal := makeSIGUSR1Channel()
  266. // SIGUSR2 triggers an immediate load log and optional process profile output
  267. logServerLoadSignal := makeSIGUSR2Channel()
  268. // SIGTSTP triggers tunnelServer to stop establishing new tunnels. The
  269. // in-proxy broker, if running, may also stop enqueueing announces or
  270. // offers.
  271. stopEstablishingTunnelsSignal := makeSIGTSTPChannel()
  272. // SIGCONT triggers tunnelServer to resume establishing new tunnels. The
  273. // in-proxy broker, if running, will resume enqueueing all announces and
  274. // offers.
  275. resumeEstablishingTunnelsSignal := makeSIGCONTChannel()
  276. err = nil
  277. loop:
  278. for {
  279. select {
  280. case <-stopEstablishingTunnelsSignal:
  281. tunnelServer.SetEstablishTunnels(false)
  282. // Dump profiles when entering the load limiting state with an
  283. // unexpectedly low established client count, as determined by
  284. // DumpProfilesOnStopEstablishTunnels.
  285. if config.DumpProfilesOnStopEstablishTunnels(
  286. tunnelServer.GetEstablishedClientCount()) {
  287. // Run the profile dump in a goroutine and don't block this loop. Shutdown
  288. // doesn't wait for any running outputProcessProfiles to complete.
  289. go func() {
  290. outputProcessProfiles(support.Config, "stop_establish_tunnels")
  291. }()
  292. }
  293. case <-resumeEstablishingTunnelsSignal:
  294. tunnelServer.SetEstablishTunnels(true)
  295. case <-reloadSupportServicesSignal:
  296. support.Reload()
  297. case <-logServerLoadSignal:
  298. // Signal profiles writes first to ensure some diagnostics are
  299. // available in case logServerLoad hangs (which has happened
  300. // in the past due to a deadlock bug).
  301. select {
  302. case signalProcessProfiles <- struct{}{}:
  303. default:
  304. }
  305. logServerLoad(support, false, 0, 0, false, 0)
  306. case <-systemStopSignal:
  307. log.WithTrace().Info("shutdown by system")
  308. break loop
  309. case err = <-errorChannel:
  310. break loop
  311. }
  312. }
  313. // During any delayed or hung shutdown, periodically dump profiles to help
  314. // diagnose the cause. Shutdown doesn't wait for any running
  315. // outputProcessProfiles to complete.
  316. signalProfileDumperStop := make(chan struct{})
  317. go func() {
  318. tickSeconds := 10
  319. ticker := time.NewTicker(time.Duration(tickSeconds) * time.Second)
  320. defer ticker.Stop()
  321. for i := tickSeconds; i <= 60; i += tickSeconds {
  322. select {
  323. case <-signalProfileDumperStop:
  324. return
  325. case <-ticker.C:
  326. filenameSuffix := fmt.Sprintf("delayed_shutdown_%ds", i)
  327. outputProcessProfiles(support.Config, filenameSuffix)
  328. }
  329. }
  330. }()
  331. close(shutdownBroadcast)
  332. waitGroup.Wait()
  333. close(signalProfileDumperStop)
  334. return err
  335. }
  336. func getRuntimeMetrics() LogFields {
  337. numGoroutine := runtime.NumGoroutine()
  338. var memStats runtime.MemStats
  339. runtime.ReadMemStats(&memStats)
  340. lastGC := ""
  341. if memStats.LastGC > 0 {
  342. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  343. }
  344. return LogFields{
  345. "num_goroutine": numGoroutine,
  346. "heap_alloc": memStats.HeapAlloc,
  347. "heap_sys": memStats.HeapSys,
  348. "heap_idle": memStats.HeapIdle,
  349. "heap_inuse": memStats.HeapInuse,
  350. "heap_released": memStats.HeapReleased,
  351. "heap_objects": memStats.HeapObjects,
  352. "num_gc": memStats.NumGC,
  353. "num_forced_gc": memStats.NumForcedGC,
  354. "last_gc": lastGC,
  355. }
  356. }
  357. func outputProcessProfiles(config *Config, filenameSuffix string) {
  358. log.WithTraceFields(getRuntimeMetrics()).Info("runtime_metrics")
  359. if config.ProcessProfileOutputDirectory != "" {
  360. common.WriteRuntimeProfiles(
  361. CommonLogger(log),
  362. config.ProcessProfileOutputDirectory,
  363. filenameSuffix,
  364. config.ProcessBlockProfileDurationSeconds,
  365. config.ProcessCPUProfileDurationSeconds)
  366. }
  367. }
  368. // getCPUPercent returns the overall system CPU percent (not the percent used
  369. // by this process), across all cores.
  370. func getCPUPercent() (float64, error) {
  371. values, err := cpu.Percent(0, false)
  372. if err != nil {
  373. return 0, errors.Trace(err)
  374. }
  375. if len(values) != 1 {
  376. return 0, errors.TraceNew("unexpected cpu.Percent return value")
  377. }
  378. return values[0], nil
  379. }
  380. func logServerLoad(
  381. support *SupportServices,
  382. logNetworkBytes bool,
  383. networkBytesReceived int64,
  384. networkBytesSent int64,
  385. logCPU bool,
  386. CPUPercent float64) {
  387. serverLoad := getRuntimeMetrics()
  388. serverLoad["event_name"] = "server_load"
  389. if logNetworkBytes {
  390. // Negative values, which may occur due to counter wrap arounds, are
  391. // omitted.
  392. if networkBytesReceived >= 0 {
  393. serverLoad["network_bytes_received"] = networkBytesReceived
  394. }
  395. if networkBytesSent >= 0 {
  396. serverLoad["network_bytes_sent"] = networkBytesSent
  397. }
  398. }
  399. if logCPU {
  400. serverLoad["cpu_percent"] = CPUPercent
  401. }
  402. establishTunnels, establishLimitedCount :=
  403. support.TunnelServer.GetEstablishTunnelsMetrics()
  404. serverLoad["establish_tunnels"] = establishTunnels
  405. serverLoad["establish_tunnels_limited_count"] = establishLimitedCount
  406. serverLoad.Add(support.ReplayCache.GetMetrics())
  407. serverLoad.Add(support.ServerTacticsParametersCache.GetMetrics())
  408. upstreamStats, protocolStats, regionStats :=
  409. support.TunnelServer.GetLoadStats()
  410. for name, value := range upstreamStats {
  411. serverLoad[name] = value
  412. }
  413. for protocol, stats := range protocolStats {
  414. serverLoad[protocol] = stats
  415. }
  416. log.LogRawFieldsWithTimestamp(serverLoad)
  417. for region, regionProtocolStats := range regionStats {
  418. serverLoad := LogFields{
  419. "event_name": "server_load",
  420. "region": region,
  421. }
  422. for protocol, stats := range regionProtocolStats {
  423. serverLoad[protocol] = stats
  424. }
  425. log.LogRawFieldsWithTimestamp(serverLoad)
  426. }
  427. }
  428. func logIrregularTunnel(
  429. support *SupportServices,
  430. listenerTunnelProtocol string,
  431. listenerPort int,
  432. peerIP string,
  433. tunnelError error,
  434. logFields LogFields) {
  435. if logFields == nil {
  436. logFields = make(LogFields)
  437. }
  438. logFields["event_name"] = "irregular_tunnel"
  439. logFields["listener_protocol"] = listenerTunnelProtocol
  440. logFields["listener_port_number"] = listenerPort
  441. logFields["tunnel_error"] = tunnelError.Error()
  442. // Note: logging with the "client_" prefix for legacy compatibility; it
  443. // would be more correct to use the prefix "peer_".
  444. support.GeoIPService.Lookup(peerIP).SetClientLogFields(logFields)
  445. log.LogRawFieldsWithTimestamp(logFields)
  446. }
  447. // SupportServices carries common and shared data components
  448. // across different server components. SupportServices implements a
  449. // hot reload of traffic rules, psinet database, and geo IP database
  450. // components, which allows these data components to be refreshed
  451. // without restarting the server process.
  452. type SupportServices struct {
  453. // TODO: make all fields non-exported, none are accessed outside
  454. // of this package.
  455. Config *Config
  456. TrafficRulesSet *TrafficRulesSet
  457. OSLConfig *osl.Config
  458. PsinetDatabase *psinet.Database
  459. GeoIPService *GeoIPService
  460. DNSResolver *DNSResolver
  461. TunnelServer *TunnelServer
  462. PacketTunnelServer *tun.Server
  463. TacticsServer *tactics.Server
  464. Blocklist *Blocklist
  465. PacketManipulator *packetman.Manipulator
  466. ReplayCache *ReplayCache
  467. ServerTacticsParametersCache *ServerTacticsParametersCache
  468. discovery *Discovery
  469. }
  470. // NewSupportServices initializes a new SupportServices.
  471. func NewSupportServices(config *Config) (*SupportServices, error) {
  472. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  473. if err != nil {
  474. return nil, errors.Trace(err)
  475. }
  476. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  477. if err != nil {
  478. return nil, errors.Trace(err)
  479. }
  480. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  481. if err != nil {
  482. return nil, errors.Trace(err)
  483. }
  484. geoIPService, err := NewGeoIPService(config.GeoIPDatabaseFilenames)
  485. if err != nil {
  486. return nil, errors.Trace(err)
  487. }
  488. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  489. if err != nil {
  490. return nil, errors.Trace(err)
  491. }
  492. blocklist, err := NewBlocklist(config.BlocklistFilename)
  493. if err != nil {
  494. return nil, errors.Trace(err)
  495. }
  496. tacticsServer, err := tactics.NewServer(
  497. CommonLogger(log),
  498. getTacticsAPIParameterLogFieldFormatter(),
  499. getTacticsAPIParameterValidator(config),
  500. config.TacticsConfigFilename)
  501. if err != nil {
  502. return nil, errors.Trace(err)
  503. }
  504. support := &SupportServices{
  505. Config: config,
  506. TrafficRulesSet: trafficRulesSet,
  507. OSLConfig: oslConfig,
  508. PsinetDatabase: psinetDatabase,
  509. GeoIPService: geoIPService,
  510. DNSResolver: dnsResolver,
  511. TacticsServer: tacticsServer,
  512. Blocklist: blocklist,
  513. }
  514. support.ReplayCache = NewReplayCache(support)
  515. support.ServerTacticsParametersCache =
  516. NewServerTacticsParametersCache(support)
  517. return support, nil
  518. }
  519. // Reload reinitializes traffic rules, psinet database, and geo IP database
  520. // components. If any component fails to reload, an error is logged and
  521. // Reload proceeds, using the previous state of the component.
  522. func (support *SupportServices) Reload() {
  523. reloaders := append(
  524. []common.Reloader{
  525. support.TrafficRulesSet,
  526. support.OSLConfig,
  527. support.PsinetDatabase,
  528. support.TacticsServer,
  529. support.Blocklist},
  530. support.GeoIPService.Reloaders()...)
  531. reloadDiscovery := func(reloadedTactics bool) {
  532. err := support.discovery.reload(reloadedTactics)
  533. if err != nil {
  534. log.WithTraceFields(
  535. LogFields{"error": errors.Trace(err)}).Warning(
  536. "failed to reload discovery")
  537. return
  538. }
  539. }
  540. // Note: established clients aren't notified when tactics change after a
  541. // reload; new tactics will be obtained on the next client handshake or
  542. // tactics request.
  543. reloadTactics := func() {
  544. // Don't use stale tactics.
  545. support.ReplayCache.Flush()
  546. support.ServerTacticsParametersCache.Flush()
  547. err := support.TunnelServer.ReloadTactics()
  548. if err != nil {
  549. log.WithTraceFields(
  550. LogFields{"error": errors.Trace(err)}).Warning(
  551. "failed to reload tunnel server tactics")
  552. }
  553. if support.Config.RunPacketManipulator {
  554. err := reloadPacketManipulationSpecs(support)
  555. if err != nil {
  556. log.WithTraceFields(
  557. LogFields{"error": errors.Trace(err)}).Warning(
  558. "failed to reload packet manipulation specs")
  559. }
  560. }
  561. reloadDiscovery(true)
  562. }
  563. // Take these actions only after the corresponding Reloader has reloaded.
  564. // In both the traffic rules and OSL cases, there is some impact from state
  565. // reset, so the reset should be avoided where possible.
  566. //
  567. // Note: if both tactics and psinet are reloaded at the same time and
  568. // the discovery strategy tactic has changed, then discovery will be reloaded
  569. // twice.
  570. reloadPostActions := map[common.Reloader]func(){
  571. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  572. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  573. support.TacticsServer: reloadTactics,
  574. support.PsinetDatabase: func() { reloadDiscovery(false) },
  575. }
  576. for _, reloader := range reloaders {
  577. if !reloader.WillReload() {
  578. // Skip logging
  579. continue
  580. }
  581. // "reloaded" flag indicates if file was actually reloaded or ignored
  582. reloaded, err := reloader.Reload()
  583. if reloaded {
  584. if action, ok := reloadPostActions[reloader]; ok {
  585. action()
  586. }
  587. }
  588. if err != nil {
  589. log.WithTraceFields(
  590. LogFields{
  591. "reloader": reloader.LogDescription(),
  592. "error": err}).Error("reload failed")
  593. // Keep running with previous state
  594. } else {
  595. log.WithTraceFields(
  596. LogFields{
  597. "reloader": reloader.LogDescription(),
  598. "reloaded": reloaded}).Info("reload success")
  599. }
  600. }
  601. }