services.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 server
  20. import (
  21. "os"
  22. "os/signal"
  23. "sync"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  25. )
  26. func RunServices(encodedConfig []byte) error {
  27. config, err := LoadConfig(encodedConfig)
  28. if err != nil {
  29. log.WithContextFields(LogFields{"error": err}).Error("load config failed")
  30. return psiphon.ContextError(err)
  31. }
  32. // TODO: init logging
  33. waitGroup := new(sync.WaitGroup)
  34. shutdownBroadcast := make(chan struct{})
  35. errors := make(chan error)
  36. // TODO: optional services (e.g., run SSH only)
  37. waitGroup.Add(1)
  38. go func() {
  39. defer waitGroup.Done()
  40. err := RunWebServer(config, shutdownBroadcast)
  41. select {
  42. case errors <- err:
  43. default:
  44. }
  45. }()
  46. waitGroup.Add(1)
  47. go func() {
  48. defer waitGroup.Done()
  49. err := RunSSHServer(config, shutdownBroadcast)
  50. select {
  51. case errors <- err:
  52. default:
  53. }
  54. }()
  55. // An OS signal triggers an orderly shutdown
  56. systemStopSignal := make(chan os.Signal, 1)
  57. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  58. err = nil
  59. select {
  60. case <-systemStopSignal:
  61. log.WithContext().Info("shutdown by system")
  62. case err = <-errors:
  63. log.WithContextFields(LogFields{"error": err}).Error("service failed")
  64. }
  65. close(shutdownBroadcast)
  66. waitGroup.Wait()
  67. return err
  68. }