Debian Codegraph @

ansible_collections/community/libvirt/plugins/modules/virt_pool.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2015, Maciej Delmanowski <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: virt_pool
14 author: "Maciej Delmanowski (@drybjed)"
15 short_description: Manage libvirt storage pools
16 description:
17 - Manage I(libvirt) storage pools.
18 options:
19 name:
20 aliases: [ "pool" ]
21 description:
22 - Name of the storage pool being managed. Note that pool must be previously
23 defined with xml.
24 type: str
25 state:
26 choices: [ "active", "inactive", "present", "absent", "undefined", "deleted" ]
27 description:
28 - Specify which state you want a storage pool to be in.
29 If 'active', pool will be started.
30 If 'present', ensure that pool is present but do not change its
31 state; if it is missing, you need to specify xml argument.
32 If 'inactive', pool will be stopped.
33 If 'undefined' or 'absent', pool will be removed from I(libvirt) configuration.
34 If 'deleted', pool contents will be deleted and then pool undefined.
35 type: str
36 command:
37 choices: [ "define", "build", "create", "start", "stop", "destroy",
38 "delete", "undefine", "get_xml", "list_pools", "facts",
39 "info", "status", "refresh" ]
40 description:
41 - In addition to state management, various non-idempotent commands are available.
42 See examples.
43 type: str
44 autostart:
45 type: bool
46 description:
47 - Specify if a given storage pool should be started automatically on system boot.
48 mode:
49 choices: [ 'new', 'repair', 'resize', 'no_overwrite', 'overwrite', 'normal', 'zeroed' ]
50 description:
51 - Pass additional parameters to 'build' or 'delete' commands.
52 type: str
53 extends_documentation_fragment:
54 - community.libvirt.virt.options_uri
55 - community.libvirt.virt.options_xml
56 - community.libvirt.requirements
57 requirements:
58 - "python-lxml"
59 '''
60
61 EXAMPLES = '''
62 - name: Define a new storage pool
63 community.libvirt.virt_pool:
64 command: define
65 name: vms
66 xml: '{{ lookup("template", "pool/dir.xml.j2") }}'
67
68 - name: Build a storage pool if it does not exist
69 community.libvirt.virt_pool:
70 command: build
71 name: vms
72
73 - name: Start a storage pool
74 community.libvirt.virt_pool:
75 command: create
76 name: vms
77
78 - name: List available pools
79 community.libvirt.virt_pool:
80 command: list_pools
81
82 - name: Get XML data of a specified pool
83 community.libvirt.virt_pool:
84 command: get_xml
85 name: vms
86
87 - name: Stop a storage pool
88 community.libvirt.virt_pool:
89 command: destroy
90 name: vms
91
92 - name: Delete a storage pool (destroys contents)
93 community.libvirt.virt_pool:
94 command: delete
95 name: vms
96
97 - name: Undefine a storage pool
98 community.libvirt.virt_pool:
99 command: undefine
100 name: vms
101
102 # Gather facts about storage pools
103 # Facts will be available as 'ansible_libvirt_pools'
104 - name: Gather facts about storage pools
105 community.libvirt.virt_pool:
106 command: facts
107
108 - name: Gather information about pools managed by 'libvirt' remotely using uri
109 community.libvirt.virt_pool:
110 command: info
111 uri: '{{ item }}'
112 with_items: '{{ libvirt_uris }}'
113 register: storage_pools
114
115 - name: Ensure that a pool is active (needs to be defined and built first)
116 community.libvirt.virt_pool:
117 state: active
118 name: vms
119
120 - name: Ensure that a pool is inactive
121 community.libvirt.virt_pool:
122 state: inactive
123 name: vms
124
125 - name: Ensure that a given pool will be started at boot
126 community.libvirt.virt_pool:
127 autostart: true
128 name: vms
129
130 - name: Disable autostart for a given pool
131 community.libvirt.virt_pool:
132 autostart: false
133 name: vms
134 '''
135
136 try:
137 import libvirt
138 except ImportError:
139 HAS_VIRT = False
140 else:
141 HAS_VIRT = True
142
143 try:
144 from lxml import etree
145 except ImportError:
146 HAS_XML = False
147 else:
148 HAS_XML = True
149
150 from ansible.module_utils.basic import AnsibleModule
151
152
153 VIRT_FAILED = 1
154 VIRT_SUCCESS = 0
155 VIRT_UNAVAILABLE = 2
156
157 ALL_COMMANDS = []
158 ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', 'build', 'delete',
159 'undefine', 'destroy', 'get_xml', 'define', 'refresh']
160 HOST_COMMANDS = ['list_pools', 'facts', 'info']
161 ALL_COMMANDS.extend(ENTRY_COMMANDS)
162 ALL_COMMANDS.extend(HOST_COMMANDS)
163
164 ENTRY_STATE_ACTIVE_MAP = {
165 0: "inactive",
166 1: "active"
167 }
168
169 ENTRY_STATE_AUTOSTART_MAP = {
170 0: "no",
171 1: "yes"
172 }
173
174 ENTRY_STATE_PERSISTENT_MAP = {
175 0: "no",
176 1: "yes"
177 }
178
179 ENTRY_STATE_INFO_MAP = {
180 0: "inactive",
181 1: "building",
182 2: "running",
183 3: "degraded",
184 4: "inaccessible"
185 }
186
187 ENTRY_BUILD_FLAGS_MAP = {
188 "new": 0,
189 "repair": 1,
190 "resize": 2,
191 "no_overwrite": 4,
192 "overwrite": 8
193 }
194
195 ENTRY_DELETE_FLAGS_MAP = {
196 "normal": 0,
197 "zeroed": 1
198 }
199
200 ALL_MODES = []
201 ALL_MODES.extend(ENTRY_BUILD_FLAGS_MAP.keys())
202 ALL_MODES.extend(ENTRY_DELETE_FLAGS_MAP.keys())
203
204
205 class EntryNotFound(Exception):
206 pass
207
208
209 class LibvirtConnection(object):
210
211 def __init__(self, uri, module):
212
213 self.module = module
214
215 conn = libvirt.open(uri)
216
217 if not conn:
218 raise Exception("hypervisor connection failure")
219
220 self.conn = conn
221
222 def find_entry(self, entryid):
223 # entryid = -1 returns a list of everything
224
225 # Get all entries
226 results = self.conn.listAllStoragePools()
227
228 if entryid == -1:
229 return results
230
231 for entry in results:
232 if entry.name() == entryid:
233 return entry
234
235 raise EntryNotFound("storage pool %s not found" % entryid)
236
237 def create(self, entryid):
238 if not self.module.check_mode:
239 return self.find_entry(entryid).create()
240 else:
241 try:
242 state = self.find_entry(entryid).isActive()
243 except Exception:
244 return self.module.exit_json(changed=True)
245 if not state:
246 return self.module.exit_json(changed=True)
247
248 def destroy(self, entryid):
249 if not self.module.check_mode:
250 return self.find_entry(entryid).destroy()
251 else:
252 if self.find_entry(entryid).isActive():
253 return self.module.exit_json(changed=True)
254
255 def undefine(self, entryid):
256 if not self.module.check_mode:
257 return self.find_entry(entryid).undefine()
258 else:
259 if not self.find_entry(entryid):
260 return self.module.exit_json(changed=True)
261
262 def get_status2(self, entry):
263 state = entry.isActive()
264 return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
265
266 def get_status(self, entryid):
267 if not self.module.check_mode:
268 state = self.find_entry(entryid).isActive()
269 return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
270 else:
271 try:
272 state = self.find_entry(entryid).isActive()
273 return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
274 except Exception:
275 return ENTRY_STATE_ACTIVE_MAP.get("inactive", "unknown")
276
277 def get_uuid(self, entryid):
278 return self.find_entry(entryid).UUIDString()
279
280 def get_xml(self, entryid):
281 return self.find_entry(entryid).XMLDesc(0)
282
283 def get_info(self, entryid):
284 return self.find_entry(entryid).info()
285
286 def get_volume_count(self, entryid):
287 return self.find_entry(entryid).numOfVolumes()
288
289 def get_volume_names(self, entryid):
290 return self.find_entry(entryid).listAllVolumes()
291
292 def get_devices(self, entryid):
293 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
294 if xml.xpath('/pool/source/device'):
295 result = []
296 for device in xml.xpath('/pool/source/device'):
297 result.append(device.get('path'))
298 try:
299 return result
300 except Exception:
301 raise ValueError('No devices specified')
302
303 def get_format(self, entryid):
304 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
305 try:
306 result = xml.xpath('/pool/source/format')[0].get('type')
307 except Exception:
308 raise ValueError('Format not specified')
309 return result
310
311 def get_host(self, entryid):
312 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
313 try:
314 result = xml.xpath('/pool/source/host')[0].get('name')
315 except Exception:
316 raise ValueError('Host not specified')
317 return result
318
319 def get_source_path(self, entryid):
320 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
321 try:
322 result = xml.xpath('/pool/source/dir')[0].get('path')
323 except Exception:
324 raise ValueError('Source path not specified')
325 return result
326
327 def get_path(self, entryid):
328 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
329 try:
330 result = xml.xpath('/pool/target/path')[0].text
331 except Exception:
332 raise ValueError('Target path not specified')
333 return result
334
335 def get_type(self, entryid):
336 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
337 return xml.get('type')
338
339 def build(self, entryid, flags):
340 if not self.module.check_mode:
341 return self.find_entry(entryid).build(flags)
342 else:
343 try:
344 state = self.find_entry(entryid)
345 except Exception:
346 return self.module.exit_json(changed=True)
347 if not state:
348 return self.module.exit_json(changed=True)
349
350 def delete(self, entryid, flags):
351 if not self.module.check_mode:
352 return self.find_entry(entryid).delete(flags)
353 else:
354 try:
355 state = self.find_entry(entryid)
356 except Exception:
357 return self.module.exit_json(changed=True)
358 if state:
359 return self.module.exit_json(changed=True)
360
361 def get_autostart(self, entryid):
362 state = self.find_entry(entryid).autostart()
363 return ENTRY_STATE_AUTOSTART_MAP.get(state, "unknown")
364
365 def get_autostart2(self, entryid):
366 if not self.module.check_mode:
367 return self.find_entry(entryid).autostart()
368 else:
369 try:
370 return self.find_entry(entryid).autostart()
371 except Exception:
372 return self.module.exit_json(changed=True)
373
374 def set_autostart(self, entryid, val):
375 if not self.module.check_mode:
376 return self.find_entry(entryid).setAutostart(val)
377 else:
378 try:
379 state = self.find_entry(entryid).autostart()
380 except Exception:
381 return self.module.exit_json(changed=True)
382 if bool(state) != val:
383 return self.module.exit_json(changed=True)
384
385 def refresh(self, entryid):
386 return self.find_entry(entryid).refresh()
387
388 def get_persistent(self, entryid):
389 state = self.find_entry(entryid).isPersistent()
390 return ENTRY_STATE_PERSISTENT_MAP.get(state, "unknown")
391
392 def define_from_xml(self, entryid, xml):
393 if not self.module.check_mode:
394 return self.conn.storagePoolDefineXML(xml)
395 else:
396 try:
397 self.find_entry(entryid)
398 except Exception:
399 return self.module.exit_json(changed=True)
400
401
402 class VirtStoragePool(object):
403
404 def __init__(self, uri, module):
405 self.module = module
406 self.uri = uri
407 self.conn = LibvirtConnection(self.uri, self.module)
408
409 def get_pool(self, entryid):
410 return self.conn.find_entry(entryid)
411
412 def list_pools(self, state=None):
413 results = []
414 for entry in self.conn.find_entry(-1):
415 if state:
416 if state == self.conn.get_status2(entry):
417 results.append(entry.name())
418 else:
419 results.append(entry.name())
420 return results
421
422 def state(self):
423 results = []
424 for entry in self.list_pools():
425 state_blurb = self.conn.get_status(entry)
426 results.append("%s %s" % (entry, state_blurb))
427 return results
428
429 def autostart(self, entryid):
430 return self.conn.set_autostart(entryid, True)
431
432 def get_autostart(self, entryid):
433 return self.conn.get_autostart2(entryid)
434
435 def set_autostart(self, entryid, state):
436 return self.conn.set_autostart(entryid, state)
437
438 def create(self, entryid):
439 return self.conn.create(entryid)
440
441 def start(self, entryid):
442 return self.conn.create(entryid)
443
444 def stop(self, entryid):
445 return self.conn.destroy(entryid)
446
447 def destroy(self, entryid):
448 return self.conn.destroy(entryid)
449
450 def undefine(self, entryid):
451 return self.conn.undefine(entryid)
452
453 def status(self, entryid):
454 return self.conn.get_status(entryid)
455
456 def get_xml(self, entryid):
457 return self.conn.get_xml(entryid)
458
459 def define(self, entryid, xml):
460 return self.conn.define_from_xml(entryid, xml)
461
462 def build(self, entryid, flags):
463 return self.conn.build(entryid, ENTRY_BUILD_FLAGS_MAP.get(flags, 0))
464
465 def delete(self, entryid, flags):
466 return self.conn.delete(entryid, ENTRY_DELETE_FLAGS_MAP.get(flags, 0))
467
468 def refresh(self, entryid):
469 return self.conn.refresh(entryid)
470
471 def info(self):
472 return self.facts(facts_mode='info')
473
474 def facts(self, facts_mode='facts'):
475 results = dict()
476 for entry in self.list_pools():
477 results[entry] = dict()
478 if self.conn.find_entry(entry):
479 data = self.conn.get_info(entry)
480 # libvirt returns maxMem, memory, and cpuTime as long()'s, which
481 # xmlrpclib tries to convert to regular int's during serialization.
482 # This throws exceptions, so convert them to strings here and
483 # assume the other end of the xmlrpc connection can figure things
484 # out or doesn't care.
485 results[entry] = {
486 "status": ENTRY_STATE_INFO_MAP.get(data[0], "unknown"),
487 "size_total": str(data[1]),
488 "size_used": str(data[2]),
489 "size_available": str(data[3]),
490 }
491 results[entry]["autostart"] = self.conn.get_autostart(entry)
492 results[entry]["persistent"] = self.conn.get_persistent(entry)
493 results[entry]["state"] = self.conn.get_status(entry)
494 results[entry]["type"] = self.conn.get_type(entry)
495 results[entry]["uuid"] = self.conn.get_uuid(entry)
496 if self.conn.find_entry(entry).isActive():
497 results[entry]["volume_count"] = self.conn.get_volume_count(entry)
498 results[entry]["volumes"] = list()
499 for volume in self.conn.get_volume_names(entry):
500 results[entry]["volumes"].append(volume.name())
501 else:
502 results[entry]["volume_count"] = -1
503
504 try:
505 results[entry]["path"] = self.conn.get_path(entry)
506 except ValueError:
507 pass
508
509 try:
510 results[entry]["host"] = self.conn.get_host(entry)
511 except ValueError:
512 pass
513
514 try:
515 results[entry]["source_path"] = self.conn.get_source_path(entry)
516 except ValueError:
517 pass
518
519 try:
520 results[entry]["format"] = self.conn.get_format(entry)
521 except ValueError:
522 pass
523
524 try:
525 devices = self.conn.get_devices(entry)
526 results[entry]["devices"] = devices
527 except ValueError:
528 pass
529
530 else:
531 results[entry]["state"] = self.conn.get_status(entry)
532
533 facts = dict()
534 if facts_mode == 'facts':
535 facts["ansible_facts"] = dict()
536 facts["ansible_facts"]["ansible_libvirt_pools"] = results
537 elif facts_mode == 'info':
538 facts['pools'] = results
539 return facts
540
541
542 def core(module):
543
544 state = module.params.get('state', None)
545 name = module.params.get('name', None)
546 command = module.params.get('command', None)
547 uri = module.params.get('uri', None)
548 xml = module.params.get('xml', None)
549 autostart = module.params.get('autostart', None)
550 mode = module.params.get('mode', None)
551
552 v = VirtStoragePool(uri, module)
553 res = {}
554
555 if state and command == 'list_pools':
556 res = v.list_pools(state=state)
557 if not isinstance(res, dict):
558 res = {command: res}
559 return VIRT_SUCCESS, res
560
561 if state:
562 if not name:
563 module.fail_json(msg="state change requires a specified name")
564
565 res['changed'] = False
566 if state in ['active']:
567 if v.status(name) != 'active':
568 res['changed'] = True
569 res['msg'] = v.start(name)
570 elif state in ['present']:
571 try:
572 v.get_pool(name)
573 except EntryNotFound:
574 if not xml:
575 module.fail_json(msg="storage pool '" + name + "' not present, but xml not specified")
576 v.define(name, xml)
577 res = {'changed': True, 'created': name}
578 elif state in ['inactive']:
579 entries = v.list_pools()
580 if name in entries:
581 if v.status(name) != 'inactive':
582 res['changed'] = True
583 res['msg'] = v.destroy(name)
584 elif state in ['undefined', 'absent']:
585 entries = v.list_pools()
586 if name in entries:
587 if v.status(name) != 'inactive':
588 v.destroy(name)
589 res['changed'] = True
590 res['msg'] = v.undefine(name)
591 elif state in ['deleted']:
592 entries = v.list_pools()
593 if name in entries:
594 if v.status(name) != 'inactive':
595 v.destroy(name)
596 v.delete(name, mode)
597 res['changed'] = True
598 res['msg'] = v.undefine(name)
599 else:
600 module.fail_json(msg="unexpected state")
601
602 return VIRT_SUCCESS, res
603
604 if command:
605 if command in ENTRY_COMMANDS:
606 if not name:
607 module.fail_json(msg="%s requires 1 argument: name" % command)
608 if command == 'define':
609 if not xml:
610 module.fail_json(msg="define requires xml argument")
611 try:
612 v.get_pool(name)
613 except EntryNotFound:
614 v.define(name, xml)
615 res = {'changed': True, 'created': name}
616 return VIRT_SUCCESS, res
617 elif command == 'build':
618 res = v.build(name, mode)
619 if not isinstance(res, dict):
620 res = {'changed': True, command: res}
621 return VIRT_SUCCESS, res
622 elif command == 'delete':
623 res = v.delete(name, mode)
624 if not isinstance(res, dict):
625 res = {'changed': True, command: res}
626 return VIRT_SUCCESS, res
627 res = getattr(v, command)(name)
628 if not isinstance(res, dict):
629 res = {command: res}
630 return VIRT_SUCCESS, res
631
632 elif hasattr(v, command):
633 res = getattr(v, command)()
634 if not isinstance(res, dict):
635 res = {command: res}
636 return VIRT_SUCCESS, res
637
638 else:
639 module.fail_json(msg="Command %s not recognized" % command)
640
641 if autostart is not None:
642 if not name:
643 module.fail_json(msg="state change requires a specified name")
644
645 res['changed'] = False
646 if autostart:
647 if not v.get_autostart(name):
648 res['changed'] = True
649 res['msg'] = v.set_autostart(name, True)
650 else:
651 if v.get_autostart(name):
652 res['changed'] = True
653 res['msg'] = v.set_autostart(name, False)
654
655 return VIRT_SUCCESS, res
656
657 module.fail_json(msg="expected state or command parameter to be specified")
658
659
660 def main():
661
662 module = AnsibleModule(
663 argument_spec=dict(
664 name=dict(aliases=['pool']),
665 state=dict(choices=['active', 'inactive', 'present', 'absent', 'undefined', 'deleted']),
666 command=dict(choices=ALL_COMMANDS),
667 uri=dict(default='qemu:///system'),
668 xml=dict(),
669 autostart=dict(type='bool'),
670 mode=dict(choices=ALL_MODES),
671 ),
672 supports_check_mode=True
673 )
674
675 if not HAS_VIRT:
676 module.fail_json(
677 msg='The `libvirt` module is not importable. Check the requirements.'
678 )
679
680 if not HAS_XML:
681 module.fail_json(
682 msg='The `lxml` module is not importable. Check the requirements.'
683 )
684
685 rc = VIRT_SUCCESS
686 try:
687 rc, result = core(module)
688 except Exception as e:
689 module.fail_json(msg=str(e))
690
691 if rc != 0: # something went wrong emit the msg
692 module.fail_json(rc=rc, msg=result)
693 else:
694 module.exit_json(**result)
695
696
697 if __name__ == '__main__':
698 main()