Debian Codegraph @

ceilometer_instance_poller/instance_poller.py

raw symbols SCIP
1 #!/usr/bin/python3
2
3 # Copyright (c) 2022, Thomas Goirand <[email protected]>
4 # (c) 2022, Sylvain Didelot <[email protected]>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18
19 import configparser
20 import datetime
21 import os
22 import pathlib
23 import json
24 import random
25 import sys
26 from xml.dom import minidom
27
28 import guestfs
29 import libvirt
30
31 from oslo_config import cfg
32 from oslo_log import log as logging
33
34 LOG = logging.getLogger(__name__,project='ceilometer-intance-poller')
35
36 common_opts = [
37 cfg.StrOpt('instance_info_cache_path',
38 default='/var/cache/ceilometer-instance-poller',
39 help='Path where to store the cache of instance polled information.'),
40 cfg.IntOpt('instance_info_cache_expiration',
41 default=240,
42 help='Time in minute for the instance information cache expiration.'),
43 cfg.IntOpt('instance_info_cache_fuzzing',
44 default=120,
45 help='Time in minute to randomly add to instance_info_cache_expiration.'
46 ' The point is to not poll all instances at the same time.'),
47 ]
48
49 # Define your CLI-only options with boolean switches
50 cli_only_opts = [
51 cfg.BoolOpt('use-cache-only',
52 default=False,
53 help='Only use cache data when available.'),
54 cfg.BoolOpt('do-not-print',
55 default=False,
56 help='Do not print the output of found values. Useful to only put data in cache in a cron.'),
57 ]
58
59 def list_opts():
60 return [
61 ("DEFAULT", common_opts),
62 ]
63
64 conn = None
65
66
67 class Cache(datetime.timedelta):
68 dir = None
69
70 def __new__(cls, name, cache_path, *args, **kwargs):
71 td = super().__new__(cls, *args, **kwargs)
72 td.name = name
73 td.dir = pathlib.Path(cache_path)
74 dir = pathlib.Path(cache_path)
75 return td
76
77 def check(self):
78 now = datetime.datetime.now(datetime.timezone.utc)
79
80 try:
81 with (self.dir / self.name).open() as f:
82 cache = json.load(f)
83 if datetime.datetime.fromisoformat(cache["expire"]) < now:
84 return
85 return cache["data"]
86 except (FileNotFoundError, json.decoder.JSONDecodeError, KeyError, TypeError):
87 return
88
89 def store(self, data):
90 now = datetime.datetime.now(datetime.timezone.utc)
91 expire = now + self
92 expire = expire.isoformat()
93
94 cache = {"expire": expire, "data": data}
95 with (self.dir / self.name).open("w") as f:
96 json.dump(cache, f)
97
98
99 def _libvirt_connect():
100 try:
101 conn = libvirt.openReadOnly("qemu:///system")
102 except libvirt.libvirtError as e:
103 LOG.error("Could not connect to libvirt: %s" % repr(e))
104 exit(1)
105 return conn
106
107
108 def _list_all_domains(conn):
109
110 # domainNames = conn.listDefinedDomains()
111 # if domainNames == None:
112 # print('Failed to get a list of domain names', file=sys.stderr)
113
114 domainIDs = conn.listDomainsID()
115 if domainIDs == None:
116 LOG.error("Failed to get a list of domain IDs")
117 exit(1)
118
119 domains = []
120 try:
121 if len(domainIDs) != 0:
122 for domainID in domainIDs:
123 domains.append(conn.lookupByID(domainID))
124 except libvirt.libvirtError as e:
125 LOG.error("Could not list domains using libvirt: %s" % repr(e))
126 conn.close()
127 exit(1)
128
129 return domains
130
131
132 def _libvirt_disconnect(conn):
133 conn.close()
134
135
136 def _print_all(domains, expiration_timeout, cache_fuzzing, cache_path, use_cache_only, do_not_print):
137 if len(domains) == 0:
138 LOG.debug("Empty list of domains: no VMs?")
139 print('[]')
140 else:
141
142 if os.path.isfile('/etc/ceph/ceph.client.openstack.keyring'):
143 # Read the Ceph openstack client key, that we need
144 # further down when doing guestfs.GuestFS.add_drive()
145 cephclientconfig = configparser.ConfigParser()
146 cephclientconfig.read('/etc/ceph/ceph.client.openstack.keyring')
147 cephkey = cephclientconfig['client.openstack']['key']
148
149 if os.path.isfile('/etc/ceph/ceph.conf'):
150 # Get the list of mon hosts from ceph.conf
151 cephconfig = configparser.ConfigParser()
152 cephconfig.read('/etc/ceph/ceph.conf')
153 cephmons = cephconfig['global']['mon_host']
154 cephmonarray = [c+':6789' for c in cephmons.split(',')]
155
156 metrics = []
157 for domain in domains:
158 instance_uuid = domain.UUIDString()
159 instance_vcpus = domain.maxVcpus()
160 LOG.debug(f"Found instance {instance_uuid} ({instance_vcpus} vcpus)")
161 if use_cache_only:
162 exp = (expiration_timeout + cache_fuzzing) * 2
163 else:
164 exp = expiration_timeout + random.randrange(cache_fuzzing)
165 cache = Cache(instance_uuid, cache_path, minutes=exp)
166 metric = cache.check()
167
168 if metric is None and not use_cache_only:
169 LOG.debug(f"No cahe for instance {instance_uuid}: will fetch the data using libgestfs.")
170 g = guestfs.GuestFS(python_return_dict=True)
171
172 # The naive way is to replace what's below
173 # including all of the for disk in disks loop
174 # by a g.add_libvirt_dom(). This unfortunately
175 # cannot work with a Ceph backend, because there
176 # is no way to provide the Ceph auth credentials
177 # with this function: libguestfs simply doesn't
178 # have this feature.
179 # So instead, we parse all of the domain's XML
180 # and add each disk one by one.
181 # g.add_libvirt_dom(domain, readonly=True)
182
183 raw_xml = domain.XMLDesc()
184 xml = minidom.parseString(raw_xml)
185 disks = xml.getElementsByTagName("disk")
186
187 for disk in disks:
188
189 disk_type = disk.getAttribute('type')
190 disk_device = disk.getAttribute('device')
191 disksources = disk.getElementsByTagName('source')
192 for disksource in disksources:
193 disk_targets = disk.getElementsByTagName('target')
194 for disk_target in disk_targets:
195 disk_target_dev = disk_target.getAttribute('dev')
196 disk_name = '/dev/' + disk_target_dev
197 # This should be a Ceph-based nova-compute
198 if disk_type == 'network':
199 disksource_name = disksource.getAttribute('name')
200 # Example call with a Ceph drive bellow:
201 # g.add_drive(filename='cinder/volume-bcfaf249-f69f-4c8e-829a-47e960265bcf',
202 # readonly=True,
203 # name='/dev/sda',
204 # protocol='rbd',
205 # server=['10.0.0.21:6789', '10.0.0.22:6789', '10.0.0.23:6789'],
206 # username='openstack',
207 # secret=AQAUaHteKPhnKhAAyLFTM39AnbIGfAbqQSoUYw==,
208 # copyonread=True,
209 # )
210 # If it's not a cinder volume, then we're in Nova's case,
211 # so we use 'normal' /etc/ceph/ceph.conf and
212 # /etc/ceph/ceph.client.openstack.keyring
213 if 'cinder/' not in disksource_name:
214 g.add_drive(filename=disksource_name,
215 format="raw",
216 readonly=True,
217 name=disk_name,
218 protocol='rbd',
219 server=cephmonarray,
220 username='openstack',
221 secret=cephkey,
222 copyonread=True,
223 )
224 else:
225 # We first try our normal AZ, if the disk isn't cross-az attached
226 try:
227 g.add_drive_opts(filename=disksource_name,
228 format="raw",
229 readonly=True,
230 name=disk_name,
231 protocol='rbd',
232 server=cephmonarray,
233 username='openstack',
234 secret=cephkey,
235 copyonread=True,
236 )
237 except:
238 # If not, we try each AZ one by one. This is probably a bit stupid,
239 # but it works and it's kind of fast, so let's do that.
240 for az in ['az1', 'az2', 'az3']:
241 LOG.info(f"---> Trying az {az}")
242 az_cephclientconfig_path = '/etc/ceph/ceph-' + az + '.client.openstack.keyring'
243 az_cephconf_path = '/etc/ceph/ceph-' + az + '.conf'
244 if os.path.isfile(az_cephclientconfig_path):
245 # Read the Ceph openstack client key, that we need
246 # further down when doing guestfs.GuestFS.add_drive()
247 az_cephclientconfig = configparser.ConfigParser()
248 az_cephclientconfig.read(az_cephclientconfig_path)
249 az_cephkey = az_cephclientconfig['client.openstack']['key']
250
251 if os.path.isfile(az_cephconf_path):
252 # Get the list of mon hosts from ceph.conf
253 az_cephconfig = configparser.ConfigParser()
254 az_cephconfig.read(az_cephconf_path)
255 az_cephmons = az_cephconfig['global']['mon_host']
256 az_cephmonarray = [c+':6789' for c in az_cephmons.split(',')]
257
258 try:
259 g.add_drive_opts(filename=disksource_name,
260 format="raw",
261 readonly=True,
262 name=disk_name,
263 protocol='rbd',
264 server=az_cephmonarray,
265 username='openstack',
266 secret=az_cephkey,
267 copyonread=True,
268 )
269 LOG.info(f"---> Could mount disk in {az}")
270 break
271 except:
272 LOG.info(f"---> Failed to mount disk in {az}")
273 continue
274 # This must be a non-Ceph based nova-compute
275 elif disk_type == 'file':
276 disksource_filename = disksource.getAttribute('file')
277 g.add_drive(filename=disksource_filename,
278 format='raw',
279 readonly=True,
280 name=disk_name,
281 protocol='file',
282 copyonread=True,
283 )
284
285 g.launch()
286 # Sometimes, inspect_os fails, so we just accept this fact...
287 try:
288 roots = g.inspect_os()
289 except:
290 roots = []
291
292 # If it's empty, it means guestfs couldn't find anything,
293 # maybe because of an UFS filesystem, for example.
294 if roots == []:
295 metric = {
296 "resource_id" : domain.UUIDString(),
297 "vcpus": domain.maxVcpus(),
298 "os_family": 'unknown',
299 "os_distro": 'unknown',
300 "os_info": 'unknown',
301 "os_version_major": 0,
302 "os_version_minor": 0,
303 "os_product_name": 'unknown',
304 "os_product_variant": 'unknown',
305 }
306
307 else:
308 for root in roots:
309 metric = {
310 "resource_id" : domain.UUIDString(),
311 "vcpus": domain.maxVcpus(),
312 "os_family": g.inspect_get_type(root),
313 "os_distro": g.inspect_get_distro(root),
314 "os_info": g.inspect_get_osinfo(root),
315 "os_version_major": g.inspect_get_major_version(root),
316 "os_version_minor": g.inspect_get_minor_version(root),
317 "os_product_name": g.inspect_get_product_name(root),
318 "os_product_variant": g.inspect_get_product_variant(root),
319 }
320 g.umount_all()
321 g.close()
322 cache.store(metric)
323
324 else:
325 LOG.debug(f"Using cache for instance {instance_uuid}")
326
327 if metrics != None and metric != None:
328 metrics.append(metric)
329
330
331 if do_not_print:
332 return metrics
333 else:
334 print(json.dumps(metrics))
335 return metrics
336
337 def run_instance_poller():
338 conf = cfg.ConfigOpts()
339 conf.register_opts(common_opts)
340 conf.register_cli_opts(cli_only_opts)
341 logging.register_options(conf)
342 conf(args=sys.argv[1:], project='ceilometer-instance-poller')
343 logging.setup(conf, conf.project)
344
345
346 conn = _libvirt_connect()
347 domains = _list_all_domains(conn)
348 _print_all(domains, conf.instance_info_cache_expiration,
349 conf.instance_info_cache_fuzzing,
350 conf.instance_info_cache_path,
351 conf.use_cache_only,
352 conf.do_not_print)
353 _libvirt_disconnect(conn)
354
355 if __name__ == "__main__":
356 run_instance_poller()
357 exit(0)