services.go 12 KB

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