costmodelenv.go 15 KB

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