serverconf.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. package servercfg
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/gravitl/netmaker/config"
  11. "github.com/gravitl/netmaker/models"
  12. )
  13. // EmqxBrokerType denotes the broker type for EMQX MQTT
  14. const EmqxBrokerType = "emqx"
  15. var (
  16. Version = "dev"
  17. Is_EE = false
  18. )
  19. // SetHost - sets the host ip
  20. func SetHost() error {
  21. remoteip, err := GetPublicIP()
  22. if err != nil {
  23. return err
  24. }
  25. os.Setenv("SERVER_HOST", remoteip)
  26. return nil
  27. }
  28. // GetServerConfig - gets the server config into memory from file or env
  29. func GetServerConfig() config.ServerConfig {
  30. var cfg config.ServerConfig
  31. cfg.APIConnString = GetAPIConnString()
  32. cfg.CoreDNSAddr = GetCoreDNSAddr()
  33. cfg.APIHost = GetAPIHost()
  34. cfg.APIPort = GetAPIPort()
  35. cfg.MasterKey = "(hidden)"
  36. cfg.DNSKey = "(hidden)"
  37. cfg.AllowedOrigin = GetAllowedOrigin()
  38. cfg.RestBackend = "off"
  39. cfg.NodeID = GetNodeID()
  40. cfg.StunHost = GetStunAddr()
  41. cfg.StunPort = GetStunPort()
  42. cfg.BrokerType = GetBrokerType()
  43. cfg.EmqxRestEndpoint = GetEmqxRestEndpoint()
  44. if IsRestBackend() {
  45. cfg.RestBackend = "on"
  46. }
  47. cfg.AgentBackend = "off"
  48. if IsAgentBackend() {
  49. cfg.AgentBackend = "on"
  50. }
  51. cfg.DNSMode = "off"
  52. if IsDNSMode() {
  53. cfg.DNSMode = "on"
  54. }
  55. cfg.DisplayKeys = "off"
  56. if IsDisplayKeys() {
  57. cfg.DisplayKeys = "on"
  58. }
  59. cfg.DisableRemoteIPCheck = "off"
  60. if DisableRemoteIPCheck() {
  61. cfg.DisableRemoteIPCheck = "on"
  62. }
  63. cfg.Database = GetDB()
  64. cfg.Platform = GetPlatform()
  65. cfg.Version = GetVersion()
  66. // == auth config ==
  67. var authInfo = GetAuthProviderInfo()
  68. cfg.AuthProvider = authInfo[0]
  69. cfg.ClientID = authInfo[1]
  70. cfg.ClientSecret = authInfo[2]
  71. cfg.FrontendURL = GetFrontendURL()
  72. cfg.Telemetry = Telemetry()
  73. cfg.Server = GetServer()
  74. cfg.Verbosity = GetVerbosity()
  75. cfg.IsEE = "no"
  76. if Is_EE {
  77. cfg.IsEE = "yes"
  78. }
  79. return cfg
  80. }
  81. // GetServerConfig - gets the server config into memory from file or env
  82. func GetServerInfo() models.ServerConfig {
  83. var cfg models.ServerConfig
  84. cfg.Server = GetServer()
  85. cfg.MQUserName = GetMqUserName()
  86. cfg.MQPassword = GetMqPassword()
  87. cfg.API = GetAPIConnString()
  88. cfg.CoreDNSAddr = GetCoreDNSAddr()
  89. cfg.APIPort = GetAPIPort()
  90. cfg.DNSMode = "off"
  91. if IsDNSMode() {
  92. cfg.DNSMode = "on"
  93. }
  94. cfg.Version = GetVersion()
  95. cfg.Is_EE = Is_EE
  96. cfg.StunHost = GetStunAddr()
  97. cfg.StunPort = GetStunPort()
  98. return cfg
  99. }
  100. // GetFrontendURL - gets the frontend url
  101. func GetFrontendURL() string {
  102. var frontend = ""
  103. if os.Getenv("FRONTEND_URL") != "" {
  104. frontend = os.Getenv("FRONTEND_URL")
  105. } else if config.Config.Server.FrontendURL != "" {
  106. frontend = config.Config.Server.FrontendURL
  107. }
  108. return frontend
  109. }
  110. // GetAPIConnString - gets the api connections string
  111. func GetAPIConnString() string {
  112. conn := ""
  113. if os.Getenv("SERVER_API_CONN_STRING") != "" {
  114. conn = os.Getenv("SERVER_API_CONN_STRING")
  115. } else if config.Config.Server.APIConnString != "" {
  116. conn = config.Config.Server.APIConnString
  117. }
  118. return conn
  119. }
  120. // SetVersion - set version of netmaker
  121. func SetVersion(v string) {
  122. Version = v
  123. }
  124. // GetVersion - version of netmaker
  125. func GetVersion() string {
  126. return Version
  127. }
  128. // GetDB - gets the database type
  129. func GetDB() string {
  130. database := "sqlite"
  131. if os.Getenv("DATABASE") != "" {
  132. database = os.Getenv("DATABASE")
  133. } else if config.Config.Server.Database != "" {
  134. database = config.Config.Server.Database
  135. }
  136. return database
  137. }
  138. // GetAPIHost - gets the api host
  139. func GetAPIHost() string {
  140. serverhost := "127.0.0.1"
  141. remoteip, _ := GetPublicIP()
  142. if os.Getenv("SERVER_HTTP_HOST") != "" {
  143. serverhost = os.Getenv("SERVER_HTTP_HOST")
  144. } else if config.Config.Server.APIHost != "" {
  145. serverhost = config.Config.Server.APIHost
  146. } else if os.Getenv("SERVER_HOST") != "" {
  147. serverhost = os.Getenv("SERVER_HOST")
  148. } else {
  149. if remoteip != "" {
  150. serverhost = remoteip
  151. }
  152. }
  153. return serverhost
  154. }
  155. // GetPodIP - get the pod's ip
  156. func GetPodIP() string {
  157. podip := "127.0.0.1"
  158. if os.Getenv("POD_IP") != "" {
  159. podip = os.Getenv("POD_IP")
  160. }
  161. return podip
  162. }
  163. // GetAPIPort - gets the api port
  164. func GetAPIPort() string {
  165. apiport := "8081"
  166. if os.Getenv("API_PORT") != "" {
  167. apiport = os.Getenv("API_PORT")
  168. } else if config.Config.Server.APIPort != "" {
  169. apiport = config.Config.Server.APIPort
  170. }
  171. return apiport
  172. }
  173. // GetStunAddr - gets the stun host address
  174. func GetStunAddr() string {
  175. stunAddr := ""
  176. if os.Getenv("STUN_DOMAIN") != "" {
  177. stunAddr = os.Getenv("STUN_DOMAIN")
  178. } else if config.Config.Server.StunHost != "" {
  179. stunAddr = config.Config.Server.StunHost
  180. }
  181. return stunAddr
  182. }
  183. // GetDefaultNodeLimit - get node limit if one is set
  184. func GetDefaultNodeLimit() int32 {
  185. var limit int32
  186. limit = 999999999
  187. envlimit, err := strconv.Atoi(os.Getenv("DEFAULT_NODE_LIMIT"))
  188. if err == nil && envlimit != 0 {
  189. limit = int32(envlimit)
  190. } else if config.Config.Server.DefaultNodeLimit != 0 {
  191. limit = config.Config.Server.DefaultNodeLimit
  192. }
  193. return limit
  194. }
  195. // GetCoreDNSAddr - gets the core dns address
  196. func GetCoreDNSAddr() string {
  197. addr, _ := GetPublicIP()
  198. if os.Getenv("COREDNS_ADDR") != "" {
  199. addr = os.Getenv("COREDNS_ADDR")
  200. } else if config.Config.Server.CoreDNSAddr != "" {
  201. addr = config.Config.Server.CoreDNSAddr
  202. }
  203. return addr
  204. }
  205. // GetMessageQueueEndpoint - gets the message queue endpoint
  206. func GetMessageQueueEndpoint() (string, bool) {
  207. host, _ := GetPublicIP()
  208. if os.Getenv("SERVER_BROKER_ENDPOINT") != "" {
  209. host = os.Getenv("SERVER_BROKER_ENDPOINT")
  210. } else if config.Config.Server.ServerBrokerEndpoint != "" {
  211. host = config.Config.Server.ServerBrokerEndpoint
  212. } else if os.Getenv("BROKER_ENDPOINT") != "" {
  213. host = os.Getenv("BROKER_ENDPOINT")
  214. } else if config.Config.Server.BrokerEndpoint != "" {
  215. host = config.Config.Server.BrokerEndpoint
  216. } else {
  217. host += ":1883" // default
  218. }
  219. return host, strings.Contains(host, "wss") || strings.Contains(host, "ssl")
  220. }
  221. // GetBrokerType - returns the type of MQ broker
  222. func GetBrokerType() string {
  223. if os.Getenv("BROKER_TYPE") != "" {
  224. return os.Getenv("BROKER_TYPE")
  225. } else {
  226. return "mosquitto"
  227. }
  228. }
  229. // GetMasterKey - gets the configured master key of server
  230. func GetMasterKey() string {
  231. key := ""
  232. if os.Getenv("MASTER_KEY") != "" {
  233. key = os.Getenv("MASTER_KEY")
  234. } else if config.Config.Server.MasterKey != "" {
  235. key = config.Config.Server.MasterKey
  236. }
  237. return key
  238. }
  239. // GetDNSKey - gets the configured dns key of server
  240. func GetDNSKey() string {
  241. key := "secretkey"
  242. if os.Getenv("DNS_KEY") != "" {
  243. key = os.Getenv("DNS_KEY")
  244. } else if config.Config.Server.DNSKey != "" {
  245. key = config.Config.Server.DNSKey
  246. }
  247. return key
  248. }
  249. // GetAllowedOrigin - get the allowed origin
  250. func GetAllowedOrigin() string {
  251. allowedorigin := "*"
  252. if os.Getenv("CORS_ALLOWED_ORIGIN") != "" {
  253. allowedorigin = os.Getenv("CORS_ALLOWED_ORIGIN")
  254. } else if config.Config.Server.AllowedOrigin != "" {
  255. allowedorigin = config.Config.Server.AllowedOrigin
  256. }
  257. return allowedorigin
  258. }
  259. // IsRestBackend - checks if rest is on or off
  260. func IsRestBackend() bool {
  261. isrest := true
  262. if os.Getenv("REST_BACKEND") != "" {
  263. if os.Getenv("REST_BACKEND") == "off" {
  264. isrest = false
  265. }
  266. } else if config.Config.Server.RestBackend != "" {
  267. if config.Config.Server.RestBackend == "off" {
  268. isrest = false
  269. }
  270. }
  271. return isrest
  272. }
  273. // IsMetricsExporter - checks if metrics exporter is on or off
  274. func IsMetricsExporter() bool {
  275. export := false
  276. if os.Getenv("METRICS_EXPORTER") != "" {
  277. if os.Getenv("METRICS_EXPORTER") == "on" {
  278. export = true
  279. }
  280. } else if config.Config.Server.MetricsExporter != "" {
  281. if config.Config.Server.MetricsExporter == "on" {
  282. export = true
  283. }
  284. }
  285. return export
  286. }
  287. // IsAgentBackend - checks if agent backed is on or off
  288. func IsAgentBackend() bool {
  289. isagent := true
  290. if os.Getenv("AGENT_BACKEND") != "" {
  291. if os.Getenv("AGENT_BACKEND") == "off" {
  292. isagent = false
  293. }
  294. } else if config.Config.Server.AgentBackend != "" {
  295. if config.Config.Server.AgentBackend == "off" {
  296. isagent = false
  297. }
  298. }
  299. return isagent
  300. }
  301. // IsMessageQueueBackend - checks if message queue is on or off
  302. func IsMessageQueueBackend() bool {
  303. ismessagequeue := true
  304. if os.Getenv("MESSAGEQUEUE_BACKEND") != "" {
  305. if os.Getenv("MESSAGEQUEUE_BACKEND") == "off" {
  306. ismessagequeue = false
  307. }
  308. } else if config.Config.Server.MessageQueueBackend != "" {
  309. if config.Config.Server.MessageQueueBackend == "off" {
  310. ismessagequeue = false
  311. }
  312. }
  313. return ismessagequeue
  314. }
  315. // Telemetry - checks if telemetry data should be sent
  316. func Telemetry() string {
  317. telemetry := "on"
  318. if os.Getenv("TELEMETRY") == "off" {
  319. telemetry = "off"
  320. }
  321. if config.Config.Server.Telemetry == "off" {
  322. telemetry = "off"
  323. }
  324. return telemetry
  325. }
  326. // GetServer - gets the server name
  327. func GetServer() string {
  328. server := ""
  329. if os.Getenv("SERVER_NAME") != "" {
  330. server = os.Getenv("SERVER_NAME")
  331. } else if config.Config.Server.Server != "" {
  332. server = config.Config.Server.Server
  333. }
  334. return server
  335. }
  336. func GetVerbosity() int32 {
  337. var verbosity = 0
  338. var err error
  339. if os.Getenv("VERBOSITY") != "" {
  340. verbosity, err = strconv.Atoi(os.Getenv("VERBOSITY"))
  341. if err != nil {
  342. verbosity = 0
  343. }
  344. } else if config.Config.Server.Verbosity != 0 {
  345. verbosity = int(config.Config.Server.Verbosity)
  346. }
  347. if verbosity < 0 || verbosity > 4 {
  348. verbosity = 0
  349. }
  350. return int32(verbosity)
  351. }
  352. // IsDNSMode - should it run with DNS
  353. func IsDNSMode() bool {
  354. isdns := true
  355. if os.Getenv("DNS_MODE") != "" {
  356. if os.Getenv("DNS_MODE") == "off" {
  357. isdns = false
  358. }
  359. } else if config.Config.Server.DNSMode != "" {
  360. if config.Config.Server.DNSMode == "off" {
  361. isdns = false
  362. }
  363. }
  364. return isdns
  365. }
  366. // IsDisplayKeys - should server be able to display keys?
  367. func IsDisplayKeys() bool {
  368. isdisplay := true
  369. if os.Getenv("DISPLAY_KEYS") != "" {
  370. if os.Getenv("DISPLAY_KEYS") == "off" {
  371. isdisplay = false
  372. }
  373. } else if config.Config.Server.DisplayKeys != "" {
  374. if config.Config.Server.DisplayKeys == "off" {
  375. isdisplay = false
  376. }
  377. }
  378. return isdisplay
  379. }
  380. // DisableRemoteIPCheck - disable the remote ip check
  381. func DisableRemoteIPCheck() bool {
  382. disabled := false
  383. if os.Getenv("DISABLE_REMOTE_IP_CHECK") != "" {
  384. if os.Getenv("DISABLE_REMOTE_IP_CHECK") == "on" {
  385. disabled = true
  386. }
  387. } else if config.Config.Server.DisableRemoteIPCheck != "" {
  388. if config.Config.Server.DisableRemoteIPCheck == "on" {
  389. disabled = true
  390. }
  391. }
  392. return disabled
  393. }
  394. // GetPublicIP - gets public ip
  395. func GetPublicIP() (string, error) {
  396. endpoint := ""
  397. var err error
  398. iplist := []string{"https://ip.server.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  399. publicIpService := os.Getenv("PUBLIC_IP_SERVICE")
  400. if publicIpService != "" {
  401. // prepend the user-specified service so it's checked first
  402. iplist = append([]string{publicIpService}, iplist...)
  403. } else if config.Config.Server.PublicIPService != "" {
  404. publicIpService = config.Config.Server.PublicIPService
  405. // prepend the user-specified service so it's checked first
  406. iplist = append([]string{publicIpService}, iplist...)
  407. }
  408. for _, ipserver := range iplist {
  409. client := &http.Client{
  410. Timeout: time.Second * 10,
  411. }
  412. resp, err := client.Get(ipserver)
  413. if err != nil {
  414. continue
  415. }
  416. defer resp.Body.Close()
  417. if resp.StatusCode == http.StatusOK {
  418. bodyBytes, err := io.ReadAll(resp.Body)
  419. if err != nil {
  420. continue
  421. }
  422. endpoint = string(bodyBytes)
  423. break
  424. }
  425. }
  426. if err == nil && endpoint == "" {
  427. err = errors.New("public address not found")
  428. }
  429. return endpoint, err
  430. }
  431. // GetPlatform - get the system type of server
  432. func GetPlatform() string {
  433. platform := "linux"
  434. if os.Getenv("PLATFORM") != "" {
  435. platform = os.Getenv("PLATFORM")
  436. } else if config.Config.Server.Platform != "" {
  437. platform = config.Config.Server.Platform
  438. }
  439. return platform
  440. }
  441. // GetSQLConn - get the sql connection string
  442. func GetSQLConn() string {
  443. sqlconn := "http://"
  444. if os.Getenv("SQL_CONN") != "" {
  445. sqlconn = os.Getenv("SQL_CONN")
  446. } else if config.Config.Server.SQLConn != "" {
  447. sqlconn = config.Config.Server.SQLConn
  448. }
  449. return sqlconn
  450. }
  451. // GetNodeID - gets the node id
  452. func GetNodeID() string {
  453. var id string
  454. var err error
  455. // id = getMacAddr()
  456. if os.Getenv("NODE_ID") != "" {
  457. id = os.Getenv("NODE_ID")
  458. } else if config.Config.Server.NodeID != "" {
  459. id = config.Config.Server.NodeID
  460. } else {
  461. id, err = os.Hostname()
  462. if err != nil {
  463. return ""
  464. }
  465. }
  466. return id
  467. }
  468. func SetNodeID(id string) {
  469. config.Config.Server.NodeID = id
  470. }
  471. // GetServerCheckinInterval - gets the server check-in time
  472. func GetServerCheckinInterval() int64 {
  473. var t = int64(5)
  474. var envt, _ = strconv.Atoi(os.Getenv("SERVER_CHECKIN_INTERVAL"))
  475. if envt > 0 {
  476. t = int64(envt)
  477. } else if config.Config.Server.ServerCheckinInterval > 0 {
  478. t = config.Config.Server.ServerCheckinInterval
  479. }
  480. return t
  481. }
  482. // GetAuthProviderInfo = gets the oauth provider info
  483. func GetAuthProviderInfo() (pi []string) {
  484. var authProvider = ""
  485. defer func() {
  486. if authProvider == "oidc" {
  487. if os.Getenv("OIDC_ISSUER") != "" {
  488. pi = append(pi, os.Getenv("OIDC_ISSUER"))
  489. } else if config.Config.Server.OIDCIssuer != "" {
  490. pi = append(pi, config.Config.Server.OIDCIssuer)
  491. } else {
  492. pi = []string{"", "", ""}
  493. }
  494. }
  495. }()
  496. if os.Getenv("AUTH_PROVIDER") != "" && os.Getenv("CLIENT_ID") != "" && os.Getenv("CLIENT_SECRET") != "" {
  497. authProvider = strings.ToLower(os.Getenv("AUTH_PROVIDER"))
  498. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" || authProvider == "oidc" {
  499. return []string{authProvider, os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")}
  500. } else {
  501. authProvider = ""
  502. }
  503. } else if config.Config.Server.AuthProvider != "" && config.Config.Server.ClientID != "" && config.Config.Server.ClientSecret != "" {
  504. authProvider = strings.ToLower(config.Config.Server.AuthProvider)
  505. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" || authProvider == "oidc" {
  506. return []string{authProvider, config.Config.Server.ClientID, config.Config.Server.ClientSecret}
  507. }
  508. }
  509. return []string{"", "", ""}
  510. }
  511. // GetAzureTenant - retrieve the azure tenant ID from env variable or config file
  512. func GetAzureTenant() string {
  513. var azureTenant = ""
  514. if os.Getenv("AZURE_TENANT") != "" {
  515. azureTenant = os.Getenv("AZURE_TENANT")
  516. } else if config.Config.Server.AzureTenant != "" {
  517. azureTenant = config.Config.Server.AzureTenant
  518. }
  519. return azureTenant
  520. }
  521. // GetMqPassword - fetches the MQ password
  522. func GetMqPassword() string {
  523. password := ""
  524. if os.Getenv("MQ_PASSWORD") != "" {
  525. password = os.Getenv("MQ_PASSWORD")
  526. } else if config.Config.Server.MQPassword != "" {
  527. password = config.Config.Server.MQPassword
  528. }
  529. return password
  530. }
  531. // GetMqUserName - fetches the MQ username
  532. func GetMqUserName() string {
  533. password := ""
  534. if os.Getenv("MQ_USERNAME") != "" {
  535. password = os.Getenv("MQ_USERNAME")
  536. } else if config.Config.Server.MQUserName != "" {
  537. password = config.Config.Server.MQUserName
  538. }
  539. return password
  540. }
  541. // GetEmqxRestEndpoint - returns the REST API Endpoint of EMQX
  542. func GetEmqxRestEndpoint() string {
  543. return os.Getenv("EMQX_REST_ENDPOINT")
  544. }
  545. // IsBasicAuthEnabled - checks if basic auth has been configured to be turned off
  546. func IsBasicAuthEnabled() bool {
  547. var enabled = true //default
  548. if os.Getenv("BASIC_AUTH") != "" {
  549. enabled = os.Getenv("BASIC_AUTH") == "yes"
  550. } else if config.Config.Server.BasicAuth != "" {
  551. enabled = config.Config.Server.BasicAuth == "yes"
  552. }
  553. return enabled
  554. }
  555. // GetLicenseKey - retrieves pro license value from env or conf files
  556. func GetLicenseKey() string {
  557. licenseKeyValue := os.Getenv("LICENSE_KEY")
  558. if licenseKeyValue == "" {
  559. licenseKeyValue = config.Config.Server.LicenseValue
  560. }
  561. return licenseKeyValue
  562. }
  563. // GetNetmakerAccountID - get's the associated, Netmaker, account ID to verify ownership
  564. func GetNetmakerAccountID() string {
  565. netmakerAccountID := os.Getenv("NETMAKER_ACCOUNT_ID")
  566. if netmakerAccountID == "" {
  567. netmakerAccountID = config.Config.Server.NetmakerAccountID
  568. }
  569. return netmakerAccountID
  570. }
  571. func GetStunPort() int {
  572. port := 3478 //default
  573. if os.Getenv("STUN_PORT") != "" {
  574. portInt, err := strconv.Atoi(os.Getenv("STUN_PORT"))
  575. if err == nil {
  576. port = portInt
  577. }
  578. } else if config.Config.Server.StunPort != 0 {
  579. port = config.Config.Server.StunPort
  580. }
  581. return port
  582. }
  583. func IsProxyEnabled() bool {
  584. var enabled = false //default
  585. if os.Getenv("PROXY") != "" {
  586. enabled = os.Getenv("PROXY") == "on"
  587. } else if config.Config.Server.Proxy != "" {
  588. enabled = config.Config.Server.Proxy == "on"
  589. }
  590. return enabled
  591. }