2
0

costmodelenv.go 17 KB

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