serverconf.go 22 KB

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