costmodelenv.go 17 KB

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