main.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "os"
  7. "os/signal"
  8. "runtime/debug"
  9. "strconv"
  10. "sync"
  11. "syscall"
  12. "github.com/gravitl/netmaker/auth"
  13. controller "github.com/gravitl/netmaker/controllers"
  14. "github.com/gravitl/netmaker/database"
  15. "github.com/gravitl/netmaker/functions"
  16. nodepb "github.com/gravitl/netmaker/grpc"
  17. "github.com/gravitl/netmaker/logger"
  18. "github.com/gravitl/netmaker/logic"
  19. "github.com/gravitl/netmaker/models"
  20. "github.com/gravitl/netmaker/mq"
  21. "github.com/gravitl/netmaker/netclient/ncutils"
  22. "github.com/gravitl/netmaker/servercfg"
  23. "github.com/gravitl/netmaker/serverctl"
  24. "google.golang.org/grpc"
  25. )
  26. // Start DB Connection and start API Request Handler
  27. func main() {
  28. fmt.Println(models.RetrieveLogo()) // print the logo
  29. initialize() // initial db and grpc server
  30. setGarbageCollection()
  31. defer database.CloseDB()
  32. startControllers() // start the grpc or rest endpoints
  33. }
  34. func initialize() { // Client Mode Prereq Check
  35. var err error
  36. if servercfg.GetNodeID() == "" {
  37. logger.FatalLog("error: must set NODE_ID, currently blank")
  38. }
  39. if err = database.InitializeDatabase(); err != nil {
  40. logger.FatalLog("Error connecting to database")
  41. }
  42. logger.Log(0, "database successfully connected")
  43. err = logic.TimerCheckpoint()
  44. if err != nil {
  45. logger.Log(1, "Timer error occurred: ", err.Error())
  46. }
  47. var authProvider = auth.InitializeAuthProvider()
  48. if authProvider != "" {
  49. logger.Log(0, "OAuth provider,", authProvider+",", "initialized")
  50. } else {
  51. logger.Log(0, "no OAuth provider found or not configured, continuing without OAuth")
  52. }
  53. if servercfg.IsClientMode() != "off" {
  54. output, err := ncutils.RunCmd("id -u", true)
  55. if err != nil {
  56. logger.FatalLog("Error running 'id -u' for prereq check. Please investigate or disable client mode.", output, err.Error())
  57. }
  58. uid, err := strconv.Atoi(string(output[:len(output)-1]))
  59. if err != nil {
  60. logger.FatalLog("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.", err.Error())
  61. }
  62. if uid != 0 {
  63. logger.FatalLog("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
  64. }
  65. if err := serverctl.InitServerNetclient(); err != nil {
  66. logger.FatalLog("Did not find netclient to use CLIENT_MODE")
  67. }
  68. }
  69. // initialize iptables to ensure gateways work correctly and mq is forwarded if containerized
  70. if servercfg.ManageIPTables() != "off" {
  71. if err = serverctl.InitIPTables(); err != nil {
  72. logger.FatalLog("Unable to initialize iptables on host:", err.Error())
  73. }
  74. }
  75. if servercfg.IsDNSMode() {
  76. err := functions.SetDNSDir()
  77. if err != nil {
  78. logger.FatalLog(err.Error())
  79. }
  80. }
  81. }
  82. func startControllers() {
  83. var waitnetwork sync.WaitGroup
  84. //Run Agent Server
  85. if servercfg.IsAgentBackend() {
  86. if !(servercfg.DisableRemoteIPCheck()) && servercfg.GetGRPCHost() == "127.0.0.1" {
  87. err := servercfg.SetHost()
  88. if err != nil {
  89. logger.FatalLog("Unable to Set host. Exiting...", err.Error())
  90. }
  91. }
  92. waitnetwork.Add(1)
  93. go runGRPC(&waitnetwork)
  94. }
  95. if servercfg.IsDNSMode() {
  96. err := logic.SetDNS()
  97. if err != nil {
  98. logger.Log(0, "error occurred initializing DNS: ", err.Error())
  99. }
  100. }
  101. //Run Rest Server
  102. if servercfg.IsRestBackend() {
  103. if !servercfg.DisableRemoteIPCheck() && servercfg.GetAPIHost() == "127.0.0.1" {
  104. err := servercfg.SetHost()
  105. if err != nil {
  106. logger.FatalLog("Unable to Set host. Exiting...", err.Error())
  107. }
  108. }
  109. waitnetwork.Add(1)
  110. go controller.HandleRESTRequests(&waitnetwork)
  111. }
  112. //Run MessageQueue
  113. if servercfg.IsMessageQueueBackend() {
  114. waitnetwork.Add(1)
  115. go runMessageQueue(&waitnetwork)
  116. }
  117. if !servercfg.IsAgentBackend() && !servercfg.IsRestBackend() && !servercfg.IsMessageQueueBackend() {
  118. logger.Log(0, "No Server Mode selected, so nothing is being served! Set Agent mode (AGENT_BACKEND) or Rest mode (REST_BACKEND) or MessageQueue (MESSAGEQUEUE_BACKEND) to 'true'.")
  119. }
  120. waitnetwork.Wait()
  121. }
  122. func runGRPC(wg *sync.WaitGroup) {
  123. defer wg.Done()
  124. grpcport := servercfg.GetGRPCPort()
  125. listener, err := net.Listen("tcp", ":"+grpcport)
  126. // Handle errors if any
  127. if err != nil {
  128. logger.FatalLog("[netmaker] Unable to listen on port", grpcport, ": error:", err.Error())
  129. }
  130. s := grpc.NewServer(
  131. authServerUnaryInterceptor(),
  132. )
  133. // Create NodeService type
  134. srv := &controller.NodeServiceServer{}
  135. // Register the service with the server
  136. nodepb.RegisterNodeServiceServer(s, srv)
  137. // Start the server in a child routine
  138. go func() {
  139. if err := s.Serve(listener); err != nil {
  140. logger.FatalLog("Failed to serve:", err.Error())
  141. }
  142. }()
  143. logger.Log(0, "Agent Server successfully started on port ", grpcport, "(gRPC)")
  144. // Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
  145. // Ignore other incoming signals
  146. ctx, stop := signal.NotifyContext(context.TODO(), os.Interrupt)
  147. defer stop()
  148. // Block main routine until a signal is received
  149. // As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
  150. <-ctx.Done()
  151. // After receiving CTRL+C Properly stop the server
  152. logger.Log(0, "Stopping the Agent server...")
  153. s.GracefulStop()
  154. listener.Close()
  155. logger.Log(0, "Agent server closed..")
  156. logger.Log(0, "Closed DB connection.")
  157. }
  158. // Should we be using a context vice a waitgroup????????????
  159. func runMessageQueue(wg *sync.WaitGroup) {
  160. defer wg.Done()
  161. logger.Log(0, fmt.Sprintf("connecting to mq broker at %s", servercfg.GetMessageQueueEndpoint()))
  162. var client = mq.SetupMQTT(false) // Set up the subscription listener
  163. ctx, cancel := context.WithCancel(context.Background())
  164. go mq.Keepalive(ctx)
  165. quit := make(chan os.Signal, 1)
  166. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  167. <-quit
  168. cancel()
  169. logger.Log(0, "Message Queue shutting down")
  170. client.Disconnect(250)
  171. }
  172. func authServerUnaryInterceptor() grpc.ServerOption {
  173. return grpc.UnaryInterceptor(controller.AuthServerUnaryInterceptor)
  174. }
  175. func setGarbageCollection() {
  176. _, gcset := os.LookupEnv("GOGC")
  177. if !gcset {
  178. debug.SetGCPercent(ncutils.DEFAULT_GC_PERCENT)
  179. }
  180. }