namespaces.go 1.9 KB
Newer Older
H
hongming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*

 Copyright 2019 The KubeSphere Authors.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

*/
J
jeff 已提交
18 19 20 21 22 23 24 25
package metrics

import (
	"net/url"
	"strings"

	"k8s.io/api/core/v1"

H
huanggze 已提交
26
	prom "kubesphere.io/kubesphere/pkg/simple/client/prometheus"
J
jeff 已提交
27 28 29 30 31 32 33 34 35 36
)

func GetNamespacesWithMetrics(namespaces []*v1.Namespace) []*v1.Namespace {
	var nsNameList []string
	for i := range namespaces {
		nsNameList = append(nsNameList, namespaces[i].Name)
	}
	nsFilter := "^(" + strings.Join(nsNameList, "|") + ")$"
	var timeRelateParams = make(url.Values)

H
huanggze 已提交
37 38 39 40 41
	params := prom.MonitoringRequestParams{
		ResourcesFilter: nsFilter,
		Params:          timeRelateParams,
		QueryType:       prom.DefaultQueryType,
		MetricsFilter:   "namespace_cpu_usage|namespace_memory_usage_wo_cache|namespace_pod_count",
J
jeff 已提交
42 43 44 45 46 47 48 49
	}

	rawMetrics := MonitorAllMetrics(&params, MetricLevelNamespace)

	for _, result := range rawMetrics.Results {
		for _, data := range result.Data.Result {
			metricDescMap, ok := data["metric"].(map[string]interface{})
			if ok {
H
hongming 已提交
50
				if ns, exist := metricDescMap["resource_name"]; exist {
J
jeff 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
					timeAndValue, ok := data["value"].([]interface{})
					if ok && len(timeAndValue) == 2 {
						for i := 0; i < len(namespaces); i++ {
							if namespaces[i].Name == ns {
								if namespaces[i].Annotations == nil {
									namespaces[i].Annotations = make(map[string]string, 0)
								}
								namespaces[i].Annotations[result.MetricName] = timeAndValue[1].(string)
							}
						}
					}
				}
			}
		}
	}

	return namespaces
}