serverconf.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. package servercfg
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "os"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/gravitl/netmaker/config"
  12. "github.com/gravitl/netmaker/models"
  13. "golang.org/x/exp/slog"
  14. )
  15. // EmqxBrokerType denotes the broker type for EMQX MQTT
  16. const EmqxBrokerType = "emqx"
  17. // Emqxdeploy - emqx deploy type
  18. type Emqxdeploy string
  19. var (
  20. Version = "dev"
  21. IsPro = false
  22. ErrLicenseValidation error
  23. EmqxCloudDeploy Emqxdeploy = "cloud"
  24. EmqxOnPremDeploy Emqxdeploy = "on-prem"
  25. )
  26. // SetHost - sets the host ip
  27. func SetHost() error {
  28. remoteip, err := GetPublicIP()
  29. if err != nil {
  30. return err
  31. }
  32. os.Setenv("SERVER_HOST", remoteip)
  33. return nil
  34. }
  35. // GetServerConfig - gets the server config into memory from file or env
  36. func GetServerConfig() config.ServerConfig {
  37. var cfg config.ServerConfig
  38. cfg.APIConnString = GetAPIConnString()
  39. cfg.CoreDNSAddr = GetCoreDNSAddr()
  40. cfg.APIHost = GetAPIHost()
  41. cfg.APIPort = GetAPIPort()
  42. cfg.MasterKey = "(hidden)"
  43. cfg.DNSKey = "(hidden)"
  44. cfg.AllowedOrigin = GetAllowedOrigin()
  45. cfg.RestBackend = "off"
  46. cfg.NodeID = GetNodeID()
  47. cfg.BrokerType = GetBrokerType()
  48. cfg.EmqxRestEndpoint = GetEmqxRestEndpoint()
  49. if AutoUpdateEnabled() {
  50. cfg.NetclientAutoUpdate = "enabled"
  51. } else {
  52. cfg.NetclientAutoUpdate = "disabled"
  53. }
  54. if IsRestBackend() {
  55. cfg.RestBackend = "on"
  56. }
  57. cfg.DNSMode = "off"
  58. if IsDNSMode() {
  59. cfg.DNSMode = "on"
  60. }
  61. cfg.DisplayKeys = "off"
  62. if IsDisplayKeys() {
  63. cfg.DisplayKeys = "on"
  64. }
  65. cfg.DisableRemoteIPCheck = "off"
  66. if DisableRemoteIPCheck() {
  67. cfg.DisableRemoteIPCheck = "on"
  68. }
  69. cfg.Database = GetDB()
  70. cfg.Platform = GetPlatform()
  71. cfg.Version = GetVersion()
  72. cfg.PublicIp, _ = GetPublicIP()
  73. // == auth config ==
  74. var authInfo = GetAuthProviderInfo()
  75. cfg.AuthProvider = authInfo[0]
  76. cfg.ClientID = authInfo[1]
  77. cfg.ClientSecret = authInfo[2]
  78. cfg.FrontendURL = GetFrontendURL()
  79. cfg.Telemetry = Telemetry()
  80. cfg.Server = GetServer()
  81. cfg.Verbosity = GetVerbosity()
  82. cfg.IsPro = "no"
  83. if IsPro {
  84. cfg.IsPro = "yes"
  85. }
  86. cfg.JwtValidityDuration = GetJwtValidityDuration()
  87. cfg.RacAutoDisable = GetRacAutoDisable()
  88. cfg.MetricInterval = GetMetricInterval()
  89. cfg.ManageDNS = GetManageDNS()
  90. cfg.DefaultDomain = GetDefaultDomain()
  91. return cfg
  92. }
  93. // GetJwtValidityDuration - returns the JWT validity duration in seconds
  94. func GetJwtValidityDuration() time.Duration {
  95. var defaultDuration = time.Duration(24) * time.Hour
  96. if os.Getenv("JWT_VALIDITY_DURATION") != "" {
  97. t, err := strconv.Atoi(os.Getenv("JWT_VALIDITY_DURATION"))
  98. if err != nil {
  99. return defaultDuration
  100. }
  101. return time.Duration(t) * time.Second
  102. }
  103. return defaultDuration
  104. }
  105. // GetRacAutoDisable - returns whether the feature to autodisable RAC is enabled
  106. func GetRacAutoDisable() bool {
  107. return os.Getenv("RAC_AUTO_DISABLE") == "true"
  108. }
  109. // GetServerInfo - gets the server config into memory from file or env
  110. func GetServerInfo() models.ServerConfig {
  111. var cfg models.ServerConfig
  112. cfg.Server = GetServer()
  113. if GetBrokerType() == EmqxBrokerType {
  114. cfg.MQUserName = "HOST_ID"
  115. cfg.MQPassword = "HOST_PASS"
  116. } else {
  117. cfg.MQUserName = GetMqUserName()
  118. cfg.MQPassword = GetMqPassword()
  119. }
  120. cfg.API = GetAPIConnString()
  121. cfg.CoreDNSAddr = GetCoreDNSAddr()
  122. cfg.APIPort = GetAPIPort()
  123. cfg.DNSMode = "off"
  124. cfg.Broker = GetPublicBrokerEndpoint()
  125. cfg.BrokerType = GetBrokerType()
  126. if IsDNSMode() {
  127. cfg.DNSMode = "on"
  128. }
  129. cfg.Version = GetVersion()
  130. cfg.IsPro = IsPro
  131. cfg.MetricInterval = GetMetricInterval()
  132. cfg.ManageDNS = GetManageDNS()
  133. cfg.DefaultDomain = GetDefaultDomain()
  134. return cfg
  135. }
  136. // GetFrontendURL - gets the frontend url
  137. func GetFrontendURL() string {
  138. var frontend = ""
  139. if os.Getenv("FRONTEND_URL") != "" {
  140. frontend = os.Getenv("FRONTEND_URL")
  141. } else if config.Config.Server.FrontendURL != "" {
  142. frontend = config.Config.Server.FrontendURL
  143. }
  144. return frontend
  145. }
  146. // GetAPIConnString - gets the api connections string
  147. func GetAPIConnString() string {
  148. conn := ""
  149. if os.Getenv("SERVER_API_CONN_STRING") != "" {
  150. conn = os.Getenv("SERVER_API_CONN_STRING")
  151. } else if config.Config.Server.APIConnString != "" {
  152. conn = config.Config.Server.APIConnString
  153. }
  154. return conn
  155. }
  156. // SetVersion - set version of netmaker
  157. func SetVersion(v string) {
  158. Version = v
  159. }
  160. // GetVersion - version of netmaker
  161. func GetVersion() string {
  162. return Version
  163. }
  164. // GetDB - gets the database type
  165. func GetDB() string {
  166. database := "sqlite"
  167. if os.Getenv("DATABASE") != "" {
  168. database = os.Getenv("DATABASE")
  169. } else if config.Config.Server.Database != "" {
  170. database = config.Config.Server.Database
  171. }
  172. return database
  173. }
  174. // CacheEnabled - checks if cache is enabled
  175. func CacheEnabled() bool {
  176. caching := true
  177. if os.Getenv("CACHING_ENABLED") == "false" {
  178. caching = false
  179. } else if config.Config.Server.CacheEnabled == "false" {
  180. caching = false
  181. }
  182. return caching
  183. }
  184. // GetAPIHost - gets the api host
  185. func GetAPIHost() string {
  186. serverhost := "127.0.0.1"
  187. remoteip, _ := GetPublicIP()
  188. if os.Getenv("SERVER_HTTP_HOST") != "" {
  189. serverhost = os.Getenv("SERVER_HTTP_HOST")
  190. } else if config.Config.Server.APIHost != "" {
  191. serverhost = config.Config.Server.APIHost
  192. } else if os.Getenv("SERVER_HOST") != "" {
  193. serverhost = os.Getenv("SERVER_HOST")
  194. } else {
  195. if remoteip != "" {
  196. serverhost = remoteip
  197. }
  198. }
  199. return serverhost
  200. }
  201. // GetAPIPort - gets the api port
  202. func GetAPIPort() string {
  203. apiport := "8081"
  204. if os.Getenv("API_PORT") != "" {
  205. apiport = os.Getenv("API_PORT")
  206. } else if config.Config.Server.APIPort != "" {
  207. apiport = config.Config.Server.APIPort
  208. }
  209. return apiport
  210. }
  211. // GetCoreDNSAddr - gets the core dns address
  212. func GetCoreDNSAddr() string {
  213. addr, _ := GetPublicIP()
  214. if os.Getenv("COREDNS_ADDR") != "" {
  215. addr = os.Getenv("COREDNS_ADDR")
  216. } else if config.Config.Server.CoreDNSAddr != "" {
  217. addr = config.Config.Server.CoreDNSAddr
  218. }
  219. return addr
  220. }
  221. // GetPublicBrokerEndpoint - returns the public broker endpoint which shall be used by netclient
  222. func GetPublicBrokerEndpoint() string {
  223. if os.Getenv("BROKER_ENDPOINT") != "" {
  224. return os.Getenv("BROKER_ENDPOINT")
  225. } else {
  226. return config.Config.Server.Broker
  227. }
  228. }
  229. func GetSmtpHost() string {
  230. v := ""
  231. if fromEnv := os.Getenv("SMTP_HOST"); fromEnv != "" {
  232. v = fromEnv
  233. } else if fromCfg := config.Config.Server.SmtpHost; fromCfg != "" {
  234. v = fromCfg
  235. }
  236. return v
  237. }
  238. func GetSmtpPort() int {
  239. v := 587
  240. if fromEnv := os.Getenv("SMTP_PORT"); fromEnv != "" {
  241. port, err := strconv.Atoi(fromEnv)
  242. if err == nil {
  243. v = port
  244. }
  245. } else if fromCfg := config.Config.Server.SmtpPort; fromCfg != 0 {
  246. v = fromCfg
  247. }
  248. return v
  249. }
  250. func GetSenderEmail() string {
  251. v := ""
  252. if fromEnv := os.Getenv("EMAIL_SENDER_ADDR"); fromEnv != "" {
  253. v = fromEnv
  254. } else if fromCfg := config.Config.Server.EmailSenderAddr; fromCfg != "" {
  255. v = fromCfg
  256. }
  257. return v
  258. }
  259. func GetSenderUser() string {
  260. v := ""
  261. if fromEnv := os.Getenv("EMAIL_SENDER_USER"); fromEnv != "" {
  262. v = fromEnv
  263. } else if fromCfg := config.Config.Server.EmailSenderUser; fromCfg != "" {
  264. v = fromCfg
  265. }
  266. return v
  267. }
  268. func GetEmaiSenderPassword() string {
  269. v := ""
  270. if fromEnv := os.Getenv("EMAIL_SENDER_PASSWORD"); fromEnv != "" {
  271. v = fromEnv
  272. } else if fromCfg := config.Config.Server.EmailSenderPassword; fromCfg != "" {
  273. v = fromCfg
  274. }
  275. return v
  276. }
  277. // GetOwnerEmail - gets the owner email (saas)
  278. func GetOwnerEmail() string {
  279. return os.Getenv("SAAS_OWNER_EMAIL")
  280. }
  281. // GetMessageQueueEndpoint - gets the message queue endpoint
  282. func GetMessageQueueEndpoint() (string, bool) {
  283. host, _ := GetPublicIP()
  284. if os.Getenv("SERVER_BROKER_ENDPOINT") != "" {
  285. host = os.Getenv("SERVER_BROKER_ENDPOINT")
  286. } else if config.Config.Server.ServerBrokerEndpoint != "" {
  287. host = config.Config.Server.ServerBrokerEndpoint
  288. } else if os.Getenv("BROKER_ENDPOINT") != "" {
  289. host = os.Getenv("BROKER_ENDPOINT")
  290. } else if config.Config.Server.Broker != "" {
  291. host = config.Config.Server.Broker
  292. } else {
  293. host += ":1883" // default
  294. }
  295. return host, strings.Contains(host, "wss") || strings.Contains(host, "ssl") || strings.Contains(host, "mqtts")
  296. }
  297. // GetBrokerType - returns the type of MQ broker
  298. func GetBrokerType() string {
  299. if os.Getenv("BROKER_TYPE") != "" {
  300. return os.Getenv("BROKER_TYPE")
  301. } else {
  302. return "mosquitto"
  303. }
  304. }
  305. // GetMasterKey - gets the configured master key of server
  306. func GetMasterKey() string {
  307. key := ""
  308. if os.Getenv("MASTER_KEY") != "" {
  309. key = os.Getenv("MASTER_KEY")
  310. } else if config.Config.Server.MasterKey != "" {
  311. key = config.Config.Server.MasterKey
  312. }
  313. return key
  314. }
  315. // GetAllowedOrigin - get the allowed origin
  316. func GetAllowedOrigin() string {
  317. allowedorigin := "*"
  318. if os.Getenv("CORS_ALLOWED_ORIGIN") != "" {
  319. allowedorigin = os.Getenv("CORS_ALLOWED_ORIGIN")
  320. } else if config.Config.Server.AllowedOrigin != "" {
  321. allowedorigin = config.Config.Server.AllowedOrigin
  322. }
  323. return allowedorigin
  324. }
  325. // IsRestBackend - checks if rest is on or off
  326. func IsRestBackend() bool {
  327. isrest := true
  328. if os.Getenv("REST_BACKEND") != "" {
  329. if os.Getenv("REST_BACKEND") == "off" {
  330. isrest = false
  331. }
  332. } else if config.Config.Server.RestBackend != "" {
  333. if config.Config.Server.RestBackend == "off" {
  334. isrest = false
  335. }
  336. }
  337. return isrest
  338. }
  339. // IsMetricsExporter - checks if metrics exporter is on or off
  340. func IsMetricsExporter() bool {
  341. export := false
  342. if os.Getenv("METRICS_EXPORTER") != "" {
  343. if os.Getenv("METRICS_EXPORTER") == "on" {
  344. export = true
  345. }
  346. } else if config.Config.Server.MetricsExporter != "" {
  347. if config.Config.Server.MetricsExporter == "on" {
  348. export = true
  349. }
  350. }
  351. return export
  352. }
  353. // IsMessageQueueBackend - checks if message queue is on or off
  354. func IsMessageQueueBackend() bool {
  355. ismessagequeue := true
  356. if os.Getenv("MESSAGEQUEUE_BACKEND") != "" {
  357. if os.Getenv("MESSAGEQUEUE_BACKEND") == "off" {
  358. ismessagequeue = false
  359. }
  360. } else if config.Config.Server.MessageQueueBackend != "" {
  361. if config.Config.Server.MessageQueueBackend == "off" {
  362. ismessagequeue = false
  363. }
  364. }
  365. return ismessagequeue
  366. }
  367. // Telemetry - checks if telemetry data should be sent
  368. func Telemetry() string {
  369. telemetry := "on"
  370. if os.Getenv("TELEMETRY") == "off" {
  371. telemetry = "off"
  372. }
  373. if config.Config.Server.Telemetry == "off" {
  374. telemetry = "off"
  375. }
  376. return telemetry
  377. }
  378. // GetServer - gets the server name
  379. func GetServer() string {
  380. server := ""
  381. if os.Getenv("SERVER_NAME") != "" {
  382. server = os.Getenv("SERVER_NAME")
  383. } else if config.Config.Server.Server != "" {
  384. server = config.Config.Server.Server
  385. }
  386. return server
  387. }
  388. func GetVerbosity() int32 {
  389. var verbosity = 0
  390. var err error
  391. if os.Getenv("VERBOSITY") != "" {
  392. verbosity, err = strconv.Atoi(os.Getenv("VERBOSITY"))
  393. if err != nil {
  394. verbosity = 0
  395. }
  396. } else if config.Config.Server.Verbosity != 0 {
  397. verbosity = int(config.Config.Server.Verbosity)
  398. }
  399. if verbosity < 0 || verbosity > 4 {
  400. verbosity = 0
  401. }
  402. return int32(verbosity)
  403. }
  404. // AutoUpdateEnabled returns a boolean indicating whether netclient auto update is enabled or disabled
  405. // default is enabled
  406. func AutoUpdateEnabled() bool {
  407. if os.Getenv("NETCLIENT_AUTO_UPDATE") == "disabled" {
  408. return false
  409. } else if config.Config.Server.NetclientAutoUpdate == "disabled" {
  410. return false
  411. }
  412. return true
  413. }
  414. // IsDNSMode - should it run with DNS
  415. func IsDNSMode() bool {
  416. isdns := true
  417. if os.Getenv("DNS_MODE") != "" {
  418. if os.Getenv("DNS_MODE") == "off" {
  419. isdns = false
  420. }
  421. } else if config.Config.Server.DNSMode != "" {
  422. if config.Config.Server.DNSMode == "off" {
  423. isdns = false
  424. }
  425. }
  426. return isdns
  427. }
  428. // IsDisplayKeys - should server be able to display keys?
  429. func IsDisplayKeys() bool {
  430. isdisplay := true
  431. if os.Getenv("DISPLAY_KEYS") != "" {
  432. if os.Getenv("DISPLAY_KEYS") == "off" {
  433. isdisplay = false
  434. }
  435. } else if config.Config.Server.DisplayKeys != "" {
  436. if config.Config.Server.DisplayKeys == "off" {
  437. isdisplay = false
  438. }
  439. }
  440. return isdisplay
  441. }
  442. // DisableRemoteIPCheck - disable the remote ip check
  443. func DisableRemoteIPCheck() bool {
  444. disabled := false
  445. if os.Getenv("DISABLE_REMOTE_IP_CHECK") != "" {
  446. if os.Getenv("DISABLE_REMOTE_IP_CHECK") == "on" {
  447. disabled = true
  448. }
  449. } else if config.Config.Server.DisableRemoteIPCheck != "" {
  450. if config.Config.Server.DisableRemoteIPCheck == "on" {
  451. disabled = true
  452. }
  453. }
  454. return disabled
  455. }
  456. // GetPublicIP - gets public ip
  457. func GetPublicIP() (string, error) {
  458. endpoint := ""
  459. var err error
  460. iplist := []string{"https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  461. publicIpService := os.Getenv("PUBLIC_IP_SERVICE")
  462. if publicIpService != "" {
  463. // prepend the user-specified service so it's checked first
  464. iplist = append([]string{publicIpService}, iplist...)
  465. } else if config.Config.Server.PublicIPService != "" {
  466. publicIpService = config.Config.Server.PublicIPService
  467. // prepend the user-specified service so it's checked first
  468. iplist = append([]string{publicIpService}, iplist...)
  469. }
  470. for _, ipserver := range iplist {
  471. client := &http.Client{
  472. Timeout: time.Second * 10,
  473. }
  474. resp, err := client.Get(ipserver)
  475. if err != nil {
  476. continue
  477. }
  478. defer resp.Body.Close()
  479. if resp.StatusCode == http.StatusOK {
  480. bodyBytes, err := io.ReadAll(resp.Body)
  481. if err != nil {
  482. continue
  483. }
  484. endpoint = string(bodyBytes)
  485. break
  486. }
  487. }
  488. if endpoint == "" {
  489. err = errors.New("public address not found")
  490. }
  491. return endpoint, err
  492. }
  493. // GetPlatform - get the system type of server
  494. func GetPlatform() string {
  495. platform := "linux"
  496. if os.Getenv("PLATFORM") != "" {
  497. platform = os.Getenv("PLATFORM")
  498. } else if config.Config.Server.Platform != "" {
  499. platform = config.Config.Server.Platform
  500. }
  501. return platform
  502. }
  503. // GetSQLConn - get the sql connection string
  504. func GetSQLConn() string {
  505. sqlconn := "http://"
  506. if os.Getenv("SQL_CONN") != "" {
  507. sqlconn = os.Getenv("SQL_CONN")
  508. } else if config.Config.Server.SQLConn != "" {
  509. sqlconn = config.Config.Server.SQLConn
  510. }
  511. return sqlconn
  512. }
  513. // GetNodeID - gets the node id
  514. func GetNodeID() string {
  515. var id string
  516. var err error
  517. // id = getMacAddr()
  518. if os.Getenv("NODE_ID") != "" {
  519. id = os.Getenv("NODE_ID")
  520. } else if config.Config.Server.NodeID != "" {
  521. id = config.Config.Server.NodeID
  522. } else {
  523. id, err = os.Hostname()
  524. if err != nil {
  525. return ""
  526. }
  527. }
  528. return id
  529. }
  530. func SetNodeID(id string) {
  531. config.Config.Server.NodeID = id
  532. }
  533. // GetAuthProviderInfo = gets the oauth provider info
  534. func GetAuthProviderInfo() (pi []string) {
  535. var authProvider = ""
  536. defer func() {
  537. if authProvider == "oidc" {
  538. if os.Getenv("OIDC_ISSUER") != "" {
  539. pi = append(pi, os.Getenv("OIDC_ISSUER"))
  540. } else if config.Config.Server.OIDCIssuer != "" {
  541. pi = append(pi, config.Config.Server.OIDCIssuer)
  542. } else {
  543. pi = []string{"", "", ""}
  544. }
  545. }
  546. }()
  547. if os.Getenv("AUTH_PROVIDER") != "" && os.Getenv("CLIENT_ID") != "" && os.Getenv("CLIENT_SECRET") != "" {
  548. authProvider = strings.ToLower(os.Getenv("AUTH_PROVIDER"))
  549. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" || authProvider == "oidc" {
  550. return []string{authProvider, os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")}
  551. } else {
  552. authProvider = ""
  553. }
  554. } else if config.Config.Server.AuthProvider != "" && config.Config.Server.ClientID != "" && config.Config.Server.ClientSecret != "" {
  555. authProvider = strings.ToLower(config.Config.Server.AuthProvider)
  556. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" || authProvider == "oidc" {
  557. return []string{authProvider, config.Config.Server.ClientID, config.Config.Server.ClientSecret}
  558. }
  559. }
  560. return []string{"", "", ""}
  561. }
  562. // GetAzureTenant - retrieve the azure tenant ID from env variable or config file
  563. func GetAzureTenant() string {
  564. var azureTenant = ""
  565. if os.Getenv("AZURE_TENANT") != "" {
  566. azureTenant = os.Getenv("AZURE_TENANT")
  567. } else if config.Config.Server.AzureTenant != "" {
  568. azureTenant = config.Config.Server.AzureTenant
  569. }
  570. return azureTenant
  571. }
  572. // GetMqPassword - fetches the MQ password
  573. func GetMqPassword() string {
  574. password := ""
  575. if os.Getenv("MQ_PASSWORD") != "" {
  576. password = os.Getenv("MQ_PASSWORD")
  577. } else if config.Config.Server.MQPassword != "" {
  578. password = config.Config.Server.MQPassword
  579. }
  580. return password
  581. }
  582. // GetMqUserName - fetches the MQ username
  583. func GetMqUserName() string {
  584. password := ""
  585. if os.Getenv("MQ_USERNAME") != "" {
  586. password = os.Getenv("MQ_USERNAME")
  587. } else if config.Config.Server.MQUserName != "" {
  588. password = config.Config.Server.MQUserName
  589. }
  590. return password
  591. }
  592. // GetMetricInterval - get the publish metric interval
  593. func GetMetricInterval() string {
  594. //default 15 minutes
  595. mi := "15"
  596. if os.Getenv("PUBLISH_METRIC_INTERVAL") != "" {
  597. mi = os.Getenv("PUBLISH_METRIC_INTERVAL")
  598. }
  599. return mi
  600. }
  601. // GetManageDNS - if manage DNS enabled or not
  602. func GetManageDNS() bool {
  603. enabled := false
  604. if os.Getenv("MANAGE_DNS") != "" {
  605. enabled = os.Getenv("MANAGE_DNS") == "true"
  606. }
  607. return enabled
  608. }
  609. // GetDefaultDomain - get the default domain
  610. func GetDefaultDomain() string {
  611. //default netmaker.hosted
  612. domain := "netmaker.hosted"
  613. if os.Getenv("DEFAULT_DOMAIN") != "" {
  614. if validateDomain(os.Getenv("DEFAULT_DOMAIN")) {
  615. domain = os.Getenv("DEFAULT_DOMAIN")
  616. } else {
  617. slog.Warn("invalid value, set to default domain: netmaker.hosted", "warn", os.Getenv("DEFAULT_DOMAIN"))
  618. }
  619. }
  620. return domain
  621. }
  622. func validateDomain(domain string) bool {
  623. domainPattern := `[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}(\.[a-zA-Z0-9][a-zA-Z0-9_-]{0,62})*(\.[a-zA-Z][a-zA-Z0-9]{0,10}){1}`
  624. exp := regexp.MustCompile("^" + domainPattern + "$")
  625. return exp.MatchString(domain)
  626. }
  627. // GetBatchPeerUpdate - if batch peer update
  628. func GetBatchPeerUpdate() bool {
  629. enabled := true
  630. if os.Getenv("PEER_UPDATE_BATCH") != "" {
  631. enabled = os.Getenv("PEER_UPDATE_BATCH") == "true"
  632. }
  633. return enabled
  634. }
  635. // GetPeerUpdateBatchSize - get the batch size for peer update
  636. func GetPeerUpdateBatchSize() int {
  637. //default 50
  638. batchSize := 50
  639. if os.Getenv("PEER_UPDATE_BATCH_SIZE") != "" {
  640. b, e := strconv.Atoi(os.Getenv("PEER_UPDATE_BATCH_SIZE"))
  641. if e == nil && b > 0 && b < 1000 {
  642. batchSize = b
  643. }
  644. }
  645. return batchSize
  646. }
  647. // GetEmqxRestEndpoint - returns the REST API Endpoint of EMQX
  648. func GetEmqxRestEndpoint() string {
  649. return os.Getenv("EMQX_REST_ENDPOINT")
  650. }
  651. // IsBasicAuthEnabled - checks if basic auth has been configured to be turned off
  652. func IsBasicAuthEnabled() bool {
  653. var enabled = true //default
  654. if os.Getenv("BASIC_AUTH") != "" {
  655. enabled = os.Getenv("BASIC_AUTH") == "yes"
  656. } else if config.Config.Server.BasicAuth != "" {
  657. enabled = config.Config.Server.BasicAuth == "yes"
  658. }
  659. return enabled
  660. }
  661. // GetLicenseKey - retrieves pro license value from env or conf files
  662. func GetLicenseKey() string {
  663. licenseKeyValue := os.Getenv("LICENSE_KEY")
  664. if licenseKeyValue == "" {
  665. licenseKeyValue = config.Config.Server.LicenseValue
  666. }
  667. return licenseKeyValue
  668. }
  669. // GetNetmakerTenantID - get's the associated, Netmaker, tenant ID to verify ownership
  670. func GetNetmakerTenantID() string {
  671. netmakerTenantID := os.Getenv("NETMAKER_TENANT_ID")
  672. if netmakerTenantID == "" {
  673. netmakerTenantID = config.Config.Server.NetmakerTenantID
  674. }
  675. return netmakerTenantID
  676. }
  677. // GetUserLimit - fetches free tier limits on users
  678. func GetUserLimit() int {
  679. var userslimit int
  680. if os.Getenv("USERS_LIMIT") != "" {
  681. userslimit, _ = strconv.Atoi(os.Getenv("USERS_LIMIT"))
  682. } else {
  683. userslimit = config.Config.Server.UsersLimit
  684. }
  685. return userslimit
  686. }
  687. // GetNetworkLimit - fetches free tier limits on networks
  688. func GetNetworkLimit() int {
  689. var networkslimit int
  690. if os.Getenv("NETWORKS_LIMIT") != "" {
  691. networkslimit, _ = strconv.Atoi(os.Getenv("NETWORKS_LIMIT"))
  692. } else {
  693. networkslimit = config.Config.Server.NetworksLimit
  694. }
  695. return networkslimit
  696. }
  697. // GetMachinesLimit - fetches free tier limits on machines (clients + hosts)
  698. func GetMachinesLimit() int {
  699. if l, err := strconv.Atoi(os.Getenv("MACHINES_LIMIT")); err == nil {
  700. return l
  701. }
  702. return config.Config.Server.MachinesLimit
  703. }
  704. // GetIngressLimit - fetches free tier limits on ingresses
  705. func GetIngressLimit() int {
  706. if l, err := strconv.Atoi(os.Getenv("INGRESSES_LIMIT")); err == nil {
  707. return l
  708. }
  709. return config.Config.Server.IngressesLimit
  710. }
  711. // GetEgressLimit - fetches free tier limits on egresses
  712. func GetEgressLimit() int {
  713. if l, err := strconv.Atoi(os.Getenv("EGRESSES_LIMIT")); err == nil {
  714. return l
  715. }
  716. return config.Config.Server.EgressesLimit
  717. }
  718. // DeployedByOperator - returns true if the instance is deployed by netmaker operator
  719. func DeployedByOperator() bool {
  720. if os.Getenv("DEPLOYED_BY_OPERATOR") != "" {
  721. return os.Getenv("DEPLOYED_BY_OPERATOR") == "true"
  722. }
  723. return config.Config.Server.DeployedByOperator
  724. }
  725. // IsEndpointDetectionEnabled - returns true if endpoint detection enabled
  726. func IsEndpointDetectionEnabled() bool {
  727. var enabled = true //default
  728. if os.Getenv("ENDPOINT_DETECTION") != "" {
  729. enabled = os.Getenv("ENDPOINT_DETECTION") == "true"
  730. }
  731. return enabled
  732. }
  733. // GetEnvironment returns the environment the server is running in (e.g. dev, staging, prod...)
  734. func GetEnvironment() string {
  735. if env := os.Getenv("ENVIRONMENT"); env != "" {
  736. return env
  737. }
  738. if env := config.Config.Server.Environment; env != "" {
  739. return env
  740. }
  741. return ""
  742. }
  743. // GetEmqxDeployType - fetches emqx deploy type this server uses
  744. func GetEmqxDeployType() (deployType Emqxdeploy) {
  745. deployType = EmqxOnPremDeploy
  746. if os.Getenv("EMQX_DEPLOY_TYPE") == string(EmqxCloudDeploy) {
  747. deployType = EmqxCloudDeploy
  748. }
  749. return
  750. }
  751. // GetEmqxAppID - gets the emqx cloud app id
  752. func GetEmqxAppID() string {
  753. return os.Getenv("EMQX_APP_ID")
  754. }
  755. // GetEmqxAppSecret - gets the emqx cloud app secret
  756. func GetEmqxAppSecret() string {
  757. return os.Getenv("EMQX_APP_SECRET")
  758. }
  759. // GetAllowedEmailDomains - gets the allowed email domains for oauth signup
  760. func GetAllowedEmailDomains() string {
  761. allowedDomains := "*"
  762. if os.Getenv("ALLOWED_EMAIL_DOMAINS") != "" {
  763. allowedDomains = os.Getenv("ALLOWED_EMAIL_DOMAINS")
  764. } else if config.Config.Server.AllowedEmailDomains != "" {
  765. allowedDomains = config.Config.Server.AllowedEmailDomains
  766. }
  767. return allowedDomains
  768. }
  769. // GetNmBaseDomain - fetches nm base domain
  770. func GetNmBaseDomain() string {
  771. return os.Getenv("NM_DOMAIN")
  772. }