main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package main
  2. import (
  3. "context"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "net"
  10. "os"
  11. "os/signal"
  12. "runtime/debug"
  13. "strconv"
  14. "sync"
  15. "syscall"
  16. "time"
  17. "github.com/gravitl/netmaker/auth"
  18. "github.com/gravitl/netmaker/config"
  19. controller "github.com/gravitl/netmaker/controllers"
  20. "github.com/gravitl/netmaker/database"
  21. "github.com/gravitl/netmaker/functions"
  22. nodepb "github.com/gravitl/netmaker/grpc"
  23. "github.com/gravitl/netmaker/logger"
  24. "github.com/gravitl/netmaker/logic"
  25. "github.com/gravitl/netmaker/models"
  26. "github.com/gravitl/netmaker/mq"
  27. "github.com/gravitl/netmaker/netclient/ncutils"
  28. "github.com/gravitl/netmaker/servercfg"
  29. "github.com/gravitl/netmaker/serverctl"
  30. "github.com/gravitl/netmaker/tls"
  31. "google.golang.org/grpc"
  32. )
  33. var version = "dev"
  34. // Start DB Connection and start API Request Handler
  35. func main() {
  36. absoluteConfigPath := flag.String("c", "", "absolute path to configuration file")
  37. flag.Parse()
  38. setupConfig(*absoluteConfigPath)
  39. servercfg.SetVersion(version)
  40. fmt.Println(models.RetrieveLogo()) // print the logo
  41. initialize() // initial db and grpc server
  42. setGarbageCollection()
  43. defer database.CloseDB()
  44. startControllers() // start the grpc or rest endpoints
  45. }
  46. func setupConfig(absoluteConfigPath string) {
  47. if len(absoluteConfigPath) > 0 {
  48. cfg, err := config.ReadConfig(absoluteConfigPath)
  49. if err != nil {
  50. logger.Log(0, fmt.Sprintf("failed parsing config at: %s", absoluteConfigPath))
  51. return
  52. }
  53. config.Config = cfg
  54. }
  55. }
  56. func initialize() { // Client Mode Prereq Check
  57. var err error
  58. if servercfg.GetMasterKey() == "" {
  59. logger.Log(0, "warning: MASTER_KEY not set, this could make account recovery difficult")
  60. }
  61. if servercfg.GetNodeID() == "" {
  62. logger.FatalLog("error: must set NODE_ID, currently blank")
  63. }
  64. if err = database.InitializeDatabase(); err != nil {
  65. logger.FatalLog("Error connecting to database")
  66. }
  67. logger.Log(0, "database successfully connected")
  68. logic.SetJWTSecret()
  69. err = logic.TimerCheckpoint()
  70. if err != nil {
  71. logger.Log(1, "Timer error occurred: ", err.Error())
  72. }
  73. var authProvider = auth.InitializeAuthProvider()
  74. if authProvider != "" {
  75. logger.Log(0, "OAuth provider,", authProvider+",", "initialized")
  76. } else {
  77. logger.Log(0, "no OAuth provider found or not configured, continuing without OAuth")
  78. }
  79. err = serverctl.SetDefaultACLS()
  80. if err != nil {
  81. logger.FatalLog("error setting default acls: ", err.Error())
  82. }
  83. if servercfg.IsClientMode() != "off" {
  84. output, err := ncutils.RunCmd("id -u", true)
  85. if err != nil {
  86. logger.FatalLog("Error running 'id -u' for prereq check. Please investigate or disable client mode.", output, err.Error())
  87. }
  88. uid, err := strconv.Atoi(string(output[:len(output)-1]))
  89. if err != nil {
  90. logger.FatalLog("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.", err.Error())
  91. }
  92. if uid != 0 {
  93. logger.FatalLog("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
  94. }
  95. if err := serverctl.InitServerNetclient(); err != nil {
  96. logger.FatalLog("Did not find netclient to use CLIENT_MODE")
  97. }
  98. }
  99. // initialize iptables to ensure gateways work correctly and mq is forwarded if containerized
  100. if servercfg.ManageIPTables() != "off" {
  101. if err = serverctl.InitIPTables(true); err != nil {
  102. logger.FatalLog("Unable to initialize iptables on host:", err.Error())
  103. }
  104. }
  105. if servercfg.IsDNSMode() {
  106. err := functions.SetDNSDir()
  107. if err != nil {
  108. logger.FatalLog(err.Error())
  109. }
  110. }
  111. genCerts()
  112. }
  113. func startControllers() {
  114. var waitnetwork sync.WaitGroup
  115. //Run Agent Server
  116. if servercfg.IsAgentBackend() {
  117. if !(servercfg.DisableRemoteIPCheck()) && servercfg.GetGRPCHost() == "127.0.0.1" {
  118. err := servercfg.SetHost()
  119. if err != nil {
  120. logger.FatalLog("Unable to Set host. Exiting...", err.Error())
  121. }
  122. }
  123. waitnetwork.Add(1)
  124. go runGRPC(&waitnetwork)
  125. }
  126. if servercfg.IsDNSMode() {
  127. err := logic.SetDNS()
  128. if err != nil {
  129. logger.Log(0, "error occurred initializing DNS: ", err.Error())
  130. }
  131. }
  132. //Run Rest Server
  133. if servercfg.IsRestBackend() {
  134. if !servercfg.DisableRemoteIPCheck() && servercfg.GetAPIHost() == "127.0.0.1" {
  135. err := servercfg.SetHost()
  136. if err != nil {
  137. logger.FatalLog("Unable to Set host. Exiting...", err.Error())
  138. }
  139. }
  140. waitnetwork.Add(1)
  141. go controller.HandleRESTRequests(&waitnetwork)
  142. }
  143. //Run MessageQueue
  144. if servercfg.IsMessageQueueBackend() {
  145. waitnetwork.Add(1)
  146. go runMessageQueue(&waitnetwork)
  147. }
  148. if !servercfg.IsAgentBackend() && !servercfg.IsRestBackend() && !servercfg.IsMessageQueueBackend() {
  149. logger.Log(0, "No Server Mode selected, so nothing is being served! Set Agent mode (AGENT_BACKEND) or Rest mode (REST_BACKEND) or MessageQueue (MESSAGEQUEUE_BACKEND) to 'true'.")
  150. }
  151. waitnetwork.Wait()
  152. }
  153. func runGRPC(wg *sync.WaitGroup) {
  154. defer wg.Done()
  155. grpcport := servercfg.GetGRPCPort()
  156. listener, err := net.Listen("tcp", ":"+grpcport)
  157. // Handle errors if any
  158. if err != nil {
  159. logger.FatalLog("[netmaker] Unable to listen on port", grpcport, ": error:", err.Error())
  160. }
  161. s := grpc.NewServer(
  162. authServerUnaryInterceptor(),
  163. )
  164. // Create NodeService type
  165. srv := &controller.NodeServiceServer{}
  166. // Register the service with the server
  167. nodepb.RegisterNodeServiceServer(s, srv)
  168. // Start the server in a child routine
  169. go func() {
  170. if err := s.Serve(listener); err != nil {
  171. logger.FatalLog("Failed to serve:", err.Error())
  172. }
  173. }()
  174. logger.Log(0, "Agent Server successfully started on port ", grpcport, "(gRPC)")
  175. // Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
  176. // Ignore other incoming signals
  177. ctx, stop := signal.NotifyContext(context.TODO(), os.Interrupt)
  178. defer stop()
  179. // Block main routine until a signal is received
  180. // As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
  181. <-ctx.Done()
  182. // After receiving CTRL+C Properly stop the server
  183. logger.Log(0, "Stopping the Agent server...")
  184. s.GracefulStop()
  185. listener.Close()
  186. logger.Log(0, "Agent server closed..")
  187. logger.Log(0, "Closed DB connection.")
  188. }
  189. // Should we be using a context vice a waitgroup????????????
  190. func runMessageQueue(wg *sync.WaitGroup) {
  191. defer wg.Done()
  192. logger.Log(0, "connecting to mq broker at", servercfg.GetMessageQueueEndpoint())
  193. var client = mq.SetupMQTT(false) // Set up the subscription listener
  194. ctx, cancel := context.WithCancel(context.Background())
  195. go mq.Keepalive(ctx)
  196. quit := make(chan os.Signal, 1)
  197. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  198. <-quit
  199. cancel()
  200. logger.Log(0, "Message Queue shutting down")
  201. client.Disconnect(250)
  202. }
  203. func authServerUnaryInterceptor() grpc.ServerOption {
  204. return grpc.UnaryInterceptor(controller.AuthServerUnaryInterceptor)
  205. }
  206. func setGarbageCollection() {
  207. _, gcset := os.LookupEnv("GOGC")
  208. if !gcset {
  209. debug.SetGCPercent(ncutils.DEFAULT_GC_PERCENT)
  210. }
  211. }
  212. func genCerts() error {
  213. private, err := tls.ReadKey(functions.GetNetmakerPath())
  214. if errors.Is(err, os.ErrNotExist) {
  215. _, *private, err = ed25519.GenerateKey(rand.Reader)
  216. if err != nil {
  217. return err
  218. }
  219. if err := tls.SaveKey(functions.GetNetmakerPath(), "/root.key", *private); err != nil {
  220. return err
  221. }
  222. } else if err != nil {
  223. return err
  224. }
  225. ca, err := tls.ReadCert(functions.GetNetmakerPath() + "/root.pem")
  226. //if cert doesn't exist or will expire within 10 days --- but can't do this as clients won't be able to connect
  227. //if errors.Is(err, os.ErrNotExist) || cert.NotAfter.Before(time.Now().Add(time.Hour*24*10)) {
  228. if errors.Is(err, os.ErrNotExist) {
  229. caName := tls.NewName("CA Root", "US", "Gravitl")
  230. csr, err := tls.NewCSR(*private, caName)
  231. if err != nil {
  232. return err
  233. }
  234. rootCA, err := tls.SelfSignedCA(*private, csr, tls.CERTIFICATE_VALIDITY)
  235. if err != nil {
  236. return err
  237. }
  238. if err := tls.SaveCert(functions.GetNetmakerPath(), "/root.pem", rootCA); err != nil {
  239. return err
  240. }
  241. } else if err != nil {
  242. return err
  243. }
  244. cert, err := tls.ReadCert(functions.GetNetmakerPath() + "/server.pem")
  245. if errors.Is(err, os.ErrNotExist) || cert.NotAfter.Before(time.Now().Add(time.Hour*24*10)) {
  246. //gen new key
  247. _, key, err := ed25519.GenerateKey(rand.Reader)
  248. if err != nil {
  249. return err
  250. }
  251. serverName := tls.NewCName(servercfg.GetServer())
  252. csr, err := tls.NewCSR(key, serverName)
  253. if err != nil {
  254. return err
  255. }
  256. cert, err := tls.NewEndEntityCert(*private, csr, ca, tls.CERTIFICATE_VALIDITY)
  257. if err != nil {
  258. return err
  259. }
  260. if err := tls.SaveKey(functions.GetNetmakerPath(), "/server.key", key); err != nil {
  261. return err
  262. }
  263. if err := tls.SaveCert(functions.GetNetmakerPath(), "/server.pem", cert); err != nil {
  264. return err
  265. }
  266. } else if err != nil {
  267. return err
  268. }
  269. return nil
  270. }