serverconf.go 22 KB

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