main.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. //TODO: Harden. Add failover for every method and agent calls
  2. //TODO: Figure out why mongodb keeps failing (log rotation?)
  3. package main
  4. import (
  5. "fmt"
  6. "log"
  7. "net"
  8. "os"
  9. "os/signal"
  10. "strconv"
  11. "sync"
  12. "time"
  13. controller "github.com/gravitl/netmaker/controllers"
  14. "github.com/gravitl/netmaker/database"
  15. "github.com/gravitl/netmaker/dnslogic"
  16. "github.com/gravitl/netmaker/functions"
  17. nodepb "github.com/gravitl/netmaker/grpc"
  18. "github.com/gravitl/netmaker/models"
  19. "github.com/gravitl/netmaker/netclient/ncutils"
  20. "github.com/gravitl/netmaker/servercfg"
  21. "github.com/gravitl/netmaker/serverctl"
  22. "google.golang.org/grpc"
  23. )
  24. // Start DB Connection and start API Request Handler
  25. func main() {
  26. fmt.Println(models.RetrieveLogo()) // print the logo
  27. initialize() // initial db and grpc server
  28. defer database.CloseDB()
  29. startControllers() // start the grpc or rest endpoints
  30. }
  31. func initialize() { // Client Mode Prereq Check
  32. var err error
  33. if err = database.InitializeDatabase(); err != nil {
  34. log.Println("Error connecting to database.")
  35. log.Fatal(err)
  36. }
  37. log.Println("database successfully connected.")
  38. if servercfg.IsClientMode() != "off" {
  39. output, err := ncutils.RunCmd("id -u", true)
  40. if err != nil {
  41. log.Println("Error running 'id -u' for prereq check. Please investigate or disable client mode.")
  42. log.Fatal(output, err)
  43. }
  44. uid, err := strconv.Atoi(string(output[:len(output)-1]))
  45. if err != nil {
  46. log.Println("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.")
  47. log.Fatal(err)
  48. }
  49. if uid != 0 {
  50. log.Fatal("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
  51. }
  52. if err := serverctl.InitServerNetclient(); err != nil {
  53. log.Fatal("Did not find netclient to use CLIENT_MODE")
  54. }
  55. }
  56. if servercfg.IsDNSMode() {
  57. err := functions.SetDNSDir()
  58. if err != nil {
  59. log.Fatal(err)
  60. }
  61. }
  62. }
  63. func startControllers() {
  64. var waitnetwork sync.WaitGroup
  65. //Run Agent Server
  66. if servercfg.IsAgentBackend() {
  67. if !(servercfg.DisableRemoteIPCheck()) && servercfg.GetGRPCHost() == "127.0.0.1" {
  68. err := servercfg.SetHost()
  69. if err != nil {
  70. log.Println("Unable to Set host. Exiting...")
  71. log.Fatal(err)
  72. }
  73. }
  74. waitnetwork.Add(1)
  75. go runGRPC(&waitnetwork)
  76. }
  77. if servercfg.IsClientMode() == "on" {
  78. waitnetwork.Add(1)
  79. go runClient(&waitnetwork)
  80. }
  81. if servercfg.IsDNSMode() {
  82. err := dnslogic.SetDNS()
  83. if err != nil {
  84. log.Println("error occurred initializing DNS:", err)
  85. }
  86. }
  87. //Run Rest Server
  88. if servercfg.IsRestBackend() {
  89. if !servercfg.DisableRemoteIPCheck() && servercfg.GetAPIHost() == "127.0.0.1" {
  90. err := servercfg.SetHost()
  91. if err != nil {
  92. log.Println("Unable to Set host. Exiting...")
  93. log.Fatal(err)
  94. }
  95. }
  96. waitnetwork.Add(1)
  97. controller.HandleRESTRequests(&waitnetwork)
  98. }
  99. if !servercfg.IsAgentBackend() && !servercfg.IsRestBackend() {
  100. log.Println("No Server Mode selected, so nothing is being served! Set either Agent mode (AGENT_BACKEND) or Rest mode (REST_BACKEND) to 'true'.")
  101. }
  102. waitnetwork.Wait()
  103. log.Println("[netmaker] exiting")
  104. }
  105. func runClient(wg *sync.WaitGroup) {
  106. defer wg.Done()
  107. go func() {
  108. for {
  109. if err := serverctl.HandleContainedClient(); err != nil {
  110. // PASS
  111. }
  112. time.Sleep(time.Second * 15)
  113. }
  114. }()
  115. }
  116. func runGRPC(wg *sync.WaitGroup) {
  117. defer wg.Done()
  118. // Configure 'log' package to give file name and line number on eg. log.Fatal
  119. // Pipe flags to one another (log.LstdFLags = log.Ldate | log.Ltime)
  120. log.SetFlags(log.LstdFlags | log.Lshortfile)
  121. grpcport := servercfg.GetGRPCPort()
  122. listener, err := net.Listen("tcp", ":"+grpcport)
  123. // Handle errors if any
  124. if err != nil {
  125. log.Fatalf("Unable to listen on port "+grpcport+", error: %v", err)
  126. }
  127. s := grpc.NewServer(
  128. authServerUnaryInterceptor(),
  129. )
  130. // Create NodeService type
  131. srv := &controller.NodeServiceServer{}
  132. // Register the service with the server
  133. nodepb.RegisterNodeServiceServer(s, srv)
  134. // Start the server in a child routine
  135. go func() {
  136. if err := s.Serve(listener); err != nil {
  137. log.Fatalf("Failed to serve: %v", err)
  138. }
  139. }()
  140. log.Println("Agent Server succesfully started on port " + grpcport + " (gRPC)")
  141. // Right way to stop the server using a SHUTDOWN HOOK
  142. // Create a channel to receive OS signals
  143. c := make(chan os.Signal)
  144. // Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
  145. // Ignore other incoming signals
  146. signal.Notify(c, os.Interrupt)
  147. // Block main routine until a signal is received
  148. // As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
  149. <-c
  150. // After receiving CTRL+C Properly stop the server
  151. log.Println("Stopping the Agent server...")
  152. s.Stop()
  153. listener.Close()
  154. log.Println("Agent server closed..")
  155. log.Println("Closed DB connection.")
  156. }
  157. func authServerUnaryInterceptor() grpc.ServerOption {
  158. return grpc.UnaryInterceptor(controller.AuthServerUnaryInterceptor)
  159. }
  160. // func authServerStreamInterceptor() grpc.ServerOption {
  161. // return grpc.StreamInterceptor(controller.AuthServerStreamInterceptor)
  162. // }