services.go 4.3 KB

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