monitoring.go 9.8 KB
Newer Older
G
Guangzhe Huang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*

 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.

*/

package monitoring

import (
H
huanggze 已提交
22 23 24
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/kubernetes"
H
huanggze 已提交
25
	"k8s.io/klog"
H
huanggze 已提交
26 27 28
	ksinformers "kubesphere.io/kubesphere/pkg/client/informers/externalversions"
	"kubesphere.io/kubesphere/pkg/constants"
	"kubesphere.io/kubesphere/pkg/informers"
H
huanggze 已提交
29
	"kubesphere.io/kubesphere/pkg/models/monitoring/expressions"
H
huanggze 已提交
30 31
	"kubesphere.io/kubesphere/pkg/models/openpitrix"
	"kubesphere.io/kubesphere/pkg/server/params"
G
Guangzhe Huang 已提交
32
	"kubesphere.io/kubesphere/pkg/simple/client/monitoring"
H
huanggze 已提交
33
	opclient "kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
G
Guangzhe Huang 已提交
34 35 36 37
	"time"
)

type MonitoringOperator interface {
H
huanggze 已提交
38 39
	GetMetric(expr, namespace string, time time.Time) (monitoring.Metric, error)
	GetMetricOverTime(expr, namespace string, start, end time.Time, step time.Duration) (monitoring.Metric, error)
Z
zryfish 已提交
40 41
	GetNamedMetrics(metrics []string, time time.Time, opt monitoring.QueryOption) Metrics
	GetNamedMetricsOverTime(metrics []string, start, end time.Time, step time.Duration, opt monitoring.QueryOption) Metrics
H
huanggze 已提交
42
	GetMetadata(namespace string) Metadata
H
huanggze 已提交
43
	GetMetricLabelSet(metric, namespace string, start, end time.Time) MetricLabelSet
H
huanggze 已提交
44 45 46 47

	// TODO: refactor
	GetKubeSphereStats() Metrics
	GetWorkspaceStats(workspace string) Metrics
G
Guangzhe Huang 已提交
48 49 50
}

type monitoringOperator struct {
H
huanggze 已提交
51 52 53 54
	c   monitoring.Interface
	k8s kubernetes.Interface
	ks  ksinformers.SharedInformerFactory
	op  openpitrix.Interface
G
Guangzhe Huang 已提交
55 56
}

H
huanggze 已提交
57 58 59 60 61 62 63
func NewMonitoringOperator(client monitoring.Interface, k8s kubernetes.Interface, factory informers.InformerFactory, opClient opclient.Client) MonitoringOperator {
	return &monitoringOperator{
		c:   client,
		k8s: k8s,
		ks:  factory.KubeSphereSharedInformerFactory(),
		op:  openpitrix.NewOpenpitrixOperator(factory.KubernetesSharedInformerFactory(), opClient),
	}
G
Guangzhe Huang 已提交
64 65
}

H
huanggze 已提交
66 67 68 69 70 71 72 73 74 75
func (mo monitoringOperator) GetMetric(expr, namespace string, time time.Time) (monitoring.Metric, error) {
	// Different monitoring backend implementations have different ways to enforce namespace isolation.
	// Each implementation should register itself to `ReplaceNamespaceFns` during init().
	// We hard code "prometheus" here because we only support this datasource so far.
	// In the future, maybe the value should be returned from a method like `mo.c.GetMonitoringServiceName()`.
	expr, err := expressions.ReplaceNamespaceFns["prometheus"](expr, namespace)
	if err != nil {
		return monitoring.Metric{}, err
	}
	return mo.c.GetMetric(expr, time), nil
G
Guangzhe Huang 已提交
76 77
}

H
huanggze 已提交
78 79 80 81 82 83 84 85 86 87
func (mo monitoringOperator) GetMetricOverTime(expr, namespace string, start, end time.Time, step time.Duration) (monitoring.Metric, error) {
	// Different monitoring backend implementations have different ways to enforce namespace isolation.
	// Each implementation should register itself to `ReplaceNamespaceFns` during init().
	// We hard code "prometheus" here because we only support this datasource so far.
	// In the future, maybe the value should be returned from a method like `mo.c.GetMonitoringServiceName()`.
	expr, err := expressions.ReplaceNamespaceFns["prometheus"](expr, namespace)
	if err != nil {
		return monitoring.Metric{}, err
	}
	return mo.c.GetMetricOverTime(expr, start, end, step), nil
G
Guangzhe Huang 已提交
88 89
}

Z
zryfish 已提交
90 91 92
func (mo monitoringOperator) GetNamedMetrics(metrics []string, time time.Time, opt monitoring.QueryOption) Metrics {
	ress := mo.c.GetNamedMetrics(metrics, time, opt)
	return Metrics{Results: ress}
G
Guangzhe Huang 已提交
93 94
}

Z
zryfish 已提交
95 96 97
func (mo monitoringOperator) GetNamedMetricsOverTime(metrics []string, start, end time.Time, step time.Duration, opt monitoring.QueryOption) Metrics {
	ress := mo.c.GetNamedMetricsOverTime(metrics, start, end, step, opt)
	return Metrics{Results: ress}
G
Guangzhe Huang 已提交
98
}
H
huanggze 已提交
99 100 101 102 103

func (mo monitoringOperator) GetMetadata(namespace string) Metadata {
	data := mo.c.GetMetadata(namespace)
	return Metadata{Data: data}
}
H
huanggze 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117

func (mo monitoringOperator) GetMetricLabelSet(metric, namespace string, start, end time.Time) MetricLabelSet {
	// Different monitoring backend implementations have different ways to enforce namespace isolation.
	// Each implementation should register itself to `ReplaceNamespaceFns` during init().
	// We hard code "prometheus" here because we only support this datasource so far.
	// In the future, maybe the value should be returned from a method like `mo.c.GetMonitoringServiceName()`.
	expr, err := expressions.ReplaceNamespaceFns["prometheus"](metric, namespace)
	if err != nil {
		klog.Error(err)
		return MetricLabelSet{}
	}
	data := mo.c.GetMetricLabelSet(expr, start, end)
	return MetricLabelSet{Data: data}
}
H
huanggze 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

func (mo monitoringOperator) GetKubeSphereStats() Metrics {
	var res Metrics
	now := float64(time.Now().Unix())

	clusterList, err := mo.ks.Cluster().V1alpha1().Clusters().Lister().List(labels.Everything())
	clusterTotal := len(clusterList)
	if clusterTotal == 0 {
		clusterTotal = 1
	}
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereClusterCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereClusterCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(clusterTotal)},
					},
				},
			},
		})
	}

	wkList, err := mo.ks.Tenant().V1alpha1().Workspaces().Lister().List(labels.Everything())
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereWorkspaceCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereWorkspaceCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(len(wkList))},
					},
				},
			},
		})
	}

	usrList, err := mo.ks.Iam().V1alpha2().Users().Lister().List(labels.Everything())
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereUserCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereUserCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(len(usrList))},
					},
				},
			},
		})
	}

	tmpls, err := mo.op.ListApps(&params.Conditions{}, "", false, 0, 0)
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereAppTmplCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: KubeSphereAppTmplCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(tmpls.TotalCount)},
					},
				},
			},
		})
	}

	return res
}

func (mo monitoringOperator) GetWorkspaceStats(workspace string) Metrics {
	var res Metrics
	now := float64(time.Now().Unix())

	selector := labels.SelectorFromSet(labels.Set{constants.WorkspaceLabelKey: workspace})
	opt := metav1.ListOptions{LabelSelector: selector.String()}

	nsList, err := mo.k8s.CoreV1().Namespaces().List(opt)
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceNamespaceCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceNamespaceCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(len(nsList.Items))},
					},
				},
			},
		})
	}

	devopsList, err := mo.ks.Devops().V1alpha3().DevOpsProjects().Lister().List(selector)
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceDevopsCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceDevopsCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(len(devopsList))},
					},
				},
			},
		})
	}

	memberList, err := mo.ks.Iam().V1alpha2().WorkspaceRoleBindings().Lister().List(selector)
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceMemberCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceMemberCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(len(memberList))},
					},
				},
			},
		})
	}

	roleList, err := mo.ks.Iam().V1alpha2().WorkspaceRoles().Lister().List(selector)
	if err != nil {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceRoleCount,
			Error:      err.Error(),
		})
	} else {
		res.Results = append(res.Results, monitoring.Metric{
			MetricName: WorkspaceRoleCount,
			MetricData: monitoring.MetricData{
				MetricType: monitoring.MetricTypeVector,
				MetricValues: []monitoring.MetricValue{
					{
						Sample: &monitoring.Point{now, float64(len(roleList))},
					},
				},
			},
		})
	}

	return res
}