costmodelenv.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. package env
  2. import (
  3. "regexp"
  4. "strconv"
  5. "time"
  6. "github.com/opencost/opencost/pkg/log"
  7. "github.com/opencost/opencost/pkg/util/timeutil"
  8. )
  9. const (
  10. AppVersionEnvVar = "APP_VERSION"
  11. AWSAccessKeyIDEnvVar = "AWS_ACCESS_KEY_ID"
  12. AWSAccessKeySecretEnvVar = "AWS_SECRET_ACCESS_KEY"
  13. AWSClusterIDEnvVar = "AWS_CLUSTER_ID"
  14. AWSPricingURL = "AWS_PRICING_URL"
  15. AlibabaAccessKeyIDEnvVar = "ALIBABA_ACCESS_KEY_ID"
  16. AlibabaAccessKeySecretEnvVar = "ALIBABA_SECRET_ACCESS_KEY"
  17. KubecostNamespaceEnvVar = "KUBECOST_NAMESPACE"
  18. PodNameEnvVar = "POD_NAME"
  19. ClusterIDEnvVar = "CLUSTER_ID"
  20. ClusterProfileEnvVar = "CLUSTER_PROFILE"
  21. PrometheusServerEndpointEnvVar = "PROMETHEUS_SERVER_ENDPOINT"
  22. MaxQueryConcurrencyEnvVar = "MAX_QUERY_CONCURRENCY"
  23. QueryLoggingFileEnvVar = "QUERY_LOGGING_FILE"
  24. RemoteEnabledEnvVar = "REMOTE_WRITE_ENABLED"
  25. RemotePWEnvVar = "REMOTE_WRITE_PASSWORD"
  26. SQLAddressEnvVar = "SQL_ADDRESS"
  27. UseCSVProviderEnvVar = "USE_CSV_PROVIDER"
  28. CSVRegionEnvVar = "CSV_REGION"
  29. CSVEndpointEnvVar = "CSV_ENDPOINT"
  30. CSVPathEnvVar = "CSV_PATH"
  31. ConfigPathEnvVar = "CONFIG_PATH"
  32. CloudProviderAPIKeyEnvVar = "CLOUD_PROVIDER_API_KEY"
  33. DisableAggregateCostModelCache = "DISABLE_AGGREGATE_COST_MODEL_CACHE"
  34. EmitPodAnnotationsMetricEnvVar = "EMIT_POD_ANNOTATIONS_METRIC"
  35. EmitNamespaceAnnotationsMetricEnvVar = "EMIT_NAMESPACE_ANNOTATIONS_METRIC"
  36. EmitKsmV1MetricsEnvVar = "EMIT_KSM_V1_METRICS"
  37. EmitKsmV1MetricsOnly = "EMIT_KSM_V1_METRICS_ONLY"
  38. ThanosEnabledEnvVar = "THANOS_ENABLED"
  39. ThanosQueryUrlEnvVar = "THANOS_QUERY_URL"
  40. ThanosOffsetEnvVar = "THANOS_QUERY_OFFSET"
  41. ThanosMaxSourceResEnvVar = "THANOS_MAX_SOURCE_RESOLUTION"
  42. LogCollectionEnabledEnvVar = "LOG_COLLECTION_ENABLED"
  43. ProductAnalyticsEnabledEnvVar = "PRODUCT_ANALYTICS_ENABLED"
  44. ErrorReportingEnabledEnvVar = "ERROR_REPORTING_ENABLED"
  45. ValuesReportingEnabledEnvVar = "VALUES_REPORTING_ENABLED"
  46. DBBasicAuthUsername = "DB_BASIC_AUTH_USERNAME"
  47. DBBasicAuthPassword = "DB_BASIC_AUTH_PW"
  48. DBBearerToken = "DB_BEARER_TOKEN"
  49. MultiClusterBasicAuthUsername = "MC_BASIC_AUTH_USERNAME"
  50. MultiClusterBasicAuthPassword = "MC_BASIC_AUTH_PW"
  51. MultiClusterBearerToken = "MC_BEARER_TOKEN"
  52. InsecureSkipVerify = "INSECURE_SKIP_VERIFY"
  53. KubeConfigPathEnvVar = "KUBECONFIG_PATH"
  54. UTCOffsetEnvVar = "UTC_OFFSET"
  55. CacheWarmingEnabledEnvVar = "CACHE_WARMING_ENABLED"
  56. ETLEnabledEnvVar = "ETL_ENABLED"
  57. ETLMaxPrometheusQueryDurationMinutes = "ETL_MAX_PROMETHEUS_QUERY_DURATION_MINUTES"
  58. ETLResolutionSeconds = "ETL_RESOLUTION_SECONDS"
  59. LegacyExternalAPIDisabledVar = "LEGACY_EXTERNAL_API_DISABLED"
  60. PromClusterIDLabelEnvVar = "PROM_CLUSTER_ID_LABEL"
  61. PricingConfigmapName = "PRICING_CONFIGMAP_NAME"
  62. MetricsConfigmapName = "METRICS_CONFIGMAP_NAME"
  63. KubecostJobNameEnvVar = "KUBECOST_JOB_NAME"
  64. KubecostConfigBucketEnvVar = "KUBECOST_CONFIG_BUCKET"
  65. ClusterInfoFileEnabledEnvVar = "CLUSTER_INFO_FILE_ENABLED"
  66. ClusterCacheFileEnabledEnvVar = "CLUSTER_CACHE_FILE_ENABLED"
  67. PrometheusQueryOffsetEnvVar = "PROMETHEUS_QUERY_OFFSET"
  68. PrometheusRetryOnRateLimitResponseEnvVar = "PROMETHEUS_RETRY_ON_RATE_LIMIT"
  69. PrometheusRetryOnRateLimitMaxRetriesEnvVar = "PROMETHEUS_RETRY_ON_RATE_LIMIT_MAX_RETRIES"
  70. PrometheusRetryOnRateLimitDefaultWaitEnvVar = "PROMETHEUS_RETRY_ON_RATE_LIMIT_DEFAULT_WAIT"
  71. IngestPodUIDEnvVar = "INGEST_POD_UID"
  72. ETLReadOnlyMode = "ETL_READ_ONLY"
  73. )
  74. var offsetRegex = regexp.MustCompile(`^(\+|-)(\d\d):(\d\d)$`)
  75. func IsETLReadOnlyMode() bool {
  76. return GetBool(ETLReadOnlyMode, false)
  77. }
  78. // GetKubecostConfigBucket returns a file location for a mounted bucket configuration which is used to store
  79. // a subset of kubecost configurations that require sharing via remote storage.
  80. func GetKubecostConfigBucket() string {
  81. return Get(KubecostConfigBucketEnvVar, "")
  82. }
  83. // IsClusterInfoFileEnabled returns true if the cluster info is read from a file or pulled from the local
  84. // cloud provider and kubernetes.
  85. func IsClusterInfoFileEnabled() bool {
  86. return GetBool(ClusterInfoFileEnabledEnvVar, false)
  87. }
  88. // IsClusterCacheFileEnabled returns true if the kubernetes cluster data is read from a file or pulled from the local
  89. // kubernetes API.
  90. func IsClusterCacheFileEnabled() bool {
  91. return GetBool(ClusterCacheFileEnabledEnvVar, false)
  92. }
  93. // IsPrometheusRetryOnRateLimitResponse will attempt to retry if a 429 response is received OR a 400 with a body containing
  94. // ThrottleException (common in AWS services like AMP)
  95. func IsPrometheusRetryOnRateLimitResponse() bool {
  96. return GetBool(PrometheusRetryOnRateLimitResponseEnvVar, true)
  97. }
  98. // GetPrometheusRetryOnRateLimitMaxRetries returns the maximum number of retries that should be attempted prior to failing.
  99. // Only used if IsPrometheusRetryOnRateLimitResponse() is true.
  100. func GetPrometheusRetryOnRateLimitMaxRetries() int {
  101. return GetInt(PrometheusRetryOnRateLimitMaxRetriesEnvVar, 5)
  102. }
  103. // GetPrometheusRetryOnRateLimitDefaultWait returns the default wait time for a retriable rate limit response without a
  104. // Retry-After header.
  105. func GetPrometheusRetryOnRateLimitDefaultWait() time.Duration {
  106. return GetDuration(PrometheusRetryOnRateLimitDefaultWaitEnvVar, 100*time.Millisecond)
  107. }
  108. // GetPrometheusQueryOffset returns the time.Duration to offset all prometheus queries by. NOTE: This env var is applied
  109. // to all non-range queries made via our query context. This should only be applied when there is a significant delay in
  110. // data arriving in the target prom db. For example, if supplying a thanos or cortex querier for the prometheus server, using
  111. // a 3h offset will ensure that current time = current time - 3h.
  112. //
  113. // This offset is NOT the same as the GetThanosOffset() option, as that is only applied to queries made specifically targetting
  114. // thanos. This offset is applied globally.
  115. func GetPrometheusQueryOffset() time.Duration {
  116. offset := Get(PrometheusQueryOffsetEnvVar, "")
  117. if offset == "" {
  118. return 0
  119. }
  120. dur, err := timeutil.ParseDuration(offset)
  121. if err != nil {
  122. return 0
  123. }
  124. return dur
  125. }
  126. func GetPricingConfigmapName() string {
  127. return Get(PricingConfigmapName, "pricing-configs")
  128. }
  129. func GetMetricsConfigmapName() string {
  130. return Get(MetricsConfigmapName, "metrics-config")
  131. }
  132. // GetAWSAccessKeyID returns the environment variable value for AWSAccessKeyIDEnvVar which represents
  133. // the AWS access key for authentication
  134. func GetAppVersion() string {
  135. return Get(AppVersionEnvVar, "1.91.0-rc.0")
  136. }
  137. // IsEmitNamespaceAnnotationsMetric returns true if cost-model is configured to emit the kube_namespace_annotations metric
  138. // containing the namespace annotations
  139. func IsEmitNamespaceAnnotationsMetric() bool {
  140. return GetBool(EmitNamespaceAnnotationsMetricEnvVar, false)
  141. }
  142. // IsEmitPodAnnotationsMetric returns true if cost-model is configured to emit the kube_pod_annotations metric containing
  143. // pod annotations.
  144. func IsEmitPodAnnotationsMetric() bool {
  145. return GetBool(EmitPodAnnotationsMetricEnvVar, false)
  146. }
  147. // IsEmitKsmV1Metrics returns true if cost-model is configured to emit all necessary KSM v1
  148. // metrics that were removed in KSM v2
  149. func IsEmitKsmV1Metrics() bool {
  150. return GetBool(EmitKsmV1MetricsEnvVar, true)
  151. }
  152. func IsEmitKsmV1MetricsOnly() bool {
  153. return GetBool(EmitKsmV1MetricsOnly, false)
  154. }
  155. // GetAWSAccessKeyID returns the environment variable value for AWSAccessKeyIDEnvVar which represents
  156. // the AWS access key for authentication
  157. func GetAWSAccessKeyID() string {
  158. return Get(AWSAccessKeyIDEnvVar, "")
  159. }
  160. // GetAWSAccessKeySecret returns the environment variable value for AWSAccessKeySecretEnvVar which represents
  161. // the AWS access key secret for authentication
  162. func GetAWSAccessKeySecret() string {
  163. return Get(AWSAccessKeySecretEnvVar, "")
  164. }
  165. // GetAWSClusterID returns the environment variable value for AWSClusterIDEnvVar which represents
  166. // an AWS specific cluster identifier.
  167. func GetAWSClusterID() string {
  168. return Get(AWSClusterIDEnvVar, "")
  169. }
  170. // GetAWSPricingURL returns an optional alternative URL to fetch AWS pricing data from; for use in airgapped environments
  171. func GetAWSPricingURL() string {
  172. return Get(AWSPricingURL, "")
  173. }
  174. // GetAlibabaAccessKeyID returns the environment variable value for AlibabaAccessKeyIDEnvVar which represents
  175. // the Alibaba access key for authentication
  176. func GetAlibabaAccessKeyID() string {
  177. return Get(AlibabaAccessKeyIDEnvVar, "")
  178. }
  179. // GetAlibabaAccessKeySecret returns the environment variable value for AlibabaAccessKeySecretEnvVar which represents
  180. // the Alibaba access key secret for authentication
  181. func GetAlibabaAccessKeySecret() string {
  182. return Get(AlibabaAccessKeySecretEnvVar, "")
  183. }
  184. // GetKubecostNamespace returns the environment variable value for KubecostNamespaceEnvVar which
  185. // represents the namespace the cost model exists in.
  186. func GetKubecostNamespace() string {
  187. return Get(KubecostNamespaceEnvVar, "kubecost")
  188. }
  189. // GetPodName returns the name of the current running pod. If this environment variable is not set,
  190. // empty string is returned.
  191. func GetPodName() string {
  192. return Get(PodNameEnvVar, "")
  193. }
  194. // GetClusterProfile returns the environment variable value for ClusterProfileEnvVar which
  195. // represents the cluster profile configured for
  196. func GetClusterProfile() string {
  197. return Get(ClusterProfileEnvVar, "development")
  198. }
  199. // GetClusterID returns the environment variable value for ClusterIDEnvVar which represents the
  200. // configurable identifier used for multi-cluster metric emission.
  201. func GetClusterID() string {
  202. return Get(ClusterIDEnvVar, "")
  203. }
  204. // GetPrometheusServerEndpoint returns the environment variable value for PrometheusServerEndpointEnvVar which
  205. // represents the prometheus server endpoint used to execute prometheus queries.
  206. func GetPrometheusServerEndpoint() string {
  207. return Get(PrometheusServerEndpointEnvVar, "")
  208. }
  209. func GetInsecureSkipVerify() bool {
  210. return GetBool(InsecureSkipVerify, false)
  211. }
  212. // IsAggregateCostModelCacheDisabled returns the environment variable value for DisableAggregateCostModelCache which
  213. // will inform the aggregator on whether to load cached data. Defaults to false
  214. func IsAggregateCostModelCacheDisabled() bool {
  215. return GetBool(DisableAggregateCostModelCache, false)
  216. }
  217. // IsRemoteEnabled returns the environment variable value for RemoteEnabledEnvVar which represents whether
  218. // or not remote write is enabled for prometheus for use with SQL backed persistent storage.
  219. func IsRemoteEnabled() bool {
  220. return GetBool(RemoteEnabledEnvVar, false)
  221. }
  222. // GetRemotePW returns the environment variable value for RemotePWEnvVar which represents the remote
  223. // persistent storage password.
  224. func GetRemotePW() string {
  225. return Get(RemotePWEnvVar, "")
  226. }
  227. // GetSQLAddress returns the environment variable value for SQLAddressEnvVar which represents the SQL
  228. // database address used with remote persistent storage.
  229. func GetSQLAddress() string {
  230. return Get(SQLAddressEnvVar, "")
  231. }
  232. // IsUseCSVProvider returns the environment variable value for UseCSVProviderEnvVar which represents
  233. // whether or not the use of a CSV cost provider is enabled.
  234. func IsUseCSVProvider() bool {
  235. return GetBool(UseCSVProviderEnvVar, false)
  236. }
  237. // GetCSVRegion returns the environment variable value for CSVRegionEnvVar which represents the
  238. // region configured for a CSV provider.
  239. func GetCSVRegion() string {
  240. return Get(CSVRegionEnvVar, "")
  241. }
  242. // GetCSVEndpoint returns the environment variable value for CSVEndpointEnvVar which represents the
  243. // endpoint configured for a S3 CSV provider another than AWS S3.
  244. func GetCSVEndpoint() string {
  245. return Get(CSVEndpointEnvVar, "")
  246. }
  247. // GetCSVPath returns the environment variable value for CSVPathEnvVar which represents the key path
  248. // configured for a CSV provider.
  249. func GetCSVPath() string {
  250. return Get(CSVPathEnvVar, "")
  251. }
  252. // GetConfigPath returns the environment variable value for ConfigPathEnvVar which represents the cost
  253. // model configuration path
  254. func GetConfigPath() string {
  255. return Get(ConfigPathEnvVar, "")
  256. }
  257. // GetConfigPath returns the environment variable value for ConfigPathEnvVar which represents the cost
  258. // model configuration path
  259. func GetConfigPathWithDefault(defaultValue string) string {
  260. return Get(ConfigPathEnvVar, defaultValue)
  261. }
  262. // GetCloudProviderAPI returns the environment variable value for CloudProviderAPIEnvVar which represents
  263. // the API key provided for the cloud provider.
  264. func GetCloudProviderAPIKey() string {
  265. return Get(CloudProviderAPIKeyEnvVar, "")
  266. }
  267. // IsThanosEnabled returns the environment variable value for ThanosEnabledEnvVar which represents whether
  268. // or not thanos is enabled.
  269. func IsThanosEnabled() bool {
  270. return GetBool(ThanosEnabledEnvVar, false)
  271. }
  272. // GetThanosQueryUrl returns the environment variable value for ThanosQueryUrlEnvVar which represents the
  273. // target query endpoint for hitting thanos.
  274. func GetThanosQueryUrl() string {
  275. return Get(ThanosQueryUrlEnvVar, "")
  276. }
  277. // GetThanosOffset returns the environment variable value for ThanosOffsetEnvVar which represents the total
  278. // amount of time to offset all queries made to thanos.
  279. func GetThanosOffset() string {
  280. return Get(ThanosOffsetEnvVar, "3h")
  281. }
  282. // GetThanosMaxSourceResolution returns the environment variable value for ThanosMaxSourceResEnvVar which represents
  283. // the max source resolution to use when querying thanos.
  284. func GetThanosMaxSourceResolution() string {
  285. res := Get(ThanosMaxSourceResEnvVar, "raw")
  286. switch res {
  287. case "raw":
  288. return "0s"
  289. case "0s":
  290. fallthrough
  291. case "5m":
  292. fallthrough
  293. case "1h":
  294. return res
  295. default:
  296. return "0s"
  297. }
  298. }
  299. // IsLogCollectionEnabled returns the environment variable value for LogCollectionEnabledEnvVar which represents
  300. // whether or not log collection has been enabled for kubecost deployments.
  301. func IsLogCollectionEnabled() bool {
  302. return GetBool(LogCollectionEnabledEnvVar, true)
  303. }
  304. // IsProductAnalyticsEnabled returns the environment variable value for ProductAnalyticsEnabledEnvVar
  305. func IsProductAnalyticsEnabled() bool {
  306. return GetBool(ProductAnalyticsEnabledEnvVar, true)
  307. }
  308. // IsErrorReportingEnabled returns the environment variable value for ErrorReportingEnabledEnvVar
  309. func IsErrorReportingEnabled() bool {
  310. return GetBool(ErrorReportingEnabledEnvVar, true)
  311. }
  312. // IsValuesReportingEnabled returns the environment variable value for ValuesReportingEnabledEnvVar
  313. func IsValuesReportingEnabled() bool {
  314. return GetBool(ValuesReportingEnabledEnvVar, true)
  315. }
  316. // GetMaxQueryConcurrency returns the environment variable value for MaxQueryConcurrencyEnvVar
  317. func GetMaxQueryConcurrency() int {
  318. return GetInt(MaxQueryConcurrencyEnvVar, 5)
  319. }
  320. // GetQueryLoggingFile returns a file location if query logging is enabled. Otherwise, empty string
  321. func GetQueryLoggingFile() string {
  322. return Get(QueryLoggingFileEnvVar, "")
  323. }
  324. func GetDBBasicAuthUsername() string {
  325. return Get(DBBasicAuthUsername, "")
  326. }
  327. func GetDBBasicAuthUserPassword() string {
  328. return Get(DBBasicAuthPassword, "")
  329. }
  330. func GetDBBearerToken() string {
  331. return Get(DBBearerToken, "")
  332. }
  333. // GetMultiClusterBasicAuthUsername returns the environemnt variable value for MultiClusterBasicAuthUsername
  334. func GetMultiClusterBasicAuthUsername() string {
  335. return Get(MultiClusterBasicAuthUsername, "")
  336. }
  337. // GetMultiClusterBasicAuthPassword returns the environemnt variable value for MultiClusterBasicAuthPassword
  338. func GetMultiClusterBasicAuthPassword() string {
  339. return Get(MultiClusterBasicAuthPassword, "")
  340. }
  341. func GetMultiClusterBearerToken() string {
  342. return Get(MultiClusterBearerToken, "")
  343. }
  344. // GetKubeConfigPath returns the environment variable value for KubeConfigPathEnvVar
  345. func GetKubeConfigPath() string {
  346. return Get(KubeConfigPathEnvVar, "")
  347. }
  348. // GetUTCOffset returns the environemnt variable value for UTCOffset
  349. func GetUTCOffset() string {
  350. return Get(UTCOffsetEnvVar, "")
  351. }
  352. // GetParsedUTCOffset returns the duration of the configured UTC offset
  353. func GetParsedUTCOffset() time.Duration {
  354. offset := time.Duration(0)
  355. if offsetStr := GetUTCOffset(); offsetStr != "" {
  356. match := offsetRegex.FindStringSubmatch(offsetStr)
  357. if match == nil {
  358. log.Warnf("Illegal UTC offset: %s", offsetStr)
  359. return offset
  360. }
  361. sig := 1
  362. if match[1] == "-" {
  363. sig = -1
  364. }
  365. hrs64, _ := strconv.ParseInt(match[2], 10, 64)
  366. hrs := sig * int(hrs64)
  367. mins64, _ := strconv.ParseInt(match[3], 10, 64)
  368. mins := sig * int(mins64)
  369. offset = time.Duration(hrs)*time.Hour + time.Duration(mins)
  370. }
  371. return offset
  372. }
  373. // GetKubecostJobName returns the environment variable value for KubecostJobNameEnvVar
  374. func GetKubecostJobName() string {
  375. return Get(KubecostJobNameEnvVar, "kubecost")
  376. }
  377. func IsCacheWarmingEnabled() bool {
  378. return GetBool(CacheWarmingEnabledEnvVar, true)
  379. }
  380. func IsETLEnabled() bool {
  381. return GetBool(ETLEnabledEnvVar, true)
  382. }
  383. func GetETLMaxPrometheusQueryDuration() time.Duration {
  384. dayMins := 60 * 24
  385. mins := time.Duration(GetInt64(ETLMaxPrometheusQueryDurationMinutes, int64(dayMins)))
  386. return mins * time.Minute
  387. }
  388. // GetETLResolution determines the resolution of ETL queries. The smaller the
  389. // duration, the higher the resolution; the higher the resolution, the more
  390. // accurate the query results, but the more computationally expensive. This
  391. // value is always 1m for Prometheus, but is configurable for Thanos.
  392. func GetETLResolution() time.Duration {
  393. // If Thanos is not enabled, hard-code to 1m resolution
  394. if !IsThanosEnabled() {
  395. return 60 * time.Second
  396. }
  397. // Thanos is enabled, so use the configured ETL resolution, or default to
  398. // 5m (i.e. 300s)
  399. secs := time.Duration(GetInt64(ETLResolutionSeconds, 300))
  400. return secs * time.Second
  401. }
  402. func LegacyExternalCostsAPIDisabled() bool {
  403. return GetBool(LegacyExternalAPIDisabledVar, false)
  404. }
  405. // GetPromClusterLabel returns the environemnt variable value for PromClusterIDLabel
  406. func GetPromClusterLabel() string {
  407. return Get(PromClusterIDLabelEnvVar, "cluster_id")
  408. }
  409. // IsIngestingPodUID returns the env variable from ingestPodUID, which alters the
  410. // contents of podKeys in Allocation
  411. func IsIngestingPodUID() bool {
  412. return GetBool(IngestPodUIDEnvVar, false)
  413. }