services.go 7.5 KB

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