2
0

costmodelenv.go 16 KB

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