services.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. )
  33. // RunServices initializes support functions including logging, GeoIP service, and
  34. // redis connection pooling; and then starts the server components and runs them
  35. // until os.Interrupt or os.Kill signals are received. The config determines
  36. // which components are run.
  37. func RunServices(encodedConfigs [][]byte) error {
  38. config, err := LoadConfig(encodedConfigs)
  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. err = InitGeoIP(config)
  49. if err != nil {
  50. log.WithContextFields(LogFields{"error": err}).Error("init GeoIP failed")
  51. return psiphon.ContextError(err)
  52. }
  53. psinetDatabase, err := NewPsinetDatabase(config.PsinetDatabaseFilename)
  54. if err != nil {
  55. log.WithContextFields(LogFields{"error": err}).Error("init PsinetDatabase failed")
  56. return psiphon.ContextError(err)
  57. }
  58. if config.UseRedis() {
  59. err = InitRedis(config)
  60. if err != nil {
  61. log.WithContextFields(LogFields{"error": err}).Error("init redis failed")
  62. return psiphon.ContextError(err)
  63. }
  64. }
  65. waitGroup := new(sync.WaitGroup)
  66. shutdownBroadcast := make(chan struct{})
  67. errors := make(chan error)
  68. tunnelServer, err := NewTunnelServer(config, psinetDatabase, shutdownBroadcast)
  69. if err != nil {
  70. log.WithContextFields(LogFields{"error": err}).Error("init tunnel server failed")
  71. return psiphon.ContextError(err)
  72. }
  73. if config.RunLoadMonitor() {
  74. waitGroup.Add(1)
  75. go func() {
  76. waitGroup.Done()
  77. ticker := time.NewTicker(time.Duration(config.LoadMonitorPeriodSeconds) * time.Second)
  78. defer ticker.Stop()
  79. for {
  80. select {
  81. case <-shutdownBroadcast:
  82. return
  83. case <-ticker.C:
  84. logLoad(tunnelServer)
  85. }
  86. }
  87. }()
  88. }
  89. if config.RunWebServer() {
  90. waitGroup.Add(1)
  91. go func() {
  92. defer waitGroup.Done()
  93. err := RunWebServer(config, psinetDatabase, shutdownBroadcast)
  94. select {
  95. case errors <- err:
  96. default:
  97. }
  98. }()
  99. }
  100. // The tunnel server is always run; it launches multiple
  101. // listeners, depending on which tunnel protocols are enabled.
  102. waitGroup.Add(1)
  103. go func() {
  104. defer waitGroup.Done()
  105. err := tunnelServer.Run()
  106. select {
  107. case errors <- err:
  108. default:
  109. }
  110. }()
  111. // An OS signal triggers an orderly shutdown
  112. systemStopSignal := make(chan os.Signal, 1)
  113. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  114. // SIGUSR1 triggers a load log
  115. logLoadSignal := make(chan os.Signal, 1)
  116. signal.Notify(logLoadSignal, syscall.SIGUSR1)
  117. err = nil
  118. loop:
  119. for {
  120. select {
  121. case <-logLoadSignal:
  122. logLoad(tunnelServer)
  123. case <-systemStopSignal:
  124. log.WithContext().Info("shutdown by system")
  125. break loop
  126. case err = <-errors:
  127. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  128. break loop
  129. }
  130. }
  131. close(shutdownBroadcast)
  132. waitGroup.Wait()
  133. return err
  134. }
  135. func logLoad(server *TunnelServer) {
  136. // golang runtime stats
  137. var memStats runtime.MemStats
  138. runtime.ReadMemStats(&memStats)
  139. fields := LogFields{
  140. "NumGoroutine": runtime.NumGoroutine(),
  141. "MemStats.Alloc": memStats.Alloc,
  142. "MemStats.TotalAlloc": memStats.TotalAlloc,
  143. "MemStats.Sys": memStats.Sys,
  144. }
  145. // tunnel server stats
  146. for tunnelProtocol, stats := range server.GetLoadStats() {
  147. for stat, value := range stats {
  148. fields[tunnelProtocol+"."+stat] = value
  149. }
  150. }
  151. log.WithContextFields(fields).Info("load")
  152. }