costmodelenv.go 15 KB

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