github.com/kubewharf/katalyst-core@v0.5.3/pkg/controller/resource-recommend/datasource/prometheus/prometheus_query.go (about) 1 /* 2 Copyright 2022 The Katalyst Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package prometheus 18 19 import ( 20 "fmt" 21 22 datasourcetypes "github.com/kubewharf/katalyst-core/pkg/util/resource-recommend/types/datasource" 23 ) 24 25 const ( 26 // ContainerCpuUsageQueryExpr is used to query container cpu usage by promql 27 ContainerCpuUsageQueryExpr = `rate(container_cpu_usage_seconds_total{container!="POD",namespace="%s",pod=~"%s",container="%s"%s}[30s])` 28 // ContainerMemUsageQueryExpr is used to query container cpu usage by promql 29 ContainerMemUsageQueryExpr = `container_memory_working_set_bytes{container!="POD",namespace="%s",pod=~"%s",container="%s"%s}` 30 ) 31 32 const ( 33 WorkloadSuffixRuleForDeployment = `[a-z0-9]+-[a-z0-9]{5}$` 34 ) 35 36 func GetContainerCpuUsageQueryExp(namespace string, workloadName string, kind string, containerName string, extraFilters string) string { 37 if len(extraFilters) != 0 { 38 extraLabels := fmt.Sprintf(",%s", extraFilters) 39 return fmt.Sprintf(ContainerCpuUsageQueryExpr, namespace, convertWorkloadNameToPods(workloadName, kind), containerName, extraLabels) 40 } 41 return fmt.Sprintf(ContainerCpuUsageQueryExpr, namespace, convertWorkloadNameToPods(workloadName, kind), containerName, extraFilters) 42 } 43 44 func GetContainerMemUsageQueryExp(namespace string, workloadName string, kind string, containerName string, extraFilters string) string { 45 if len(extraFilters) != 0 { 46 extraLabels := fmt.Sprintf(",%s", extraFilters) 47 return fmt.Sprintf(ContainerMemUsageQueryExpr, namespace, convertWorkloadNameToPods(workloadName, kind), containerName, extraLabels) 48 } 49 return fmt.Sprintf(ContainerMemUsageQueryExpr, namespace, convertWorkloadNameToPods(workloadName, kind), containerName, extraFilters) 50 } 51 52 func convertWorkloadNameToPods(workloadName string, workloadKind string) string { 53 switch workloadKind { 54 case string(datasourcetypes.WorkloadDeployment): 55 return fmt.Sprintf("^%s-%s", workloadName, WorkloadSuffixRuleForDeployment) 56 } 57 return fmt.Sprintf("^%s-%s", workloadName, `.*`) 58 } 59 60 func GetExtraFilters(extraFilters string, baseFilter string) string { 61 if extraFilters == "" { 62 return baseFilter 63 } 64 if baseFilter == "" { 65 return extraFilters 66 } 67 return extraFilters + "," + baseFilter 68 }