services.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. // An OS signal triggers an orderly shutdown
  121. systemStopSignal := make(chan os.Signal, 1)
  122. signal.Notify(systemStopSignal, os.Interrupt, os.Kill, syscall.SIGTERM)
  123. // SIGUSR1 triggers a reload of support services
  124. reloadSupportServicesSignal := make(chan os.Signal, 1)
  125. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  126. // SIGUSR2 triggers an immediate load log and optional process profile output
  127. logServerLoadSignal := make(chan os.Signal, 1)
  128. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  129. // SIGTSTP triggers tunnelServer to stop establishing new tunnels
  130. stopEstablishingTunnelsSignal := make(chan os.Signal, 1)
  131. signal.Notify(stopEstablishingTunnelsSignal, syscall.SIGTSTP)
  132. // SIGCONT triggers tunnelServer to resume establishing new tunnels
  133. resumeEstablishingTunnelsSignal := make(chan os.Signal, 1)
  134. signal.Notify(resumeEstablishingTunnelsSignal, syscall.SIGCONT)
  135. err = nil
  136. loop:
  137. for {
  138. select {
  139. case <-stopEstablishingTunnelsSignal:
  140. tunnelServer.SetEstablishTunnels(false)
  141. case <-resumeEstablishingTunnelsSignal:
  142. tunnelServer.SetEstablishTunnels(true)
  143. case <-reloadSupportServicesSignal:
  144. supportServices.Reload()
  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. OSLConfig *osl.Config
  271. PsinetDatabase *psinet.Database
  272. GeoIPService *GeoIPService
  273. DNSResolver *DNSResolver
  274. TunnelServer *TunnelServer
  275. }
  276. // NewSupportServices initializes a new SupportServices.
  277. func NewSupportServices(config *Config) (*SupportServices, error) {
  278. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  279. if err != nil {
  280. return nil, common.ContextError(err)
  281. }
  282. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  283. if err != nil {
  284. return nil, common.ContextError(err)
  285. }
  286. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  287. if err != nil {
  288. return nil, common.ContextError(err)
  289. }
  290. geoIPService, err := NewGeoIPService(
  291. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  292. if err != nil {
  293. return nil, common.ContextError(err)
  294. }
  295. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  296. if err != nil {
  297. return nil, common.ContextError(err)
  298. }
  299. return &SupportServices{
  300. Config: config,
  301. TrafficRulesSet: trafficRulesSet,
  302. OSLConfig: oslConfig,
  303. PsinetDatabase: psinetDatabase,
  304. GeoIPService: geoIPService,
  305. DNSResolver: dnsResolver,
  306. }, nil
  307. }
  308. // Reload reinitializes traffic rules, psinet database, and geo IP database
  309. // components. If any component fails to reload, an error is logged and
  310. // Reload proceeds, using the previous state of the component.
  311. func (support *SupportServices) Reload() {
  312. reloaders := append(
  313. []common.Reloader{
  314. support.TrafficRulesSet,
  315. support.OSLConfig,
  316. support.PsinetDatabase},
  317. support.GeoIPService.Reloaders()...)
  318. // Take these actions only after the corresponding Reloader has reloaded.
  319. // In both the traffic rules and OSL cases, there is some impact from state
  320. // reset, so the reset should be avoided where possible.
  321. reloadPostActions := map[common.Reloader]func(){
  322. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  323. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  324. }
  325. for _, reloader := range reloaders {
  326. if !reloader.WillReload() {
  327. // Skip logging
  328. continue
  329. }
  330. // "reloaded" flag indicates if file was actually reloaded or ignored
  331. reloaded, err := reloader.Reload()
  332. if reloaded {
  333. if action, ok := reloadPostActions[reloader]; ok {
  334. action()
  335. }
  336. }
  337. if err != nil {
  338. log.WithContextFields(
  339. LogFields{
  340. "reloader": reloader.LogDescription(),
  341. "error": err}).Error("reload failed")
  342. // Keep running with previous state
  343. } else {
  344. log.WithContextFields(
  345. LogFields{
  346. "reloader": reloader.LogDescription(),
  347. "reloaded": reloaded}).Info("reload success")
  348. }
  349. }
  350. }