costmodelenv.go 16 KB

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