services.go 12 KB

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