services.go 7.1 KB

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