services.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. "os"
  26. "os/signal"
  27. "path/filepath"
  28. "runtime"
  29. "runtime/pprof"
  30. "sync"
  31. "syscall"
  32. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  35. )
  36. // RunServices initializes support functions including logging and GeoIP services;
  37. // and then starts the server components and runs them until os.Interrupt or
  38. // os.Kill signals are received. The config determines which components are run.
  39. func RunServices(configJSON []byte) error {
  40. config, err := LoadConfig(configJSON)
  41. if err != nil {
  42. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  43. return common.ContextError(err)
  44. }
  45. err = InitLogging(config)
  46. if err != nil {
  47. log.WithContextFields(LogFields{"error": err}).Error("init logging failed")
  48. return common.ContextError(err)
  49. }
  50. supportServices, err := NewSupportServices(config)
  51. if err != nil {
  52. log.WithContextFields(LogFields{"error": err}).Error("init support services failed")
  53. return common.ContextError(err)
  54. }
  55. log.WithContextFields(*common.GetBuildInfo().ToMap()).Info("startup")
  56. waitGroup := new(sync.WaitGroup)
  57. shutdownBroadcast := make(chan struct{})
  58. errors := make(chan error)
  59. tunnelServer, err := NewTunnelServer(supportServices, shutdownBroadcast)
  60. if err != nil {
  61. log.WithContextFields(LogFields{"error": err}).Error("init tunnel server failed")
  62. return common.ContextError(err)
  63. }
  64. supportServices.TunnelServer = tunnelServer
  65. if config.RunLoadMonitor() {
  66. waitGroup.Add(1)
  67. go func() {
  68. waitGroup.Done()
  69. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  70. defer ticker.Stop()
  71. for {
  72. select {
  73. case <-shutdownBroadcast:
  74. return
  75. case <-ticker.C:
  76. logServerLoad(tunnelServer)
  77. }
  78. }
  79. }()
  80. }
  81. if config.RunWebServer() {
  82. waitGroup.Add(1)
  83. go func() {
  84. defer waitGroup.Done()
  85. err := RunWebServer(supportServices, shutdownBroadcast)
  86. select {
  87. case errors <- err:
  88. default:
  89. }
  90. }()
  91. }
  92. // The tunnel server is always run; it launches multiple
  93. // listeners, depending on which tunnel protocols are enabled.
  94. waitGroup.Add(1)
  95. go func() {
  96. defer waitGroup.Done()
  97. err := tunnelServer.Run()
  98. select {
  99. case errors <- err:
  100. default:
  101. }
  102. }()
  103. // Shutdown doesn't wait for the outputProcessProfiles goroutine
  104. // to complete, as it may be sleeping while running a "block" or
  105. // CPU profile.
  106. signalProcessProfiles := make(chan struct{}, 1)
  107. go func() {
  108. for {
  109. select {
  110. case <-signalProcessProfiles:
  111. outputProcessProfiles(supportServices.Config)
  112. case <-shutdownBroadcast:
  113. return
  114. }
  115. }
  116. }()
  117. // An OS signal triggers an orderly shutdown
  118. systemStopSignal := make(chan os.Signal, 1)
  119. signal.Notify(systemStopSignal, os.Interrupt, os.Kill, syscall.SIGTERM)
  120. // SIGUSR1 triggers a reload of support services
  121. reloadSupportServicesSignal := make(chan os.Signal, 1)
  122. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  123. // SIGUSR2 triggers an immediate load log and optional process profile output
  124. logServerLoadSignal := make(chan os.Signal, 1)
  125. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  126. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  127. stopEstablishingTunnelsSignal := make(chan os.Signal, 1)
  128. signal.Notify(stopEstablishingTunnelsSignal, syscall.SIGTSTP)
  129. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  130. resumeEstablishingTunnelsSignal := make(chan os.Signal, 1)
  131. signal.Notify(resumeEstablishingTunnelsSignal, syscall.SIGCONT)
  132. err = nil
  133. loop:
  134. for {
  135. select {
  136. case <-stopEstablishingTunnelsSignal:
  137. tunnelServer.SetEstablishTunnels(false)
  138. case <-resumeEstablishingTunnelsSignal:
  139. tunnelServer.SetEstablishTunnels(true)
  140. case <-reloadSupportServicesSignal:
  141. supportServices.Reload()
  142. // Reset traffic rules for established clients to reflect reloaded config
  143. // TODO: only update when traffic rules config has changed
  144. tunnelServer.ResetAllClientTrafficRules()
  145. case <-logServerLoadSignal:
  146. // Signal profiles writes first to ensure some diagnostics are
  147. // available in case logServerLoad hangs (which has happened
  148. // in the past due to a deadlock bug).
  149. select {
  150. case signalProcessProfiles <- *new(struct{}):
  151. default:
  152. }
  153. logServerLoad(tunnelServer)
  154. case <-systemStopSignal:
  155. log.WithContext().Info("shutdown by system")
  156. break loop
  157. case err = <-errors:
  158. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  159. break loop
  160. }
  161. }
  162. close(shutdownBroadcast)
  163. waitGroup.Wait()
  164. return err
  165. }
  166. func outputProcessProfiles(config *Config) {
  167. if config.ProcessProfileOutputDirectory != "" {
  168. openProfileFile := func(profileName string) *os.File {
  169. fileName := filepath.Join(
  170. config.ProcessProfileOutputDirectory, profileName+".profile")
  171. file, err := os.OpenFile(
  172. fileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  173. if err != nil {
  174. log.WithContextFields(
  175. LogFields{
  176. "error": err,
  177. "fileName": fileName}).Error("open profile file failed")
  178. return nil
  179. }
  180. return file
  181. }
  182. writeProfile := func(profileName string) {
  183. file := openProfileFile(profileName)
  184. if file == nil {
  185. return
  186. }
  187. err := pprof.Lookup(profileName).WriteTo(file, 1)
  188. file.Close()
  189. if err != nil {
  190. log.WithContextFields(
  191. LogFields{
  192. "error": err,
  193. "profileName": profileName}).Error("write profile failed")
  194. }
  195. }
  196. // TODO: capture https://golang.org/pkg/runtime/debug/#WriteHeapDump?
  197. // May not be useful in its current state, as per:
  198. // https://groups.google.com/forum/#!topic/golang-dev/cYAkuU45Qyw
  199. // Write goroutine, heap, and threadcreate profiles
  200. // https://golang.org/pkg/runtime/pprof/#Profile
  201. writeProfile("goroutine")
  202. writeProfile("heap")
  203. writeProfile("threadcreate")
  204. // Write block profile (after sampling)
  205. // https://golang.org/pkg/runtime/pprof/#Profile
  206. if config.ProcessBlockProfileDurationSeconds > 0 {
  207. log.WithContext().Info("start block profiling")
  208. runtime.SetBlockProfileRate(1)
  209. time.Sleep(
  210. time.Duration(config.ProcessBlockProfileDurationSeconds) * time.Second)
  211. runtime.SetBlockProfileRate(0)
  212. log.WithContext().Info("end block profiling")
  213. writeProfile("block")
  214. }
  215. // Write CPU profile (after sampling)
  216. // https://golang.org/pkg/runtime/pprof/#StartCPUProfile
  217. if config.ProcessCPUProfileDurationSeconds > 0 {
  218. file := openProfileFile("cpu")
  219. if file != nil {
  220. log.WithContext().Info("start cpu profiling")
  221. err := pprof.StartCPUProfile(file)
  222. if err != nil {
  223. log.WithContextFields(
  224. LogFields{"error": err}).Error("StartCPUProfile failed")
  225. } else {
  226. time.Sleep(time.Duration(
  227. config.ProcessCPUProfileDurationSeconds) * time.Second)
  228. pprof.StopCPUProfile()
  229. log.WithContext().Info("end cpu profiling")
  230. }
  231. file.Close()
  232. }
  233. }
  234. }
  235. }
  236. func logServerLoad(server *TunnelServer) {
  237. // golang runtime stats
  238. var memStats runtime.MemStats
  239. runtime.ReadMemStats(&memStats)
  240. fields := LogFields{
  241. "event_name": "server_load",
  242. "build_rev": common.GetBuildInfo().BuildRev,
  243. "host_id": server.sshServer.support.Config.HostID,
  244. "num_goroutine": runtime.NumGoroutine(),
  245. "mem_stats": map[string]interface{}{
  246. "alloc": memStats.Alloc,
  247. "total_alloc": memStats.TotalAlloc,
  248. "sys": memStats.Sys,
  249. "pause_total_ns": memStats.PauseTotalNs,
  250. "pause_ns": memStats.PauseNs,
  251. "num_gc": memStats.NumGC,
  252. "gc_cpu_fraction": memStats.GCCPUFraction,
  253. },
  254. }
  255. // tunnel server stats
  256. fields["establish_tunnels"] = server.GetEstablishTunnels()
  257. for tunnelProtocol, stats := range server.GetLoadStats() {
  258. fields[tunnelProtocol] = stats
  259. }
  260. log.LogRawFieldsWithTimestamp(fields)
  261. }
  262. // SupportServices carries common and shared data components
  263. // across different server components. SupportServices implements a
  264. // hot reload of traffic rules, psinet database, and geo IP database
  265. // components, which allows these data components to be refreshed
  266. // without restarting the server process.
  267. type SupportServices struct {
  268. Config *Config
  269. TrafficRulesSet *TrafficRulesSet
  270. PsinetDatabase *psinet.Database
  271. GeoIPService *GeoIPService
  272. DNSResolver *DNSResolver
  273. TunnelServer *TunnelServer
  274. }
  275. // NewSupportServices initializes a new SupportServices.
  276. func NewSupportServices(config *Config) (*SupportServices, error) {
  277. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  278. if err != nil {
  279. return nil, common.ContextError(err)
  280. }
  281. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  282. if err != nil {
  283. return nil, common.ContextError(err)
  284. }
  285. geoIPService, err := NewGeoIPService(
  286. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  287. if err != nil {
  288. return nil, common.ContextError(err)
  289. }
  290. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  291. if err != nil {
  292. return nil, common.ContextError(err)
  293. }
  294. return &SupportServices{
  295. Config: config,
  296. TrafficRulesSet: trafficRulesSet,
  297. PsinetDatabase: psinetDatabase,
  298. GeoIPService: geoIPService,
  299. DNSResolver: dnsResolver,
  300. }, nil
  301. }
  302. // Reload reinitializes traffic rules, psinet database, and geo IP database
  303. // components. If any component fails to reload, an error is logged and
  304. // Reload proceeds, using the previous state of the component.
  305. //
  306. // Limitation: reload of traffic rules currently doesn't apply to existing,
  307. // established clients.
  308. func (support *SupportServices) Reload() {
  309. reloaders := append(
  310. []common.Reloader{support.TrafficRulesSet, support.PsinetDatabase},
  311. support.GeoIPService.Reloaders()...)
  312. for _, reloader := range reloaders {
  313. if !reloader.WillReload() {
  314. // Skip logging
  315. continue
  316. }
  317. // "reloaded" flag indicates if file was actually reloaded or ignored
  318. reloaded, err := reloader.Reload()
  319. if err != nil {
  320. log.WithContextFields(
  321. LogFields{
  322. "reloader": reloader.LogDescription(),
  323. "error": err}).Error("reload failed")
  324. // Keep running with previous state
  325. } else {
  326. log.WithContextFields(
  327. LogFields{
  328. "reloader": reloader.LogDescription(),
  329. "reloaded": reloaded}).Info("reload success")
  330. }
  331. }
  332. }