costmodelenv.go 16 KB

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