costmodelenv.go 18 KB

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