services.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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.RunWebServer() {
  114. waitGroup.Add(1)
  115. go func() {
  116. defer waitGroup.Done()
  117. err := RunWebServer(supportServices, shutdownBroadcast)
  118. select {
  119. case errors <- err:
  120. default:
  121. }
  122. }()
  123. }
  124. // The tunnel server is always run; it launches multiple
  125. // listeners, depending on which tunnel protocols are enabled.
  126. waitGroup.Add(1)
  127. go func() {
  128. defer waitGroup.Done()
  129. err := tunnelServer.Run()
  130. select {
  131. case errors <- err:
  132. default:
  133. }
  134. }()
  135. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  136. // to complete, as it may be sleeping while running a "block" or
  137. // CPU profile.
  138. signalProcessProfiles := make(chan struct{}, 1)
  139. go func() {
  140. for {
  141. select {
  142. case <-signalProcessProfiles:
  143. outputProcessProfiles(supportServices.Config)
  144. case <-shutdownBroadcast:
  145. return
  146. }
  147. }
  148. }()
  149. // In addition to the actual signal handling here, there is
  150. // a list of signals that need to be passed through panicwrap
  151. // in 'github.com/Psiphon-Labs/psiphon-tunnel-core/Server/main.go'
  152. // where 'panicwrap.Wrap' is called. The handled signals below, and the
  153. // list there must be kept in sync to ensure proper signal handling
  154. // An OS signal triggers an orderly shutdown
  155. systemStopSignal := make(chan os.Signal, 1)
  156. signal.Notify(systemStopSignal, os.Interrupt, os.Kill, syscall.SIGTERM)
  157. // SIGUSR1 triggers a reload of support services
  158. reloadSupportServicesSignal := make(chan os.Signal, 1)
  159. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  160. // SIGUSR2 triggers an immediate load log and optional process profile output
  161. logServerLoadSignal := make(chan os.Signal, 1)
  162. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  163. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  164. stopEstablishingTunnelsSignal := make(chan os.Signal, 1)
  165. signal.Notify(stopEstablishingTunnelsSignal, syscall.SIGTSTP)
  166. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  167. resumeEstablishingTunnelsSignal := make(chan os.Signal, 1)
  168. signal.Notify(resumeEstablishingTunnelsSignal, syscall.SIGCONT)
  169. err = nil
  170. loop:
  171. for {
  172. select {
  173. case <-stopEstablishingTunnelsSignal:
  174. tunnelServer.SetEstablishTunnels(false)
  175. case <-resumeEstablishingTunnelsSignal:
  176. tunnelServer.SetEstablishTunnels(true)
  177. case <-reloadSupportServicesSignal:
  178. supportServices.Reload()
  179. case <-logServerLoadSignal:
  180. // Signal profiles writes first to ensure some diagnostics are
  181. // available in case logServerLoad hangs (which has happened
  182. // in the past due to a deadlock bug).
  183. select {
  184. case signalProcessProfiles <- *new(struct{}):
  185. default:
  186. }
  187. logServerLoad(tunnelServer)
  188. case <-systemStopSignal:
  189. log.WithContext().Info("shutdown by system")
  190. break loop
  191. case err = <-errors:
  192. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  193. break loop
  194. }
  195. }
  196. close(shutdownBroadcast)
  197. waitGroup.Wait()
  198. return err
  199. }
  200. func outputProcessProfiles(config *Config) {
  201. var memStats runtime.MemStats
  202. runtime.ReadMemStats(&memStats)
  203. log.WithContextFields(
  204. LogFields{
  205. "num_goroutine": runtime.NumGoroutine(),
  206. "alloc": memStats.Alloc,
  207. "total_alloc": memStats.TotalAlloc,
  208. "sys": memStats.Sys,
  209. "pause_total_ns": memStats.PauseTotalNs,
  210. "pause_ns": memStats.PauseNs,
  211. "num_gc": memStats.NumGC,
  212. "gc_cpu_fraction": memStats.GCCPUFraction,
  213. }).Info("runtime_stats")
  214. if config.ProcessProfileOutputDirectory != "" {
  215. openProfileFile := func(profileName string) *os.File {
  216. fileName := filepath.Join(
  217. config.ProcessProfileOutputDirectory, profileName+".profile")
  218. file, err := os.OpenFile(
  219. fileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  220. if err != nil {
  221. log.WithContextFields(
  222. LogFields{
  223. "error": err,
  224. "fileName": fileName}).Error("open profile file failed")
  225. return nil
  226. }
  227. return file
  228. }
  229. writeProfile := func(profileName string) {
  230. file := openProfileFile(profileName)
  231. if file == nil {
  232. return
  233. }
  234. err := pprof.Lookup(profileName).WriteTo(file, 1)
  235. file.Close()
  236. if err != nil {
  237. log.WithContextFields(
  238. LogFields{
  239. "error": err,
  240. "profileName": profileName}).Error("write profile failed")
  241. }
  242. }
  243. // TODO: capture https://golang.org/pkg/runtime/debug/#WriteHeapDump?
  244. // May not be useful in its current state, as per:
  245. // https://groups.google.com/forum/#!topic/golang-dev/cYAkuU45Qyw
  246. // Write goroutine, heap, and threadcreate profiles
  247. // https://golang.org/pkg/runtime/pprof/#Profile
  248. writeProfile("goroutine")
  249. writeProfile("heap")
  250. writeProfile("threadcreate")
  251. // Write block profile (after sampling)
  252. // https://golang.org/pkg/runtime/pprof/#Profile
  253. if config.ProcessBlockProfileDurationSeconds > 0 {
  254. log.WithContext().Info("start block profiling")
  255. runtime.SetBlockProfileRate(1)
  256. time.Sleep(
  257. time.Duration(config.ProcessBlockProfileDurationSeconds) * time.Second)
  258. runtime.SetBlockProfileRate(0)
  259. log.WithContext().Info("end block profiling")
  260. writeProfile("block")
  261. }
  262. // Write CPU profile (after sampling)
  263. // https://golang.org/pkg/runtime/pprof/#StartCPUProfile
  264. if config.ProcessCPUProfileDurationSeconds > 0 {
  265. file := openProfileFile("cpu")
  266. if file != nil {
  267. log.WithContext().Info("start cpu profiling")
  268. err := pprof.StartCPUProfile(file)
  269. if err != nil {
  270. log.WithContextFields(
  271. LogFields{"error": err}).Error("StartCPUProfile failed")
  272. } else {
  273. time.Sleep(time.Duration(
  274. config.ProcessCPUProfileDurationSeconds) * time.Second)
  275. pprof.StopCPUProfile()
  276. log.WithContext().Info("end cpu profiling")
  277. }
  278. file.Close()
  279. }
  280. }
  281. }
  282. }
  283. func logServerLoad(server *TunnelServer) {
  284. protocolStats, regionStats := server.GetLoadStats()
  285. serverLoad := LogFields{
  286. "event_name": "server_load",
  287. }
  288. for protocol, stats := range protocolStats {
  289. serverLoad[protocol] = stats
  290. }
  291. serverLoad["establish_tunnels"] = server.GetEstablishTunnels()
  292. log.LogRawFieldsWithTimestamp(serverLoad)
  293. for region, regionProtocolStats := range regionStats {
  294. serverLoad := LogFields{
  295. "event_name": "server_load",
  296. "region": region,
  297. }
  298. for protocol, stats := range regionProtocolStats {
  299. serverLoad[protocol] = stats
  300. }
  301. log.LogRawFieldsWithTimestamp(serverLoad)
  302. }
  303. }
  304. // SupportServices carries common and shared data components
  305. // across different server components. SupportServices implements a
  306. // hot reload of traffic rules, psinet database, and geo IP database
  307. // components, which allows these data components to be refreshed
  308. // without restarting the server process.
  309. type SupportServices struct {
  310. Config *Config
  311. TrafficRulesSet *TrafficRulesSet
  312. OSLConfig *osl.Config
  313. PsinetDatabase *psinet.Database
  314. GeoIPService *GeoIPService
  315. DNSResolver *DNSResolver
  316. TunnelServer *TunnelServer
  317. PacketTunnelServer *tun.Server
  318. }
  319. // NewSupportServices initializes a new SupportServices.
  320. func NewSupportServices(config *Config) (*SupportServices, error) {
  321. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  322. if err != nil {
  323. return nil, common.ContextError(err)
  324. }
  325. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  326. if err != nil {
  327. return nil, common.ContextError(err)
  328. }
  329. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  330. if err != nil {
  331. return nil, common.ContextError(err)
  332. }
  333. geoIPService, err := NewGeoIPService(
  334. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  335. if err != nil {
  336. return nil, common.ContextError(err)
  337. }
  338. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  339. if err != nil {
  340. return nil, common.ContextError(err)
  341. }
  342. return &SupportServices{
  343. Config: config,
  344. TrafficRulesSet: trafficRulesSet,
  345. OSLConfig: oslConfig,
  346. PsinetDatabase: psinetDatabase,
  347. GeoIPService: geoIPService,
  348. DNSResolver: dnsResolver,
  349. }, nil
  350. }
  351. // Reload reinitializes traffic rules, psinet database, and geo IP database
  352. // components. If any component fails to reload, an error is logged and
  353. // Reload proceeds, using the previous state of the component.
  354. func (support *SupportServices) Reload() {
  355. reloaders := append(
  356. []common.Reloader{
  357. support.TrafficRulesSet,
  358. support.OSLConfig,
  359. support.PsinetDatabase},
  360. support.GeoIPService.Reloaders()...)
  361. // Take these actions only after the corresponding Reloader has reloaded.
  362. // In both the traffic rules and OSL cases, there is some impact from state
  363. // reset, so the reset should be avoided where possible.
  364. reloadPostActions := map[common.Reloader]func(){
  365. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  366. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  367. }
  368. for _, reloader := range reloaders {
  369. if !reloader.WillReload() {
  370. // Skip logging
  371. continue
  372. }
  373. // "reloaded" flag indicates if file was actually reloaded or ignored
  374. reloaded, err := reloader.Reload()
  375. if reloaded {
  376. if action, ok := reloadPostActions[reloader]; ok {
  377. action()
  378. }
  379. }
  380. if err != nil {
  381. log.WithContextFields(
  382. LogFields{
  383. "reloader": reloader.LogDescription(),
  384. "error": err}).Error("reload failed")
  385. // Keep running with previous state
  386. } else {
  387. log.WithContextFields(
  388. LogFields{
  389. "reloader": reloader.LogDescription(),
  390. "reloaded": reloaded}).Info("reload success")
  391. }
  392. }
  393. }