services.go 11 KB

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