温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Kubernetes节点之间的ping监控怎么实现

发布时间:2021-11-02 16:32:07 来源:亿速云 阅读:121 作者:小新 栏目:web开发

小编给大家分享一下Kubernetes节点之间的ping监控怎么实现,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

脚本和配置

我们解决方案的主要组件是一个脚本,该脚本监视每个节点的.status.addresses值。如果某个节点的该值已更改(例如添加了新节点),则我们的脚本使用Helm  value方式将节点列表以ConfigMap的形式传递给Helm图表:

apiVersion: v1 kind: ConfigMap metadata: name: ping-exporter-config namespace: d8-system data: nodes.json: > {{ .Values.pingExporter.targets | toJson }}    .Values.pingExporter.targets类似以下:  "cluster_targets":[{"ipAddress":"192.168.191.11","name":"kube-a-3"},{"ipAddress":"192.168.191.12","name":"kube-a-2"},{"ipAddress":"192.168.191.22","name":"kube-a-1"},{"ipAddress":"192.168.191.23","name":"kube-db-1"},{"ipAddress":"192.168.191.9","name":"kube-db-2"},{"ipAddress":"51.75.130.47","name":"kube-a-4"}],"external_targets":[{"host":"8.8.8.8","name":"google-dns"},{"host":"youtube.com"}]}

下面是Python脚本:

  1. #!/usr/bin/env python3 

  2.  

  3. import subprocess 

  4. import prometheus_client 

  5. import re 

  6. import statistics 

  7. import os 

  8. import json 

  9. import glob 

  10. import better_exchook 

  11. import datetime 

  12.  

  13. better_exchook.install() 

  14.  

  15. FPING_CMDLINE = "/usr/sbin/fping -p 1000 -C 30 -B 1 -q -r 1".split(" ") 

  16. FPING_REGEX = re.compile(r"^(\S*)\s*: (.*)$", re.MULTILINE) 

  17. CONFIG_PATH = "/config/targets.json" 

  18.  

  19. registry = prometheus_client.CollectorRegistry() 

  20.  

  21. prometheus_exceptions_counter = \ 

  22. prometheus_client.Counter('kube_node_ping_exceptions', 'Total number of exceptions', [], registry=registry) 

  23.  

  24. prom_metrics_cluster = {"sent": prometheus_client.Counter('kube_node_ping_packets_sent_total', 

  25.                                               'ICMP packets sent', 

  26.                                               ['destination_node', 'destination_node_ip_address'], 

  27.                                               registry=registry), 

  28.             "received": prometheus_client.Counter('kube_node_ping_packets_received_total', 

  29.                                                   'ICMP packets received', 

  30.                                                  ['destination_node', 'destination_node_ip_address'], 

  31.                                                  registry=registry), 

  32.             "rtt": prometheus_client.Counter('kube_node_ping_rtt_milliseconds_total', 

  33.                                              'round-trip time', 

  34.                                             ['destination_node', 'destination_node_ip_address'], 

  35.                                             registry=registry), 

  36.             "min": prometheus_client.Gauge('kube_node_ping_rtt_min', 'minimum round-trip time', 

  37.                                            ['destination_node', 'destination_node_ip_address'], 

  38.                                            registry=registry), 

  39.             "max": prometheus_client.Gauge('kube_node_ping_rtt_max', 'maximum round-trip time', 

  40.                                            ['destination_node', 'destination_node_ip_address'], 

  41.                                            registry=registry), 

  42.             "mdev": prometheus_client.Gauge('kube_node_ping_rtt_mdev', 

  43.                                             'mean deviation of round-trip times', 

  44.                                             ['destination_node', 'destination_node_ip_address'], 

  45.                                             registry=registry)} 

  46.  

  47.  

  48. prom_metrics_external = {"sent": prometheus_client.Counter('external_ping_packets_sent_total', 

  49.                                               'ICMP packets sent', 

  50.                                               ['destination_name', 'destination_host'], 

  51.                                               registry=registry), 

  52.             "received": prometheus_client.Counter('external_ping_packets_received_total', 

  53.                                                   'ICMP packets received', 

  54.                                                  ['destination_name', 'destination_host'], 

  55.                                                  registry=registry), 

  56.             "rtt": prometheus_client.Counter('external_ping_rtt_milliseconds_total', 

  57.                                              'round-trip time', 

  58.                                             ['destination_name', 'destination_host'], 

  59.                                             registry=registry), 

  60.             "min": prometheus_client.Gauge('external_ping_rtt_min', 'minimum round-trip time', 

  61.                                            ['destination_name', 'destination_host'], 

  62.                                            registry=registry), 

  63.             "max": prometheus_client.Gauge('external_ping_rtt_max', 'maximum round-trip time', 

  64.                                            ['destination_name', 'destination_host'], 

  65.                                            registry=registry), 

  66.             "mdev": prometheus_client.Gauge('external_ping_rtt_mdev', 

  67.                                             'mean deviation of round-trip times', 

  68.                                             ['destination_name', 'destination_host'], 

  69.                                             registry=registry)} 

  70.  

  71. def validate_envs(): 

  72. envs = {"MY_NODE_NAME": os.getenv("MY_NODE_NAME"), "PROMETHEUS_TEXTFILE_DIR": os.getenv("PROMETHEUS_TEXTFILE_DIR"), 

  73.         "PROMETHEUS_TEXTFILE_PREFIX": os.getenv("PROMETHEUS_TEXTFILE_PREFIX")} 

  74.  

  75. for k, v in envs.items(): 

  76.     if not v: 

  77.         raise ValueError("{} environment variable is empty".format(k)) 

  78.  

  79. return envs 

  80.  

  81.  

  82. @prometheus_exceptions_counter.count_exceptions() 

  83. def compute_results(results): 

  84. computed = {} 

  85.  

  86. matches = FPING_REGEX.finditer(results) 

  87. for match in matches: 

  88.     host = match.group(1) 

  89.     ping_results = match.group(2) 

  90.     if "duplicate" in ping_results: 

  91.         continue 

  92.     splitted = ping_results.split(" ") 

  93.     if len(splitted) != 30: 

  94.         raise ValueError("ping returned wrong number of results: \"{}\"".format(splitted)) 

  95.  

  96.     positive_results = [float(x) for x in splitted if x != "-"] 

  97.     if len(positive_results) > 0: 

  98.         computed[host] = {"sent": 30, "received": len(positive_results), 

  99.                         "rtt": sum(positive_results), 

  100.                         "max": max(positive_results), "min": min(positive_results), 

  101.                         "mdev": statistics.pstdev(positive_results)} 

  102.     else: 

  103.         computed[host] = {"sent": 30, "received": len(positive_results), "rtt": 0, 

  104.                         "max": 0, "min": 0, "mdev": 0} 

  105. if not len(computed): 

  106.     raise ValueError("regex match\"{}\" found nothing in fping output \"{}\"".format(FPING_REGEX, results)) 

  107. return computed 

  108.  

  109.  

  110. @prometheus_exceptions_counter.count_exceptions() 

  111. def call_fping(ips): 

  112. cmdline = FPING_CMDLINE + ips 

  113. process = subprocess.run(cmdline, stdout=subprocess.PIPE, 

  114.                          stderr=subprocess.STDOUT, universal_newlines=True) 

  115. if process.returncode == 3: 

  116.     raise ValueError("invalid arguments: {}".format(cmdline)) 

  117. if process.returncode == 4: 

  118.     raise OSError("fping reported syscall error: {}".format(process.stderr)) 

  119.  

  120. return process.stdout 

  121.  

  122.  

  123. envs = validate_envs() 

  124.  

  125. files = glob.glob(envs["PROMETHEUS_TEXTFILE_DIR"] + "*") 

  126. for f in files: 

  127. os.remove(f) 

  128.  

  129. labeled_prom_metrics = {"cluster_targets": [], "external_targets": []} 

  130.  

  131. while True: 

  132. with open(CONFIG_PATH, "r") as f: 

  133.     config = json.loads(f.read()) 

  134.     config["external_targets"] = [] if config["external_targets"] is None else config["external_targets"] 

  135.     for target in config["external_targets"]: 

  136.         target["name"] = target["host"] if "name" not in target.keys() else target["name"] 

  137.  

  138. if labeled_prom_metrics["cluster_targets"]: 

  139.     for metric in labeled_prom_metrics["cluster_targets"]: 

  140.         if (metric["node_name"], metric["ip"]) not in [(node["name"], node["ipAddress"]) for node in config['cluster_targets']]: 

  141.             for k, v in prom_metrics_cluster.items(): 

  142.                 v.remove(metric["node_name"], metric["ip"]) 

  143.  

  144. if labeled_prom_metrics["external_targets"]: 

  145.     for metric in labeled_prom_metrics["external_targets"]: 

  146.         if (metric["target_name"], metric["host"]) not in [(target["name"], target["host"]) for target in config['external_targets']]: 

  147.             for k, v in prom_metrics_external.items(): 

  148.                 v.remove(metric["target_name"], metric["host"]) 

  149.  

  150.  

  151. labeled_prom_metrics = {"cluster_targets": [], "external_targets": []} 

  152.  

  153. for node in config["cluster_targets"]: 

  154.     metrics = {"node_name": node["name"], "ip": node["ipAddress"], "prom_metrics": {}} 

  155.  

  156.     for k, v in prom_metrics_cluster.items(): 

  157.         metrics["prom_metrics"][k] = v.labels(node["name"], node["ipAddress"]) 

  158.  

  159.     labeled_prom_metrics["cluster_targets"].append(metrics) 

  160.  

  161. for target in config["external_targets"]: 

  162.     metrics = {"target_name": target["name"], "host": target["host"], "prom_metrics": {}} 

  163.  

  164.     for k, v in prom_metrics_external.items(): 

  165.         metrics["prom_metrics"][k] = v.labels(target["name"], target["host"]) 

  166.  

  167.     labeled_prom_metrics["external_targets"].append(metrics) 

  168.  

  169. out = call_fping([prom_metric["ip"]   for prom_metric in labeled_prom_metrics["cluster_targets"]] + \ 

  170.                  [prom_metric["host"] for prom_metric in labeled_prom_metrics["external_targets"]]) 

  171. computed = compute_results(out) 

  172.  

  173. for dimension in labeled_prom_metrics["cluster_targets"]: 

  174.     result = computed[dimension["ip"]] 

  175.     dimension["prom_metrics"]["sent"].inc(computed[dimension["ip"]]["sent"]) 

  176.     dimension["prom_metrics"]["received"].inc(computed[dimension["ip"]]["received"]) 

  177.     dimension["prom_metrics"]["rtt"].inc(computed[dimension["ip"]]["rtt"]) 

  178.     dimension["prom_metrics"]["min"].set(computed[dimension["ip"]]["min"]) 

  179.     dimension["prom_metrics"]["max"].set(computed[dimension["ip"]]["max"]) 

  180.     dimension["prom_metrics"]["mdev"].set(computed[dimension["ip"]]["mdev"]) 

  181.  

  182. for dimension in labeled_prom_metrics["external_targets"]: 

  183.     result = computed[dimension["host"]] 

  184.     dimension["prom_metrics"]["sent"].inc(computed[dimension["host"]]["sent"]) 

  185.     dimension["prom_metrics"]["received"].inc(computed[dimension["host"]]["received"]) 

  186.     dimension["prom_metrics"]["rtt"].inc(computed[dimension["host"]]["rtt"]) 

  187.     dimension["prom_metrics"]["min"].set(computed[dimension["host"]]["min"]) 

  188.     dimension["prom_metrics"]["max"].set(computed[dimension["host"]]["max"]) 

  189.     dimension["prom_metrics"]["mdev"].set(computed[dimension["host"]]["mdev"]) 

  190.  

  191. prometheus_client.write_to_textfile( 

  192.    

    envs["PROMETHEUS_TEXTFILE_DIR"] + envs["PROMETHEUS_TEXTFILE_PREFIX"] + envs["MY_NODE_NAME"] + ".prom", registry)

该脚本在每个Kubernetes节点上运行,并且每秒两次发送ICMP数据包到Kubernetes集群的所有实例。收集的结果会存储在文本文件中。

该脚本会包含在Docker镜像中:

FROM python:3.6-alpine3.8 COPY rootfs / WORKDIR /app RUN pip3 install --upgrade pip && pip3 install -r requirements.txt && apk add --no-cache fping ENTRYPOINT ["python3", "/app/ping-exporter.py"]

另外,我们还创建了一个ServiceAccount和一个具有唯一权限的对应角色用于获取节点列表(这样我们就可以知道它们的IP地址):

apiVersion: v1 kind: ServiceAccount metadata: name: ping-exporter namespace: d8-system --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: d8-system:ping-exporter rules: - apiGroups: [""] resources: ["nodes"] verbs: ["list"] --- kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: d8-system:kube-ping-exporter subjects: - kind: ServiceAccount name: ping-exporter namespace: d8-system roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: d8-system:ping-exporter

最后,我们需要DaemonSet来运行在集群中的所有实例:

apiVersion: apps/v1 kind: DaemonSet metadata: name: ping-exporter namespace: d8-system spec: updateStrategy: type: RollingUpdate selector: matchLabels:   name: ping-exporter template: metadata:   labels:     name: ping-exporter spec:   terminationGracePeriodSeconds: 0   tolerations:   - operator: "Exists"   hostNetwork: true   serviceAccountName: ping-exporter   priorityClassName: cluster-low   containers:   - image: private-registry.flant.com/ping-exporter/ping-exporter:v1     name: ping-exporter     env:       - name: MY_NODE_NAME         valueFrom:           fieldRef:             fieldPath: spec.nodeName       - name: PROMETHEUS_TEXTFILE_DIR         value: /node-exporter-textfile/       - name: PROMETHEUS_TEXTFILE_PREFIX         value: ping-exporter_     volumeMounts:       - name: textfile         mountPath: /node-exporter-textfile       - name: config         mountPath: /config   volumes:     - name: textfile       hostPath:         path: /var/run/node-exporter-textfile     - name: config       configMap:         name: ping-exporter-config   imagePullSecrets:   - name: private-registry

该解决方案的最后操作细节是:

  • Python脚本执行时,其结果(即存储在主机上/var/run/node-exporter-textfile目录中的文本文件)将传递到DaemonSet类型的node-exporter。

  • node-exporter使用--collector.textfile.directory  /host/textfile参数启动,这里的/host/textfile是hostPath目录/var/run/node-exporter-textfile。(你可以点击这里了解关于node-exporter中文本文件收集器的更多信息。)

  • 最后node-exporter读取这些文件,然后Prometheus从node-exporter实例上收集所有数据。

那么结果如何?

现在该来享受期待已久的结果了。指标创建之后,我们可以使用它们,当然也可以对其进行可视化。以下可以看到它们是怎样的。

首先,有一个通用选择器可让我们在其中选择节点以检查其“源”和“目标”连接。你可以获得一个汇总表,用于在Grafana仪表板中指定的时间段内ping选定节点的结果:

Kubernetes节点之间的ping监控怎么实现

以下是包含有关选定节点的组合统计信息的图形:

Kubernetes节点之间的ping监控怎么实现

另外,我们有一个记录列表,其中每个记录都链接到在“源”节点中选择的每个特定节点的图:

Kubernetes节点之间的ping监控怎么实现

如果将记录展开,你将看到从当前节点到目标节点中已选择的所有其他节点的详细ping统计信息:

Kubernetes节点之间的ping监控怎么实现

下面是相关的图形:

Kubernetes节点之间的ping监控怎么实现

节点之间的ping出现问题的图看起来如何?

Kubernetes节点之间的ping监控怎么实现

如果你在现实生活中观察到类似情况,那就该进行故障排查了!

最后,这是我们对外部主机执行ping操作的可视化效果:

Kubernetes节点之间的ping监控怎么实现

我们可以检查所有节点的总体视图,也可以仅检查任何特定节点的图形:

Kubernetes节点之间的ping监控怎么实现

看完了这篇文章,相信你对“Kubernetes节点之间的ping监控怎么实现”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI