services.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. "runtime"
  28. "sync"
  29. "syscall"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  33. )
  34. // RunServices initializes support functions including logging and GeoIP services;
  35. // and then starts the server components and runs them until os.Interrupt or
  36. // os.Kill signals are received. The config determines which components are run.
  37. func RunServices(configJSON []byte) error {
  38. config, err := LoadConfig(configJSON)
  39. if err != nil {
  40. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  41. return common.ContextError(err)
  42. }
  43. err = InitLogging(config)
  44. if err != nil {
  45. log.WithContextFields(LogFields{"error": err}).Error("init logging failed")
  46. return common.ContextError(err)
  47. }
  48. supportServices, err := NewSupportServices(config)
  49. if err != nil {
  50. log.WithContextFields(LogFields{"error": err}).Error("init support services failed")
  51. return common.ContextError(err)
  52. }
  53. log.WithContextFields(*common.GetBuildInfo().ToMap()).Info("startup")
  54. waitGroup := new(sync.WaitGroup)
  55. shutdownBroadcast := make(chan struct{})
  56. errors := make(chan error)
  57. tunnelServer, err := NewTunnelServer(supportServices, shutdownBroadcast)
  58. if err != nil {
  59. log.WithContextFields(LogFields{"error": err}).Error("init tunnel server failed")
  60. return common.ContextError(err)
  61. }
  62. if config.RunLoadMonitor() {
  63. waitGroup.Add(1)
  64. go func() {
  65. waitGroup.Done()
  66. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  67. defer ticker.Stop()
  68. for {
  69. select {
  70. case <-shutdownBroadcast:
  71. return
  72. case <-ticker.C:
  73. logServerLoad(tunnelServer)
  74. }
  75. }
  76. }()
  77. }
  78. if config.RunWebServer() {
  79. waitGroup.Add(1)
  80. go func() {
  81. defer waitGroup.Done()
  82. err := RunWebServer(supportServices, shutdownBroadcast)
  83. select {
  84. case errors <- err:
  85. default:
  86. }
  87. }()
  88. }
  89. // The tunnel server is always run; it launches multiple
  90. // listeners, depending on which tunnel protocols are enabled.
  91. waitGroup.Add(1)
  92. go func() {
  93. defer waitGroup.Done()
  94. err := tunnelServer.Run()
  95. select {
  96. case errors <- err:
  97. default:
  98. }
  99. }()
  100. // An OS signal triggers an orderly shutdown
  101. systemStopSignal := make(chan os.Signal, 1)
  102. signal.Notify(systemStopSignal, os.Interrupt, os.Kill, syscall.SIGTERM)
  103. // SIGUSR1 triggers a reload of support services
  104. reloadSupportServicesSignal := make(chan os.Signal, 1)
  105. signal.Notify(reloadSupportServicesSignal, syscall.SIGUSR1)
  106. // SIGUSR2 triggers an immediate load log
  107. logServerLoadSignal := make(chan os.Signal, 1)
  108. signal.Notify(logServerLoadSignal, syscall.SIGUSR2)
  109. err = nil
  110. loop:
  111. for {
  112. select {
  113. case <-reloadSupportServicesSignal:
  114. supportServices.Reload()
  115. case <-logServerLoadSignal:
  116. logServerLoad(tunnelServer)
  117. case <-systemStopSignal:
  118. log.WithContext().Info("shutdown by system")
  119. break loop
  120. case err = <-errors:
  121. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  122. break loop
  123. }
  124. }
  125. close(shutdownBroadcast)
  126. waitGroup.Wait()
  127. return err
  128. }
  129. func logServerLoad(server *TunnelServer) {
  130. // golang runtime stats
  131. var memStats runtime.MemStats
  132. runtime.ReadMemStats(&memStats)
  133. fields := LogFields{
  134. "event_name": "server_load",
  135. "BuildRev": common.GetBuildInfo().BuildRev,
  136. "HostID": server.sshServer.support.Config.HostID,
  137. "NumGoroutine": runtime.NumGoroutine(),
  138. "MemStats": map[string]interface{}{
  139. "Alloc": memStats.Alloc,
  140. "TotalAlloc": memStats.TotalAlloc,
  141. "Sys": memStats.Sys,
  142. "PauseTotalNs": memStats.PauseTotalNs,
  143. "PauseNs": memStats.PauseNs,
  144. "NumGC": memStats.NumGC,
  145. "GCCPUFraction": memStats.GCCPUFraction,
  146. },
  147. }
  148. // tunnel server stats
  149. for tunnelProtocol, stats := range server.GetLoadStats() {
  150. fields[tunnelProtocol] = stats
  151. }
  152. log.LogRawFieldsWithTimestamp(fields)
  153. }
  154. // SupportServices carries common and shared data components
  155. // across different server components. SupportServices implements a
  156. // hot reload of traffic rules, psinet database, and geo IP database
  157. // components, which allows these data components to be refreshed
  158. // without restarting the server process.
  159. type SupportServices struct {
  160. Config *Config
  161. TrafficRulesSet *TrafficRulesSet
  162. PsinetDatabase *psinet.Database
  163. GeoIPService *GeoIPService
  164. DNSResolver *DNSResolver
  165. }
  166. // NewSupportServices initializes a new SupportServices.
  167. func NewSupportServices(config *Config) (*SupportServices, error) {
  168. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  169. if err != nil {
  170. return nil, common.ContextError(err)
  171. }
  172. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  173. if err != nil {
  174. return nil, common.ContextError(err)
  175. }
  176. geoIPService, err := NewGeoIPService(
  177. config.GeoIPDatabaseFilenames, config.DiscoveryValueHMACKey)
  178. if err != nil {
  179. return nil, common.ContextError(err)
  180. }
  181. dnsResolver, err := NewDNSResolver(config.DNSResolverIPAddress)
  182. if err != nil {
  183. return nil, common.ContextError(err)
  184. }
  185. return &SupportServices{
  186. Config: config,
  187. TrafficRulesSet: trafficRulesSet,
  188. PsinetDatabase: psinetDatabase,
  189. GeoIPService: geoIPService,
  190. DNSResolver: dnsResolver,
  191. }, nil
  192. }
  193. // Reload reinitializes traffic rules, psinet database, and geo IP database
  194. // components. If any component fails to reload, an error is logged and
  195. // Reload proceeds, using the previous state of the component.
  196. //
  197. // Limitation: reload of traffic rules currently doesn't apply to existing,
  198. // established clients.
  199. func (support *SupportServices) Reload() {
  200. reloaders := append(
  201. []common.Reloader{support.TrafficRulesSet, support.PsinetDatabase},
  202. support.GeoIPService.Reloaders()...)
  203. for _, reloader := range reloaders {
  204. if !reloader.WillReload() {
  205. // Skip logging
  206. continue
  207. }
  208. // "reloaded" flag indicates if file was actually reloaded or ignored
  209. reloaded, err := reloader.Reload()
  210. if err != nil {
  211. log.WithContextFields(
  212. LogFields{
  213. "reloader": reloader.LogDescription(),
  214. "error": err}).Error("reload failed")
  215. // Keep running with previous state
  216. } else {
  217. log.WithContextFields(
  218. LogFields{
  219. "reloader": reloader.LogDescription(),
  220. "reloaded": reloaded}).Info("reload success")
  221. }
  222. }
  223. }