main.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. "log"
  6. "github.com/gravitl/netmaker/controllers"
  7. "github.com/gravitl/netmaker/servercfg"
  8. "github.com/gravitl/netmaker/serverctl"
  9. "github.com/gravitl/netmaker/mongoconn"
  10. "fmt"
  11. "os"
  12. "os/exec"
  13. "net"
  14. "context"
  15. "strconv"
  16. "sync"
  17. "os/signal"
  18. service "github.com/gravitl/netmaker/controllers"
  19. nodepb "github.com/gravitl/netmaker/grpc"
  20. "google.golang.org/grpc"
  21. )
  22. //Start MongoDB Connection and start API Request Handler
  23. func main() {
  24. //Client Mode Prereq Check
  25. if servercfg.IsClientMode() {
  26. cmd := exec.Command("id", "-u")
  27. output, err := cmd.Output()
  28. if err != nil {
  29. fmt.Println("Error running 'id -u' for prereq check. Please investigate or disable client mode.")
  30. log.Fatal(err)
  31. }
  32. i, err := strconv.Atoi(string(output[:len(output)-1]))
  33. if err != nil {
  34. fmt.Println("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.")
  35. log.Fatal(err)
  36. }
  37. if i != 0 {
  38. log.Fatal("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
  39. }
  40. }
  41. //Start Mongodb
  42. mongoconn.ConnectDatabase()
  43. installserver := false
  44. //Create the default network (default: 10.10.10.0/24)
  45. created, err := serverctl.CreateDefaultNetwork()
  46. if err != nil {
  47. fmt.Printf("Error creating default network: %v", err)
  48. }
  49. if created && servercfg.IsClientMode() {
  50. installserver = true
  51. }
  52. //NOTE: Removed Check and Logic for DNS Mode
  53. //Reasoning. DNS Logic is very small on server. Can run with little/no impact. Just sets a tiny config file.
  54. //Real work is done by CoreDNS
  55. //We can just not run CoreDNS. On Agent side is only necessary check for IsDNSMode, which we will pass.
  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. fmt.Println("Unable to Set host. Exiting.")
  63. log.Fatal(err)
  64. }
  65. }
  66. waitnetwork.Add(1)
  67. go runGRPC(&waitnetwork, installserver)
  68. }
  69. //Run Rest Server
  70. if servercfg.IsRestBackend() {
  71. if !servercfg.DisableRemoteIPCheck() && servercfg.GetAPIHost() == "127.0.0.1" {
  72. err := servercfg.SetHost()
  73. if err != nil {
  74. fmt.Println("Unable to Set host. Exiting.")
  75. log.Fatal(err)
  76. }
  77. }
  78. waitnetwork.Add(1)
  79. controller.HandleRESTRequests(&waitnetwork)
  80. }
  81. if !servercfg.IsAgentBackend() && !servercfg.IsRestBackend() {
  82. fmt.Println("Oops! No Server Mode selected. Nothing is being served! Set either Agent mode (AGENT_BACKEND) or Rest mode (REST_BACKEND) to 'true'.")
  83. }
  84. waitnetwork.Wait()
  85. fmt.Println("Exiting now.")
  86. }
  87. func runGRPC(wg *sync.WaitGroup, installserver bool) {
  88. defer wg.Done()
  89. // Configure 'log' package to give file name and line number on eg. log.Fatal
  90. // Pipe flags to one another (log.LstdFLags = log.Ldate | log.Ltime)
  91. log.SetFlags(log.LstdFlags | log.Lshortfile)
  92. grpcport := servercfg.GetGRPCPort()
  93. listener, err := net.Listen("tcp", ":"+grpcport)
  94. // Handle errors if any
  95. if err != nil {
  96. log.Fatalf("Unable to listen on port" + grpcport + ": %v", err)
  97. }
  98. s := grpc.NewServer(
  99. authServerUnaryInterceptor(),
  100. authServerStreamInterceptor(),
  101. )
  102. // Create NodeService type
  103. srv := &service.NodeServiceServer{}
  104. // Register the service with the server
  105. nodepb.RegisterNodeServiceServer(s, srv)
  106. srv.NodeDB = mongoconn.NodeDB
  107. // Start the server in a child routine
  108. go func() {
  109. if err := s.Serve(listener); err != nil {
  110. log.Fatalf("Failed to serve: %v", err)
  111. }
  112. }()
  113. fmt.Println("Agent Server succesfully started on port " + grpcport + " (gRPC)")
  114. if installserver {
  115. fmt.Println("Adding server to default network")
  116. success, err := serverctl.AddNetwork("default")
  117. if err != nil {
  118. fmt.Printf("Error adding to default network: %v", err)
  119. fmt.Println("")
  120. fmt.Println("Unable to add server to network. Continuing.")
  121. fmt.Println("Please investigate client installation on server.")
  122. } else if !success {
  123. fmt.Println("Unable to add server to network. Continuing.")
  124. fmt.Println("Please investigate client installation on server.")
  125. } else{
  126. fmt.Println("Server successfully added to default network.")
  127. }
  128. }
  129. fmt.Println("Setup complete. You are ready to begin using netmaker.")
  130. // Right way to stop the server using a SHUTDOWN HOOK
  131. // Create a channel to receive OS signals
  132. c := make(chan os.Signal)
  133. // Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
  134. // Ignore other incoming signals
  135. signal.Notify(c, os.Interrupt)
  136. // Block main routine until a signal is received
  137. // As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
  138. <-c
  139. // After receiving CTRL+C Properly stop the server
  140. fmt.Println("Stopping the Agent server...")
  141. s.Stop()
  142. listener.Close()
  143. fmt.Println("Agent server closed..")
  144. fmt.Println("Closing MongoDB connection")
  145. mongoconn.Client.Disconnect(context.TODO())
  146. fmt.Println("MongoDB connection closed.")
  147. }
  148. func authServerUnaryInterceptor() grpc.ServerOption {
  149. return grpc.UnaryInterceptor(controller.AuthServerUnaryInterceptor)
  150. }
  151. func authServerStreamInterceptor() grpc.ServerOption {
  152. return grpc.StreamInterceptor(controller.AuthServerStreamInterceptor)
  153. }