main.go 4.4 KB

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