serverconf.go 22 KB

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