monitoring.go 9.9 KB
Newer Older
G
Guangzhe Huang 已提交
1
/*
H
hongming 已提交
2
Copyright 2019 The KubeSphere Authors.
G
Guangzhe Huang 已提交
3

H
hongming 已提交
4 5 6
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
G
Guangzhe Huang 已提交
7

H
hongming 已提交
8
    http://www.apache.org/licenses/LICENSE-2.0
G
Guangzhe Huang 已提交
9

H
hongming 已提交
10 11 12 13 14
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.
G
Guangzhe Huang 已提交
15 16 17 18 19
*/

package monitoring

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

type MonitoringOperator interface {
H
huanggze 已提交
36 37
	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 已提交
38 39
	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 已提交
40
	GetMetadata(namespace string) Metadata
H
huanggze 已提交
41
	GetMetricLabelSet(metric, namespace string, start, end time.Time) MetricLabelSet
H
huanggze 已提交
42 43 44 45

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

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

H
huanggze 已提交
55 56 57 58 59 60 61
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 已提交
62 63
}

H
huanggze 已提交
64 65 66 67 68 69 70 71 72 73
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 已提交
74 75
}

H
huanggze 已提交
76 77 78 79 80 81 82 83 84 85
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 已提交
86 87
}

Z
zryfish 已提交
88 89 90
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 已提交
91 92
}

Z
zryfish 已提交
93 94 95
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 已提交
96
}
H
huanggze 已提交
97 98 99 100 101

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

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 已提交
116 117 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

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)},
					},
				},
			},
		})
	}

145
	wkList, err := mo.ks.Tenant().V1alpha2().WorkspaceTemplates().Lister().List(labels.Everything())
H
huanggze 已提交
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
	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))},
					},
				},
			},
		})
	}

185 186 187 188 189 190
	cond := &params.Conditions{
		Match: map[string]string{
			openpitrix.Status: openpitrix.StatusActive,
			openpitrix.RepoId: openpitrix.BuiltinRepoId,
		},
	}
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	if mo.op != nil {
		tmpl, err := mo.op.ListApps(cond, "", 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(tmpl.TotalCount)},
						},
H
huanggze 已提交
207 208
					},
				},
209 210
			})
		}
H
huanggze 已提交
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 299 300 301 302 303 304
	}

	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
}