Debian Codegraph @

masakarimonitors/hostmonitor/kubernetes_check/manager.py

raw
1 # Copyright(c) 2024 Samsung SDS
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from collections import deque
16
17 import eventlet
18
19 from kubernetes import client
20 from kubernetes import config
21
22 from oslo_log import log
23 from oslo_utils import timeutils
24
25 import socket
26
27 from masakarimonitors import conf
28 from masakarimonitors.ha import masakari
29 from masakarimonitors.hostmonitor import driver
30 from masakarimonitors.objects import event_constants as ec
31
32 LOG = log.getLogger(__name__)
33 CONF = conf.CONF
34
35
36 class KubernetesCheck(driver.DriverBase):
37 """Check host status by k8s"""
38
39 def __init__(self):
40 super(KubernetesCheck, self).__init__()
41 self.hostname = socket.gethostname()
42 self.monitoring_interval = CONF.host.monitoring_interval
43 self.monitoring_samples = CONF.host.monitoring_samples
44 self.notifier = masakari.SendNotification()
45 self.monitoring_data = {}
46 self.last_status = {}
47 self.running = False
48
49 config.load_incluster_config()
50 self.kube_client = client.CoreV1Api()
51
52 def update_monitoring_data(self):
53 """update monitoring data from k8s"""
54 LOG.debug("update monitoring data from k8s.")
55 node_list = self.kube_client.list_node(
56 label_selector=CONF.kubernetes.monitoring_node_labels
57 ).items
58
59 # Remove non-exist node from monitoring_data
60 self.monitoring_data = {
61 node: status for node, status in self.monitoring_data.items()
62 if node in [i.metadata.name for i in node_list]
63 }
64
65 for host in node_list:
66 hostname = host.metadata.name
67
68 for condition in host.status.conditions:
69 if condition.type != "Ready":
70 continue
71
72 host_health_history = self.monitoring_data.get(
73 hostname, deque([], maxlen=self.monitoring_samples))
74 host_health_history.appendleft(condition.status)
75 LOG.debug("hostname: %s, condition: %s",
76 hostname, host_health_history)
77
78 # Status is 'True' if node is healthy else 'False' or 'unknown'
79 # Most up-to-date state is stored in index 0
80 self.monitoring_data[hostname] = host_health_history
81
82 @staticmethod
83 def _event(host, host_health):
84 host_status = ec.EventConstants.HOST_STATUS_NORMAL
85 LOG.info("Host %s needs recovery, health status: %s." %
86 (host, host_health))
87
88 event = {
89 'notification': {
90 'type': ec.EventConstants.TYPE_COMPUTE_HOST,
91 'hostname': host,
92 'generated_time': timeutils.utcnow(),
93 'payload': {
94 'event': ec.EventConstants.EVENT_STOPPED,
95 'host_status': host_status
96 }
97 }
98 }
99
100 return event
101
102 def poll_hosts(self):
103 """poll and check hosts health"""
104 for host, health_history in self.monitoring_data.items():
105 if not self.last_status:
106 self.last_status[host] = self.monitoring_data[host][0]
107
108 if host == self.hostname:
109 continue
110
111 if len(health_history) < self.monitoring_samples:
112 continue
113
114 is_host_alive = "True" in health_history
115
116 if not is_host_alive and self.last_status.get(host):
117 event = self._event(host, is_host_alive)
118 self.notifier.send_notification(
119 CONF.host.api_retry_max,
120 CONF.host.api_retry_interval,
121 event)
122
123 self.last_status[host] = is_host_alive
124
125 def stop(self):
126 self.running = False
127
128 def monitor_hosts(self):
129 self.running = True
130 while self.running:
131 try:
132 self.update_monitoring_data()
133 LOG.info("Monitoring data: %s", self.monitoring_data)
134 self.poll_hosts()
135 except Exception as e:
136 LOG.exception("Exception when host-monitor by k8s: %s", e)
137
138 eventlet.greenthread.sleep(self.monitoring_interval)