main.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. waitnetwork.Add(1)
  60. go runGRPC(&waitnetwork, installserver)
  61. }
  62. //Run Rest Server
  63. if servercfg.IsRestBackend() {
  64. waitnetwork.Add(1)
  65. controller.HandleRESTRequests(&waitnetwork)
  66. }
  67. if !servercfg.IsAgentBackend() && !servercfg.IsRestBackend() {
  68. fmt.Println("Oops! No Server Mode selected. Nothing is being served! Set either Agent mode (AGENT_BACKEND) or Rest mode (REST_BACKEND) to 'true'.")
  69. }
  70. waitnetwork.Wait()
  71. fmt.Println("Exiting now.")
  72. }
  73. func runGRPC(wg *sync.WaitGroup, installserver bool) {
  74. defer wg.Done()
  75. // Configure 'log' package to give file name and line number on eg. log.Fatal
  76. // Pipe flags to one another (log.LstdFLags = log.Ldate | log.Ltime)
  77. log.SetFlags(log.LstdFlags | log.Lshortfile)
  78. grpcport := servercfg.GetGRPCPort()
  79. listener, err := net.Listen("tcp", ":"+grpcport)
  80. // Handle errors if any
  81. if err != nil {
  82. log.Fatalf("Unable to listen on port" + grpcport + ": %v", err)
  83. }
  84. s := grpc.NewServer(
  85. authServerUnaryInterceptor(),
  86. authServerStreamInterceptor(),
  87. )
  88. // Create NodeService type
  89. srv := &service.NodeServiceServer{}
  90. // Register the service with the server
  91. nodepb.RegisterNodeServiceServer(s, srv)
  92. srv.NodeDB = mongoconn.NodeDB
  93. // Start the server in a child routine
  94. go func() {
  95. if err := s.Serve(listener); err != nil {
  96. log.Fatalf("Failed to serve: %v", err)
  97. }
  98. }()
  99. fmt.Println("Agent Server succesfully started on port " + grpcport + " (gRPC)")
  100. if installserver {
  101. fmt.Println("Adding server to default network")
  102. success, err := serverctl.AddNetwork("default")
  103. if err != nil {
  104. fmt.Printf("Error adding to default network: %v", err)
  105. fmt.Println("")
  106. fmt.Println("Unable to add server to network. Continuing.")
  107. fmt.Println("Please investigate client installation on server.")
  108. } else if !success {
  109. fmt.Println("Unable to add server to network. Continuing.")
  110. fmt.Println("Please investigate client installation on server.")
  111. } else{
  112. fmt.Println("Server successfully added to default network.")
  113. }
  114. }
  115. fmt.Println("Setup complete. You are ready to begin using netmaker.")
  116. // Right way to stop the server using a SHUTDOWN HOOK
  117. // Create a channel to receive OS signals
  118. c := make(chan os.Signal)
  119. // Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
  120. // Ignore other incoming signals
  121. signal.Notify(c, os.Interrupt)
  122. // Block main routine until a signal is received
  123. // As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
  124. <-c
  125. // After receiving CTRL+C Properly stop the server
  126. fmt.Println("Stopping the Agent server...")
  127. s.Stop()
  128. listener.Close()
  129. fmt.Println("Agent server closed..")
  130. fmt.Println("Closing MongoDB connection")
  131. mongoconn.Client.Disconnect(context.TODO())
  132. fmt.Println("MongoDB connection closed.")
  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. }