services.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. if config.ProcessProfileOutputDirectory != "" {
  173. openProfileFile := func(profileName string) *os.File {
  174. fileName := filepath.Join(
  175. config.ProcessProfileOutputDirectory, profileName+".profile")
  176. file, err := os.OpenFile(
  177. fileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  178. if err != nil {
  179. log.WithContextFields(
  180. LogFields{
  181. "error": err,
  182. "fileName": fileName}).Error("open profile file failed")
  183. return nil
  184. }
  185. return file
  186. }
  187. writeProfile := func(profileName string) {
  188. file := openProfileFile(profileName)
  189. if file == nil {
  190. return
  191. }
  192. err := pprof.Lookup(profileName).WriteTo(file, 1)
  193. file.Close()
  194. if err != nil {
  195. log.WithContextFields(
  196. LogFields{
  197. "error": err,
  198. "profileName": profileName}).Error("write profile failed")
  199. }
  200. }
  201. // TODO: capture https://golang.org/pkg/runtime/debug/#WriteHeapDump?
  202. // May not be useful in its current state, as per:
  203. // https://groups.google.com/forum/#!topic/golang-dev/cYAkuU45Qyw
  204. // Write goroutine, heap, and threadcreate profiles
  205. // https://golang.org/pkg/runtime/pprof/#Profile
  206. writeProfile("goroutine")
  207. writeProfile("heap")
  208. writeProfile("threadcreate")
  209. // Write block profile (after sampling)
  210. // https://golang.org/pkg/runtime/pprof/#Profile
  211. if config.ProcessBlockProfileDurationSeconds > 0 {
  212. log.WithContext().Info("start block profiling")
  213. runtime.SetBlockProfileRate(1)
  214. time.Sleep(
  215. time.Duration(config.ProcessBlockProfileDurationSeconds) * time.Second)
  216. runtime.SetBlockProfileRate(0)
  217. log.WithContext().Info("end block profiling")
  218. writeProfile("block")
  219. }
  220. // Write CPU profile (after sampling)
  221. // https://golang.org/pkg/runtime/pprof/#StartCPUProfile
  222. if config.ProcessCPUProfileDurationSeconds > 0 {
  223. file := openProfileFile("cpu")
  224. if file != nil {
  225. log.WithContext().Info("start cpu profiling")
  226. err := pprof.StartCPUProfile(file)
  227. if err != nil {
  228. log.WithContextFields(
  229. LogFields{"error": err}).Error("StartCPUProfile failed")
  230. } else {
  231. time.Sleep(time.Duration(
  232. config.ProcessCPUProfileDurationSeconds) * time.Second)
  233. pprof.StopCPUProfile()
  234. log.WithContext().Info("end cpu profiling")
  235. }
  236. file.Close()
  237. }
  238. }
  239. }
  240. }
  241. func logServerLoad(server *TunnelServer) {
  242. // golang runtime stats
  243. var memStats runtime.MemStats
  244. runtime.ReadMemStats(&memStats)
  245. fields := LogFields{
  246. "event_name": "server_load",
  247. "num_goroutine": runtime.NumGoroutine(),
  248. "mem_stats": map[string]interface{}{
  249. "alloc": memStats.Alloc,
  250. "total_alloc": memStats.TotalAlloc,
  251. "sys": memStats.Sys,
  252. "pause_total_ns": memStats.PauseTotalNs,
  253. "pause_ns": memStats.PauseNs,
  254. "num_gc": memStats.NumGC,
  255. "gc_cpu_fraction": memStats.GCCPUFraction,
  256. },
  257. }
  258. // tunnel server stats
  259. fields["establish_tunnels"] = server.GetEstablishTunnels()
  260. for tunnelProtocol, stats := range server.GetLoadStats() {
  261. fields[tunnelProtocol] = stats
  262. }
  263. log.LogRawFieldsWithTimestamp(fields)
  264. }
  265. // SupportServices carries common and shared data components
  266. // across different server components. SupportServices implements a
  267. // hot reload of traffic rules, psinet database, and geo IP database
  268. // components, which allows these data components to be refreshed
  269. // without restarting the server process.
  270. type SupportServices struct {
  271. Config *Config
  272. TrafficRulesSet *TrafficRulesSet
  273. OSLConfig *osl.Config
  274. PsinetDatabase *psinet.Database
  275. GeoIPService *GeoIPService
  276. DNSResolver *DNSResolver
  277. TunnelServer *TunnelServer
  278. }
  279. // NewSupportServices initializes a new SupportServices.
  280. func NewSupportServices(config *Config) (*SupportServices, error) {
  281. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  282. if err != nil {
  283. return nil, common.ContextError(err)
  284. }
  285. oslConfig, err := osl.NewConfig(config.OSLConfigFilename)
  286. if err != nil {
  287. return nil, common.ContextError(err)
  288. }
  289. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  290. if err != nil {
  291. return nil, common.ContextError(err)
  292. }
  293. geoIPService, err := NewGeoIPService(
  294. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  295. if err != nil {
  296. return nil, common.ContextError(err)
  297. }
  298. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  299. if err != nil {
  300. return nil, common.ContextError(err)
  301. }
  302. return &SupportServices{
  303. Config: config,
  304. TrafficRulesSet: trafficRulesSet,
  305. OSLConfig: oslConfig,
  306. PsinetDatabase: psinetDatabase,
  307. GeoIPService: geoIPService,
  308. DNSResolver: dnsResolver,
  309. }, nil
  310. }
  311. // Reload reinitializes traffic rules, psinet database, and geo IP database
  312. // components. If any component fails to reload, an error is logged and
  313. // Reload proceeds, using the previous state of the component.
  314. func (support *SupportServices) Reload() {
  315. reloaders := append(
  316. []common.Reloader{
  317. support.TrafficRulesSet,
  318. support.OSLConfig,
  319. support.PsinetDatabase},
  320. support.GeoIPService.Reloaders()...)
  321. // Take these actions only after the corresponding Reloader has reloaded.
  322. // In both the traffic rules and OSL cases, there is some impact from state
  323. // reset, so the reset should be avoided where possible.
  324. reloadPostActions := map[common.Reloader]func(){
  325. support.TrafficRulesSet: func() { support.TunnelServer.ResetAllClientTrafficRules() },
  326. support.OSLConfig: func() { support.TunnelServer.ResetAllClientOSLConfigs() },
  327. }
  328. for _, reloader := range reloaders {
  329. if !reloader.WillReload() {
  330. // Skip logging
  331. continue
  332. }
  333. // "reloaded" flag indicates if file was actually reloaded or ignored
  334. reloaded, err := reloader.Reload()
  335. if reloaded {
  336. if action, ok := reloadPostActions[reloader]; ok {
  337. action()
  338. }
  339. }
  340. if err != nil {
  341. log.WithContextFields(
  342. LogFields{
  343. "reloader": reloader.LogDescription(),
  344. "error": err}).Error("reload failed")
  345. // Keep running with previous state
  346. } else {
  347. log.WithContextFields(
  348. LogFields{
  349. "reloader": reloader.LogDescription(),
  350. "reloaded": reloaded}).Info("reload success")
  351. }
  352. }
  353. }