services.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. }
  138. // tunnel server stats
  139. for tunnelProtocol, stats := range server.GetLoadStats() {
  140. for stat, value := range stats {
  141. fields[tunnelProtocol+"."+stat] = value
  142. }
  143. }
  144. log.WithContextFields(fields).Info("load")
  145. }
  146. // SupportServices carries common and shared data components
  147. // across different server components. SupportServices implements a
  148. // hot reload of traffic rules, psinet database, and geo IP database
  149. // components, which allows these data components to be refreshed
  150. // without restarting the server process.
  151. type SupportServices struct {
  152. Config *Config
  153. TrafficRulesSet *TrafficRulesSet
  154. PsinetDatabase *psinet.Database
  155. GeoIPService *GeoIPService
  156. }
  157. // NewSupportServices initializes a new SupportServices.
  158. func NewSupportServices(config *Config) (*SupportServices, error) {
  159. trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
  160. if err != nil {
  161. return nil, psiphon.ContextError(err)
  162. }
  163. psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
  164. if err != nil {
  165. return nil, psiphon.ContextError(err)
  166. }
  167. geoIPService, err := NewGeoIPService(
  168. config.GeoIPDatabaseFilename, config.DiscoveryValueHMACKey)
  169. if err != nil {
  170. return nil, psiphon.ContextError(err)
  171. }
  172. return &SupportServices{
  173. Config: config,
  174. TrafficRulesSet: trafficRulesSet,
  175. PsinetDatabase: psinetDatabase,
  176. GeoIPService: geoIPService,
  177. }, nil
  178. }
  179. // Reload reinitializes traffic rules, psinet database, and geo IP database
  180. // components. If any component fails to reload, an error is logged and
  181. // Reload proceeds, using the previous state of the component.
  182. //
  183. // Note: reload of traffic rules currently doesn't apply to existing,
  184. // established clients.
  185. //
  186. func (support *SupportServices) Reload() {
  187. if support.Config.TrafficRulesFilename != "" {
  188. err := support.TrafficRulesSet.Reload(support.Config.TrafficRulesFilename)
  189. if err != nil {
  190. log.WithContextFields(LogFields{"error": err}).Error("reload traffic rules failed")
  191. // Keep running with previous state of support.TrafficRulesSet
  192. } else {
  193. log.WithContext().Info("reloaded traffic rules")
  194. }
  195. }
  196. if support.Config.PsinetDatabaseFilename != "" {
  197. err := support.PsinetDatabase.Reload(support.Config.PsinetDatabaseFilename)
  198. if err != nil {
  199. log.WithContextFields(LogFields{"error": err}).Error("reload psinet database failed")
  200. // Keep running with previous state of support.PsinetDatabase
  201. } else {
  202. log.WithContext().Info("reloaded psinet database")
  203. }
  204. }
  205. if support.Config.GeoIPDatabaseFilename != "" {
  206. err := support.GeoIPService.ReloadDatabase(support.Config.GeoIPDatabaseFilename)
  207. if err != nil {
  208. log.WithContextFields(LogFields{"error": err}).Error("reload GeoIP database failed")
  209. // Keep running with previous state of support.GeoIPService
  210. } else {
  211. log.WithContext().Info("reloaded GeoIP database")
  212. }
  213. }
  214. }