main.go 5.6 KB

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