在k8s集群内搭建Prometheus监控平台

基本架构

Prometheus由SoundCloud发布,是一套由go语言开发的开源的监控&报警&时间序列数据库的组合。

Prometheus的基本原理是通过HTTP协议周期性抓取被监控组件的状态,任意组件只要提供对应的HTTP接口就可以接入监控。不需要任何SDK或者其他的集成过程。这样做非常适合做虚拟化环境监控系统,比如VM、Docker、Kubernetes等。

在这里插入图片描述
Prometheus 主要的组件功能如下:

  • Prometheus Server:server的作用主要是定期从静态配置的targets或者服务发现(主要是DNS、consul、k8s、mesos等)的 targets 拉取数据。
  • Exporter: 主要负责向prometheus server做数据汇报。而不同的数据汇报由不同的exporters实现,比如监控主机有node-exporters,mysql有MySQL server exporter。
  • Pushgateway:Prometheus获得数据的方式除了到对应exporter去Pull,还可以由服务先Push到pushgateway,server再去pushgateway 拉取。
  • Alertmanager:实现prometheus的告警功能。
  • webui:主要通过grafana来实现webui展示。

我们在实际使用的时候的基本流程就是:
各个服务push监控数据到其对应的指标(比如下面提到的Exporter) --> Prometheus Server定时采集数据并存储 --> 配置Grafana展示数据 & 配置告警规则进行告警

Helm部署Prometheus平台

使用helm部署kube-prometheus-stack
helm地址:传送门
github地址:传送门

请添加图片描述

Exporter

要采集目标的监控数据,首先就要在被采集目标地方安装采集组件,这种采集组件被称为Exporter。prometheus.io官网上有很多这种exporter,官方exporter列表。

采集完了怎么传输到Prometheus?

Exporter 会暴露一个HTTP接口,prometheus通过Pull模式的方式来拉取数据,会通过HTTP协议周期性抓取被监控的组件数据。
不过prometheus也提供了一种方式来支持Push模式,你可以将数据推送到Push Gateway,prometheus通过pull的方式从Push Gateway获取数据。

golang应用中接入采集组件

kratos框架

在微服务框架kratos中接入Prometheus采集组件的示例,kratos官方教程:

package mainimport ("context""fmt""log"prom "github.com/go-kratos/kratos/contrib/metrics/prometheus/v2""github.com/go-kratos/kratos/v2/middleware/metrics""github.com/prometheus/client_golang/prometheus/promhttp""github.com/go-kratos/examples/helloworld/helloworld""github.com/go-kratos/kratos/v2""github.com/go-kratos/kratos/v2/transport/grpc""github.com/go-kratos/kratos/v2/transport/http""github.com/prometheus/client_golang/prometheus"
)// go build -ldflags "-X main.Version=x.y.z"
var (// Name is the name of the compiled software.Name = "metrics"// Version is the version of the compiled software.// Version = "v1.0.0"_metricSeconds = prometheus.NewHistogramVec(prometheus.HistogramOpts{Namespace: "server",Subsystem: "requests",Name:      "duration_sec",Help:      "server requests duration(sec).",Buckets:   []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.250, 0.5, 1},}, []string{"kind", "operation"})_metricRequests = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "client",Subsystem: "requests",Name:      "code_total",Help:      "The total number of processed requests",}, []string{"kind", "operation", "code", "reason"})
)// server is used to implement helloworld.GreeterServer.
type server struct {helloworld.UnimplementedGreeterServer
}// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) {return &helloworld.HelloReply{Message: fmt.Sprintf("Hello %+v", in.Name)}, nil
}func init() {prometheus.MustRegister(_metricSeconds, _metricRequests)
}func main() {grpcSrv := grpc.NewServer(grpc.Address(":9000"),grpc.Middleware(metrics.Server(metrics.WithSeconds(prom.NewHistogram(_metricSeconds)),metrics.WithRequests(prom.NewCounter(_metricRequests)),),),)httpSrv := http.NewServer(http.Address(":8000"),http.Middleware(metrics.Server(metrics.WithSeconds(prom.NewHistogram(_metricSeconds)),metrics.WithRequests(prom.NewCounter(_metricRequests)),),),)httpSrv.Handle("/metrics", promhttp.Handler())s := &server{}helloworld.RegisterGreeterServer(grpcSrv, s)helloworld.RegisterGreeterHTTPServer(httpSrv, s)app := kratos.New(kratos.Name(Name),kratos.Server(httpSrv,grpcSrv,),)if err := app.Run(); err != nil {log.Fatal(err)}
}

最终暴露出一个http://127.0.0.1:8000/metricsHTTP接口出来,Prometheus可以通过这个接口拉取监控数据。

抓取集群外部数据源

背景:在已有的K8s集群中通过helm部署了一个kube-prometheus-stack,用于监控服务器和服务。现在已经将k8s集群中的node、pod等组件接入到prometheus了。还需要将部署在k8s集群外部的其他应用服务接入到prometheus。

prometheus抓取k8s集群外部的数据时,有以下途径:

  • ServiceMonitor
  • Additional Scrape Configuration

ServiceMonitor

ServiceMonitor 是一个CRD,它定义了 Prometheus 应该抓取的服务端点以及抓取的时间间隔。
通过ServiceMonitor监控集群外部的服务,需要配置Service、Endpoints和ServiceMonitor。

现在有一个已经部署到192.168.1.100:8000的后端服务,已经通过/metrics将监控指标暴露出来了。尝试将其接入到prometheus,具体操作如下:

在命令行中输入

$ touch external-application.yaml$ vim external-application.yaml

然后将下面的yaml文件内容拷贝进去

---
apiVersion: v1
kind: Service
metadata:name: external-application-exporternamespace: monitoringlabels:app: external-application-exporterapp.kubernetes.io/name: application-exporter
spec:type: ClusterIPports:- name: metricsport: 9101protocol: TCPtargetPort: 9101
---
apiVersion: v1
kind: Endpoints
metadata:name: external-application-exporternamespace: monitoringlabels:app: external-application-exporterapp.kubernetes.io/name: application-exporter
subsets:
- addresses:- ip: 192.168.1.100  # 这里是外部的资源列表ports:- name: metricsport: 8000
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:name: external-application-exporternamespace: monitoringlabels:app: external-application-exporterrelease: prometheus
spec:selector:matchLabels:            # Service选择器app: external-application-exporternamespaceSelector:        # Namespace选择器matchNames:- monitoringendpoints:- port: metrics           # 采集节点端口(svc定义)interval: 10s           # 采集频率根据实际需求配置,prometheus默认10spath: /metrics          # 默认地址/metrics

保存好文件之后运行命令:

kubectl apply -f external-application.yaml

之后打开prometheus控制台,进入Targets目录。可以看到新增的external-application-exporter显示出来了:

请添加图片描述
请添加图片描述

Additional Scrape Configuration

除了ip加端口提供的HTTP服务以外,我还在其他服务器上部署了可以通过域名访问的HTTPS服务。现在想用同样的方法将其接入进来。

首先尝试修改Endpoints,找到k8s的官方文档,发现Endpoints仅支持ip,也没有配置HTTPS协议的地方。
请添加图片描述
那么我们尝试换一种方式。

第一种方法

首先查阅官方文档,找到关于关于prometheus抓取配置的地方,可以看到,prometheus的抓取配置的关键字是scrape_config
请添加图片描述
我们的prometheus是通过helm部署kube-prometheus-stack得到的,所以我们查看一下该charts的value.yaml文件,看看有无配置。

输入命令:

$ cat values.yaml  | grep -C 20  scrape_config

得到如下结果:
请添加图片描述
从注释中知道,kube-prometheus是通过additionalScrapeConfigs配置抓取策略的。

于是写一个配置文件去更新helm已经部署好的prometheus的release。

$ touch prometheus.yml$ vim prometheus.yml

将一下内容写入:

prometheus:prometheusSpec:additionalScrapeConfigs:- job_name: external-application-exporter-httpsscrape_interval: 10sscrape_timeout: 10smetrics_path: /metricsscheme: httpstls_config:insecure_skip_verify: truestatic_configs:- targets: ["www.baidu.com:443"]

最后更新release:

$ helm upgrade -nmonitoring -f prometheus.yaml prometheus kube-prometheus-stack-40.0.0.tgz

使用prometheus.yaml更新release,其中kube-prometheus-stack-40.0.0.tgz是我在部署prometheus时已经helm pull到本地的chart文件。

我们在prometheus的控制台的Targets目录下可以看到我们新添加的数据源。

到这里其实就可以结束了,但是有一个不好的地方是,每次添加新的域名监控,都需要重新更新helm的release,不是特别方便。

第二种方法

翻一翻prometheus-operator的源码,发现在说明中,有关于抓取配置热更新的教程。简单的概括就是,通过配置secret,来控制prometheus的抓取数据源。secret的内容修改时,可以热更新prometheus的抓取配置。截个图看一下:

请添加图片描述

第一步,生成prometheus-additional.yaml文件

$ touch prometheus-additional.yaml$ vim prometheus-additional.yaml

prometheus-additional.yaml内容:

- job_name: external-application-exporter-httpsscrape_interval: 10sscrape_timeout: 10smetrics_path: /metricsscheme: httpstls_config:insecure_skip_verify: truestatic_configs:- targets: ["www.baidu.com:443"]

第二步,生成secret

生成用于创建secret的配置文件:

$ kubectl create secret generic additional-scrape-configs --from-file=prometheus-additional.yaml --dry-run=client -oyaml > additional-scrape-configs.yaml$ cat additional-scrape-configs.yaml

可以看到生成的additional-scrape-configs.yaml内容如下:

apiVersion: v1
data:prometheus-additional.yaml: LSBqb2JfbmFtZTogZXh0ZXJuYWwtYXBwbGljYXRpb24tZXhwb3J0ZXItaHR0cHMKICBzY3JhcGVfaW50ZXJ2YWw6IDEwcwogIHNjcmFwZV90aW1lb3V0OiAxMHMKICBtZXRyaWNzX3BhdGg6IC9tZXRyaWNzCiAgc2NoZW1lOiBodHRwcwogIHRsc19jb25maWc6CiAgICBpbnNlY3VyZV9za2lwX3ZlcmlmeTogdHJ1ZQogIHN0YXRpY19jb25maWdzOgogICAgLSB0YXJnZXRzOiBbImNpYW10ZXN0LnNtb2EuY2M6NDQzIl0K
kind: Secret
metadata:creationTimestamp: nullname: additional-scrape-configs

将这段编码解码看一下内容:

$ echo "LSBqb2JfbmFtZTogZXh0ZXJuYWwtYXBwbGljYXRpb24tZXhwb3J0ZXItaHR0cHMKICBzY3JhcGVfaW50ZXJ2YWw6IDEwcwogIHNjcmFwZV90aW1lb3V0OiAxMHMKICBtZXRyaWNzX3BhdGg6IC9tZXRyaWNzCiAgc2NoZW1lOiBodHRwcwogIHRsc19jb25maWc6CiAgICBpbnNlY3VyZV9za2lwX3ZlcmlmeTogdHJ1ZQogIHN0YXRpY19jb25maWdzOgogICAgLSB0YXJnZXRzOiBbImNpYW10ZXN0LnNtb2EuY2M6NDQzIl0K" | base64 -d

得到:

- job_name: external-application-exporter-httpsscrape_interval: 10sscrape_timeout: 10smetrics_path: /metricsscheme: httpstls_config:insecure_skip_verify: truestatic_configs:- targets: ["ciamtest.smoa.cc:443"]

可以确认配置文件生成无误,接着生成secret:

$ kubectl apply -f additional-scrape-configs.yaml -n monitoring

monitoring是prometheus部署所在的命名空间,把它们放到同一个命名空间。

确认secret生成了:

$ kubectl get secret -n monitoring

输出:
请添加图片描述

最后,修改CRD

Finally, reference this additional configuration in your prometheus.yaml CRD.

官方文档让我们修改prometheus的配置
先找到prometheus这个CRD:

$ kubectl get prometheus -n monitoring
NAME                                    VERSION   REPLICAS   AGE
prometheus-kube-prometheus-prometheus   v2.38.0   1          2d18h

然后修改它

$ kubectl edit prometheus prometheus-kube-prometheus-prometheus -n monitoring
apiVersion: monitoring.coreos.com/v1
kind: Prometheus
metadata:name: prometheuslabels:prometheus: prometheus
spec:...additionalScrapeConfigs:name: additional-scrape-configskey: prometheus-additional.yaml...

最后,在prometheus控制台看一下效果:
请添加图片描述
域名服务已经监控上了,以后想添加其他域名监控,只需要修改secret就行,great!!!

遇到的问题

  1. 更新抓取配置的secret后prometheus的控制台看不到效果
    尝试重启pod:prometheus-prometheus-kube-prometheus-prometheus-0,报错:

ts=2023-07-29T09:30:54.188Z caller=main.go:454 level=error msg=“Error loading config (–config.file=/etc/prometheus/config_out/prometheus.env.yaml)” file=/etc/prometheus/config_out/prometheus.env.yaml err=“parsing YAML file /etc/prometheus/config_out/prometheus.env.yaml: scrape timeout greater than scrape interval for scrape config with job name “external-application-exporter-https””

原因是,自定义指标的配置出错导致prometheus启动失败,scrape_interval和scrape_timeout存在问题

- job_name: external-application-exporter-httpsscrape_interval: 10sscrape_timeout: 30smetrics_path: /metricsscheme: httpstls_config:insecure_skip_verify: truestatic_configs:- targets: ["ciamtest.smoa.cc:443"]

需要改成

- job_name: external-application-exporter-httpsscrape_interval: 10sscrape_timeout: 10smetrics_path: /metricsscheme: httpstls_config:insecure_skip_verify: truestatic_configs:- targets: ["ciamtest.smoa.cc:443"]

引用

  1. Grafana & prometheus 入门
  2. Prometheus监控+Grafana+Alertmanager告警安装使用 (图文详解)
  3. Prometheus官方教程
  4. Helm仓库
  5. kube-prometheus项目的Github地址
  6. kratos官方教程
  7. K8s官方文档
  8. prometheus-operator的源码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/16696.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

大数据_Hadoop_Parquet数据格式详解

之前有面试官问到了parquet的数据格式,下面对这种格式做一个详细的解读。 参考链接 : 列存储格式Parquet浅析 - 简书 Parquet 文件结构与优势_parquet文件_KK架构的博客-CSDN博客 Parquet文件格式解析_parquet.block.size_davidfantasy的博客-CSDN博…

Redis学习路线(6)—— Redis的分布式锁

一、分布式锁的模型 (一)悲观锁: 认为线程安全问题一定会发生,因此在操作数据之前先获取锁,确保线程串行执行。例如Synchronized、Lock都属于悲观锁。 优点: 简单粗暴缺点: 性能略低 &#x…

Qt 4. 发布exe

把ex2.exe放在H盘Ex2文件夹下,执行 H:\Ex2>windeployqt ex2.exe H:\Ex2>windeployqt ex2.exe H:\Ex2\ex2.exe 64 bit, release executable Adding Qt5Svg for qsvgicon.dll Skipping plugin qtvirtualkeyboardplugin.dll due to disabled dependencies (Qt5…

go 查询采购单设备事项[小示例]V2-两种模式{严格,包含模式}

第一版: https://mp.csdn.net/mp_blog/creation/editor/131979385 第二版: 优化内容: 检索数据的两种方式: 1.严格模式--找寻名称是一模一样的内容,在上一个版本实现了 2.包含模式,也就是我输入检索关…

舌体分割的初步展示应用——依托Streamlit搭建demo

1 前言 去年在社区发布了有关中医舌象诊断的博文,其中舌象识别板块受到了极高的关注和关注。😊最近,我接触到了Python的Streamlit库,它可以帮助数据相关从业人员轻松搭建数据看板。本文将介绍如何使用Streamlit构建舌体分割的演示…

算法与数据结构-二分查找

文章目录 什么是二分查找二分查找的时间复杂度二分查找的代码实现简单实现:不重复有序数组查找目标值变体实现:查找第一个值等于给定值的元素变体实现:查找最后一个值等于给定值的元素变体实现:查找最后一个小于给定值的元素变体实…

大龄青年的浙大MBA读书梦——提面优秀190+的上岸经验分享

时间如白驹过隙,三十年的岁月也转瞬即逝,回首过往这三十年的人生路,没有大起大落,一直都是相对比较平稳。但这几年疫情原因,公司效益不好,不仅我们公司整个行业也都在裁员,为了让自己更具备竞争…

flask数据库操作

本文将详细介绍在Flask Web应用中如何设计数据库模型,并使用Flask-SQLAlchemy等扩展进行数据库操作的最佳实践。内容涵盖数据模型设计,ORM使用,关系映射,查询方法,事务处理等方面。通过本文,您可以掌握Flask数据库应用的基本知识。 Flask作为一个流行的Python Web框架,提供了高…

什么是架构 架构图

如何画架构图_个人渣记录仅为自己搜索用的博客-CSDN博客 什么是架构?要表达的到底是什么? Linus 03 年在聊到拆分和集成时有一个很好的描述: I claim that you want to start communicating between independent modules no sooner than you…

CAN转ETHERCAT网关将CAN 总线和 ETHERCAT 网络连接方法

由于好多现场会出现将CAN总线的设备接到EtherCAT网络中,由于协议的不相同,不能直接进行连接,现需一种能同时兼容CAN 总线和ETHERCAT网络的一种设备,由此捷米JM-ECT-CAN 是自主研发的一款 ETHERCAT 从站功能的通讯网关。该产品主要…

Selenium开发环境搭建

1.下载Python https://www.python.org/downloads/ 下载下来选择自己创建的路径进行安装,然后配置环境变量 cmd命令框查看 2.安装selenium cmd命令框输入: pip install selenium3.下载pycharm https://www.jetbrains.com/pycharm/download/#sec…

Helm KinD kubectl krew Istio急速安装

本篇更新网上许多安装失效的工具,如krew和KinD。 本篇测试使用时间为2023/7/20,基本都为最新版本或最新稳定版本。 前置 Helm 是 Kubernetes 的一个包管理工具,用于简化 Kubernetes 应用的部署和管理。Helm 使用名为 "chart" 的打…

搭建测试平台开发(一):Django基本配置与项目创建

一、安装Django最新版本 1 pip install django 二、创建Django项目 首先进入要存放项目的目录,再执行创建项目的命令 1 django-admin startproject testplatform 三、Django项目目录详解 1 testplatform 2 ├── testplatform  # 项目的容器 3 │ ├──…

getInputStream has already been called for this request 问题记录

问题背景 HttpServletRequest.getReader() HttpServletRequest.getInputStream() 不能在过滤器中读取一次二进制流(字符流),又在另外一个Servlet中读取一次,即一个InputSteam(BufferedReader)对象在被读取完成后,将无…

JAVA的回调机制、同步/异步调用

一、同步调用 同步调用是最基本的调用方式。类A的a()方法调用类B的b()方法,类A的方法需要等到B类的方法执行完成才会继续执行。如果B的方法长时间阻塞,就会导致A类方法无法正常执行下去。 二、异步调用 如果A调用B,B的执行时间比较长&#…

Linux系统下U盘打不开: No application is registered as handling this file

简述 系统是之前就安装好使用的Ubuntu14.04,不过由于某些原因只安装到了机械硬盘中;最近新买了一块固态硬盘,所以打算把Ubuntu系统迁移到新的固态硬盘上; 当成功的迁移了系统之后发现其引导有点问题,导致多个系统启动不…

区间预测 | MATLAB实现QRBiGRU双向门控循环单元分位数回归多输入单输出区间预测

区间预测 | MATLAB实现QRBiGRU双向门控循环单元分位数回归多输入单输出区间预测 目录 区间预测 | MATLAB实现QRBiGRU双向门控循环单元分位数回归多输入单输出区间预测效果一览基本介绍模型描述程序设计参考资料 效果一览 基本介绍 MATLAB实现QRBiGRU双向门控循环单元分位数回归…

团队任务管理器工具推荐:三款适合协作工作的首选

如果您是项目经理或领导一个小团队,那么每天要完成的任务列表似乎无穷无尽。对于任何规模的公司来说,在不依赖任何软件的情况下掌握任务管理的不同方面都是一项挑战。满足您项目管理需求的正确软件可以显著提高团队的生产力——无论您的团队规模或项目范…

微软亚研院提出模型基础架构RetNet或将成为Transformer有力继承者

作为全新的神经网络架构,RetNet 同时实现了良好的扩展结果、并行训练、低成本部署和高效推理。这些特性将使 RetNet 有可能成为继 Transformer 之后大语言模型基础网络架构的有力继承者。实验数据也显示,在语言建模任务上: RetNet 可以达到与…

使用贝叶斯滤波器通过运动模型和嘈杂的墙壁传感器定位机器人研究(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…