services.go 8.3 KB

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