services.go 13 KB

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