services.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. "math/rand"
  26. "os"
  27. "os/signal"
  28. "path/filepath"
  29. "runtime"
  30. "runtime/pprof"
  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/osl"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  38. )
  39. // RunServices initializes support functions including logging and GeoIP services;
  40. // and then starts the server components and runs them until os.Interrupt or
  41. // os.Kill signals are received. The config determines which components are run.
  42. func RunServices(configJSON []byte) error {
  43. rand.Seed(int64(time.Now().Nanosecond()))
  44. config, err := LoadConfig(configJSON)
  45. if err != nil {
  46. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  47. return common.ContextError(err)
  48. }
  49. err = InitLogging(config)
  50. if err != nil {
  51. log.WithContextFields(LogFields{"error": err}).Error("init logging failed")
  52. return common.ContextError(err)
  53. }
  54. supportServices, err := NewSupportServices(config)
  55. if err != nil {
  56. log.WithContextFields(LogFields{"error": err}).Error("init support services failed")
  57. return common.ContextError(err)
  58. }
  59. log.WithContextFields(*common.GetBuildInfo().ToMap()).Info("startup")
  60. waitGroup := new(sync.WaitGroup)
  61. shutdownBroadcast := make(chan struct{})
  62. errors := make(chan error)
  63. tunnelServer, err := NewTunnelServer(supportServices, shutdownBroadcast)
  64. if err != nil {
  65. log.WithContextFields(LogFields{"error": err}).Error("init tunnel server failed")
  66. return common.ContextError(err)
  67. }
  68. supportServices.TunnelServer = tunnelServer
  69. if config.RunPacketTunnel {
  70. packetTunnelServer, err := tun.NewServer(&tun.ServerConfig{
  71. Logger: CommonLogger(log),
  72. SudoNetworkConfigCommands: config.PacketTunnelSudoNetworkConfigCommands,
  73. GetDNSResolverIPv4Addresses: supportServices.DNSResolver.GetAllIPv4,
  74. GetDNSResolverIPv6Addresses: supportServices.DNSResolver.GetAllIPv6,
  75. EgressInterface: config.PacketTunnelEgressInterface,
  76. DownstreamPacketQueueSize: config.PacketTunnelDownstreamPacketQueueSize,
  77. SessionIdleExpirySeconds: config.PacketTunnelSessionIdleExpirySeconds,
  78. })
  79. if err != nil {
  80. log.WithContextFields(LogFields{"error": err}).Error("init packet tunnel failed")
  81. return common.ContextError(err)
  82. }
  83. supportServices.PacketTunnelServer = packetTunnelServer
  84. }
  85. // After this point, errors should be delivered to the "errors" channel and
  86. // orderly shutdown should flow through to the end of the function to ensure
  87. // all workers are synchronously stopped.
  88. if config.RunPacketTunnel {
  89. supportServices.PacketTunnelServer.Start()
  90. waitGroup.Add(1)
  91. go func() {
  92. defer waitGroup.Done()
  93. <-shutdownBroadcast
  94. supportServices.PacketTunnelServer.Stop()
  95. }()
  96. }
  97. if config.RunLoadMonitor() {
  98. waitGroup.Add(1)
  99. go func() {
  100. waitGroup.Done()
  101. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  102. defer ticker.Stop()
  103. for {
  104. select {
  105. case <-shutdownBroadcast:
  106. return
  107. case <-ticker.C:
  108. logServerLoad(tunnelServer)
  109. }
  110. }
  111. }()
  112. }
  113. if config.RunPeriodicGarbageCollection() {
  114. waitGroup.Add(1)
  115. go func() {
  116. waitGroup.Done()
  117. ticker := time.NewTicker(time.Duration(config.PeriodicGarbageCollectionSeconds) * time.Second)
  118. defer ticker.Stop()
  119. for {
  120. select {
  121. case <-shutdownBroadcast:
  122. return
  123. case <-ticker.C:
  124. runtime.GC()
  125. }
  126. }
  127. }()
  128. }
  129. if config.RunWebServer() {
  130. waitGroup.Add(1)
  131. go func() {
  132. defer waitGroup.Done()
  133. err := RunWebServer(supportServices, shutdownBroadcast)
  134. select {
  135. case errors <- err:
  136. default:
  137. }
  138. }()
  139. }
  140. // The tunnel server is always run; it launches multiple
  141. // listeners, depending on which tunnel protocols are enabled.
  142. waitGroup.Add(1)
  143. go func() {
  144. defer waitGroup.Done()
  145. err := tunnelServer.Run()
  146. select {
  147. case errors <- err:
  148. default:
  149. }
  150. }()
  151. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  152. // to complete, as it may be sleeping while running a "block" or
  153. // CPU profile.
  154. signalProcessProfiles := make(chan struct{}, 1)
  155. go func() {
  156. for {
  157. select {
  158. case <-signalProcessProfiles:
  159. outputProcessProfiles(supportServices.Config)
  160. case <-shutdownBroadcast:
  161. return
  162. }
  163. }
  164. }()
  165. // In addition to the actual signal handling here, there is
  166. // a list of signals that need to be passed through panicwrap
  167. // in 'github.com/Psiphon-Labs/psiphon-tunnel-core/Server/main.go'
  168. // where 'panicwrap.Wrap' is called. The handled signals below, and the
  169. // list there must be kept in sync to ensure proper signal handling
  170. // An OS signal triggers an orderly shutdown
  171. systemStopSignal := make(chan os.Signal, 1)
  172. signal.Notify(systemStopSignal, os.Interrupt, os.Kill, syscall.SIGTERM)
  173. // SIGUSR1 triggers a reload of support services
  174. reloadSupportServicesSignal := make(chan os.Signal, 1)
  175. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  176. // SIGUSR2 triggers an immediate load log and optional process profile output
  177. logServerLoadSignal := make(chan os.Signal, 1)
  178. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  179. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  180. stopEstablishingTunnelsSignal := make(chan os.Signal, 1)
  181. signal.Notify(stopEstablishingTunnelsSignal, syscall.SIGTSTP)
  182. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  183. resumeEstablishingTunnelsSignal := make(chan os.Signal, 1)
  184. signal.Notify(resumeEstablishingTunnelsSignal, syscall.SIGCONT)
  185. err = nil
  186. loop:
  187. for {
  188. select {
  189. case <-stopEstablishingTunnelsSignal:
  190. tunnelServer.SetEstablishTunnels(false)
  191. case <-resumeEstablishingTunnelsSignal:
  192. tunnelServer.SetEstablishTunnels(true)
  193. case <-reloadSupportServicesSignal:
  194. supportServices.Reload()
  195. case <-logServerLoadSignal:
  196. // Signal profiles writes first to ensure some diagnostics are
  197. // available in case logServerLoad hangs (which has happened
  198. // in the past due to a deadlock bug).
  199. select {
  200. case signalProcessProfiles <- *new(struct{}):
  201. default:
  202. }
  203. logServerLoad(tunnelServer)
  204. case <-systemStopSignal:
  205. log.WithContext().Info("shutdown by system")
  206. break loop
  207. case err = <-errors:
  208. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  209. break loop
  210. }
  211. }
  212. close(shutdownBroadcast)
  213. waitGroup.Wait()
  214. return err
  215. }
  216. func getRuntimeMetrics() LogFields {
  217. numGoroutine := runtime.NumGoroutine()
  218. var memStats runtime.MemStats
  219. runtime.ReadMemStats(&memStats)
  220. lastGC := ""
  221. if memStats.LastGC > 0 {
  222. lastGC = time.Unix(0, int64(memStats.LastGC)).UTC().Format(time.RFC3339)
  223. }
  224. return LogFields{
  225. "num_goroutine": numGoroutine,
  226. "heap_alloc": memStats.HeapAlloc,
  227. "heap_sys": memStats.HeapSys,
  228. "heap_idle": memStats.HeapIdle,
  229. "heap_inuse": memStats.HeapInuse,
  230. "heap_released": memStats.HeapReleased,
  231. "heap_objects": memStats.HeapObjects,
  232. "num_gc": memStats.NumGC,
  233. "num_forced_gc": memStats.NumForcedGC,
  234. "last_gc": lastGC,
  235. }
  236. }
  237. func outputProcessProfiles(config *Config) {
  238. log.WithContextFields(getRuntimeMetrics()).Info("runtime_metrics")
  239. if config.ProcessProfileOutputDirectory != "" {
  240. openProfileFile := func(profileName string) *os.File {
  241. fileName := filepath.Join(
  242. config.ProcessProfileOutputDirectory, profileName+".profile")
  243. file, err := os.OpenFile(
  244. fileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  245. if err != nil {
  246. log.WithContextFields(
  247. LogFields{
  248. "error": err,
  249. "fileName": fileName}).Error("open profile file failed")
  250. return nil
  251. }
  252. return file
  253. }
  254. writeProfile := func(profileName string) {
  255. file := openProfileFile(profileName)
  256. if file == nil {
  257. return
  258. }
  259. err := pprof.Lookup(profileName).WriteTo(file, 1)
  260. file.Close()
  261. if err != nil {
  262. log.WithContextFields(
  263. LogFields{
  264. "error": err,
  265. "profileName": profileName}).Error("write profile failed")
  266. }
  267. }
  268. // TODO: capture https://golang.org/pkg/runtime/debug/#WriteHeapDump?
  269. // May not be useful in its current state, as per:
  270. // https://groups.google.com/forum/#!topic/golang-dev/cYAkuU45Qyw
  271. // Write goroutine, heap, and threadcreate profiles
  272. // https://golang.org/pkg/runtime/pprof/#Profile
  273. writeProfile("goroutine")
  274. writeProfile("heap")
  275. writeProfile("threadcreate")
  276. // Write block profile (after sampling)
  277. // https://golang.org/pkg/runtime/pprof/#Profile
  278. if config.ProcessBlockProfileDurationSeconds > 0 {
  279. log.WithContext().Info("start block profiling")
  280. runtime.SetBlockProfileRate(1)
  281. time.Sleep(
  282. time.Duration(config.ProcessBlockProfileDurationSeconds) * time.Second)
  283. runtime.SetBlockProfileRate(0)
  284. log.WithContext().Info("end block profiling")
  285. writeProfile("block")
  286. }
  287. // Write CPU profile (after sampling)
  288. // https://golang.org/pkg/runtime/pprof/#StartCPUProfile
  289. if config.ProcessCPUProfileDurationSeconds > 0 {
  290. file := openProfileFile("cpu")
  291. if file != nil {
  292. log.WithContext().Info("start cpu profiling")
  293. err := pprof.StartCPUProfile(file)
  294. if err != nil {
  295. log.WithContextFields(
  296. LogFields{"error": err}).Error("StartCPUProfile failed")
  297. } else {
  298. time.Sleep(time.Duration(
  299. config.ProcessCPUProfileDurationSeconds) * time.Second)
  300. pprof.StopCPUProfile()
  301. log.WithContext().Info("end cpu profiling")
  302. }
  303. file.Close()
  304. }
  305. }
  306. }
  307. }
  308. func logServerLoad(server *TunnelServer) {
  309. protocolStats, regionStats := server.GetLoadStats()
  310. serverLoad := getRuntimeMetrics()
  311. serverLoad["event_name"] = "server_load"
  312. serverLoad["establish_tunnels"] = server.GetEstablishTunnels()
  313. for protocol, stats := range protocolStats {
  314. serverLoad[protocol] = stats
  315. }
  316. log.LogRawFieldsWithTimestamp(serverLoad)
  317. for region, regionProtocolStats := range regionStats {
  318. serverLoad := LogFields{
  319. "event_name": "server_load",
  320. "region": region,
  321. }
  322. for protocol, stats := range regionProtocolStats {
  323. serverLoad[protocol] = stats
  324. }
  325. log.LogRawFieldsWithTimestamp(serverLoad)
  326. }
  327. }
  328. // SupportServices carries common and shared data components
  329. // across different server components. SupportServices implements a
  330. // hot reload of traffic rules, psinet database, and geo IP database
  331. // components, which allows these data components to be refreshed
  332. // without restarting the server process.
  333. type SupportServices struct {
  334. Config *Config
  335. TrafficRulesSet *TrafficRulesSet
  336. OSLConfig *osl.Config
  337. PsinetDatabase *psinet.Database
  338. GeoIPService *GeoIPService
  339. DNSResolver *DNSResolver
  340. TunnelServer *TunnelServer
  341. PacketTunnelServer *tun.Server
  342. }
  343. // NewSupportServices initializes a new SupportServices.
  344. func NewSupportServices(config *Config) (*SupportServices, error) {
  345. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  346. if err != nil {
  347. return nil, common.ContextError(err)
  348. }
  349. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  350. if err != nil {
  351. return nil, common.ContextError(err)
  352. }
  353. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  354. if err != nil {
  355. return nil, common.ContextError(err)
  356. }
  357. geoIPService, err := NewGeoIPService(
  358. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  359. if err != nil {
  360. return nil, common.ContextError(err)
  361. }
  362. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  363. if err != nil {
  364. return nil, common.ContextError(err)
  365. }
  366. return &SupportServices{
  367. Config: config,
  368. TrafficRulesSet: trafficRulesSet,
  369. OSLConfig: oslConfig,
  370. PsinetDatabase: psinetDatabase,
  371. GeoIPService: geoIPService,
  372. DNSResolver: dnsResolver,
  373. }, nil
  374. }
  375. // Reload reinitializes traffic rules, psinet database, and geo IP database
  376. // components. If any component fails to reload, an error is logged and
  377. // Reload proceeds, using the previous state of the component.
  378. func (support *SupportServices) Reload() {
  379. reloaders := append(
  380. []common.Reloader{
  381. support.TrafficRulesSet,
  382. support.OSLConfig,
  383. support.PsinetDatabase},
  384. support.GeoIPService.Reloaders()...)
  385. // Take these actions only after the corresponding Reloader has reloaded.
  386. // In both the traffic rules and OSL cases, there is some impact from state
  387. // reset, so the reset should be avoided where possible.
  388. reloadPostActions := map[common.Reloader]func(){
  389. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  390. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  391. }
  392. for _, reloader := range reloaders {
  393. if !reloader.WillReload() {
  394. // Skip logging
  395. continue
  396. }
  397. // "reloaded" flag indicates if file was actually reloaded or ignored
  398. reloaded, err := reloader.Reload()
  399. if reloaded {
  400. if action, ok := reloadPostActions[reloader]; ok {
  401. action()
  402. }
  403. }
  404. if err != nil {
  405. log.WithContextFields(
  406. LogFields{
  407. "reloader": reloader.LogDescription(),
  408. "error": err}).Error("reload failed")
  409. // Keep running with previous state
  410. } else {
  411. log.WithContextFields(
  412. LogFields{
  413. "reloader": reloader.LogDescription(),
  414. "reloaded": reloaded}).Info("reload success")
  415. }
  416. }
  417. }