services.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. )
  32. // RunServices initializes support functions including logging, GeoIP service, and
  33. // redis connection pooling; and then starts the server components and runs them
  34. // until os.Interrupt or os.Kill signals are received. The config determines
  35. // which components are run.
  36. func RunServices(encodedConfigs [][]byte) error {
  37. config, err := LoadConfig(encodedConfigs)
  38. if err != nil {
  39. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  40. return psiphon.ContextError(err)
  41. }
  42. err = InitLogging(config)
  43. if err != nil {
  44. log.WithContextFields(LogFields{"error": err}).Error("init logging failed")
  45. return psiphon.ContextError(err)
  46. }
  47. err = InitGeoIP(config)
  48. if err != nil {
  49. log.WithContextFields(LogFields{"error": err}).Error("init GeoIP failed")
  50. return psiphon.ContextError(err)
  51. }
  52. if config.UseRedis() {
  53. err = InitRedis(config)
  54. if err != nil {
  55. log.WithContextFields(LogFields{"error": err}).Error("init redis failed")
  56. return psiphon.ContextError(err)
  57. }
  58. }
  59. waitGroup := new(sync.WaitGroup)
  60. shutdownBroadcast := make(chan struct{})
  61. errors := make(chan error)
  62. tunnelServer, err := NewTunnelServer(config, shutdownBroadcast)
  63. if err != nil {
  64. log.WithContextFields(LogFields{"error": err}).Error("init tunnel server failed")
  65. return psiphon.ContextError(err)
  66. }
  67. if config.RunLoadMonitor() {
  68. waitGroup.Add(1)
  69. go func() {
  70. waitGroup.Done()
  71. runLoadMonitor(
  72. tunnelServer,
  73. time.Duration(config.LoadMonitorPeriodSeconds)*time.Second,
  74. shutdownBroadcast)
  75. }()
  76. }
  77. if config.RunWebServer() {
  78. waitGroup.Add(1)
  79. go func() {
  80. defer waitGroup.Done()
  81. err := RunWebServer(config, 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. err = nil
  103. select {
  104. case <-systemStopSignal:
  105. log.WithContext().Info("shutdown by system")
  106. case err = <-errors:
  107. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  108. }
  109. close(shutdownBroadcast)
  110. waitGroup.Wait()
  111. return err
  112. }
  113. // runLoadMonitor periodically logs golang runtime and tunnel server stats
  114. func runLoadMonitor(
  115. server *TunnelServer,
  116. loadMonitorPeriod time.Duration,
  117. shutdownBroadcast <-chan struct{}) {
  118. ticker := time.NewTicker(loadMonitorPeriod)
  119. defer ticker.Stop()
  120. for {
  121. select {
  122. case <-shutdownBroadcast:
  123. return
  124. case <-ticker.C:
  125. // golang runtime stats
  126. var memStats runtime.MemStats
  127. runtime.ReadMemStats(&memStats)
  128. fields := LogFields{
  129. "NumGoroutine": runtime.NumGoroutine(),
  130. "MemStats.Alloc": memStats.Alloc,
  131. "MemStats.TotalAlloc": memStats.TotalAlloc,
  132. "MemStats.Sys": memStats.Sys,
  133. }
  134. // tunnel server stats
  135. for tunnelProtocol, stats := range server.GetLoadStats() {
  136. for stat, value := range stats {
  137. fields[tunnelProtocol+"."+stat] = value
  138. }
  139. }
  140. log.WithContextFields(fields).Info("load")
  141. }
  142. }
  143. }