Debian Codegraph @

ansible_collections/community/libvirt/plugins/modules/virt_net.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_net
14 author: "Maciej Delmanowski (@drybjed)"
15 short_description: Manage libvirt network configuration
16 description:
17 - Manage I(libvirt) networks.
18 options:
19 name:
20 aliases: ['network']
21 description:
22 - Name of the network being managed. Note that network must be previously
23 defined with xml.
24 type: str
25 state:
26 choices: [ "active", "inactive", "present", "absent" ]
27 description:
28 - Specify which state you want a network to be in.
29 If 'active', network will be started.
30 If 'present', ensure that network is present but do not change its
31 state; if it is missing, you need to specify xml argument.
32 If 'inactive', network will be stopped.
33 If 'undefined' or 'absent', network will be removed from I(libvirt) configuration.
34 type: str
35 command:
36 choices: [ "define", "create", "start", "stop", "destroy",
37 "undefine", "get_xml", "list_nets", "facts",
38 "info", "status", "modify"]
39 description:
40 - In addition to state management, various non-idempotent commands are available.
41 See examples.
42 Modify was added in Ansible version 2.1.
43 type: str
44 autostart:
45 type: bool
46 description:
47 - Specify if a given network should be started automatically on system boot.
48 extends_documentation_fragment:
49 - community.libvirt.virt.options_uri
50 - community.libvirt.virt.options_xml
51 - community.libvirt.requirements
52 requirements:
53 - "python-lxml"
54 '''
55
56 EXAMPLES = '''
57 - name: Define a new network
58 community.libvirt.virt_net:
59 command: define
60 name: br_nat
61 xml: '{{ lookup("template", "network/bridge.xml.j2") }}'
62
63 - name: Start a network
64 community.libvirt.virt_net:
65 command: create
66 name: br_nat
67
68 - name: List available networks
69 community.libvirt.virt_net:
70 command: list_nets
71
72 - name: Get XML data of a specified network
73 community.libvirt.virt_net:
74 command: get_xml
75 name: br_nat
76
77 - name: Stop a network
78 community.libvirt.virt_net:
79 command: destroy
80 name: br_nat
81
82 - name: Undefine a network
83 community.libvirt.virt_net:
84 command: undefine
85 name: br_nat
86
87 # Gather facts about networks
88 # Facts will be available as 'ansible_libvirt_networks'
89 - name: Gather facts about networks
90 community.libvirt.virt_net:
91 command: facts
92
93 - name: Gather information about network managed by 'libvirt' remotely using uri
94 community.libvirt.virt_net:
95 command: info
96 uri: '{{ item }}'
97 with_items: '{{ libvirt_uris }}'
98 register: networks
99
100 - name: Ensure that a network is active (needs to be defined and built first)
101 community.libvirt.virt_net:
102 state: active
103 name: br_nat
104
105 - name: Ensure that a network is inactive
106 community.libvirt.virt_net:
107 state: inactive
108 name: br_nat
109
110 - name: Ensure that a given network will be started at boot
111 community.libvirt.virt_net:
112 autostart: true
113 name: br_nat
114
115 - name: Disable autostart for a given network
116 community.libvirt.virt_net:
117 autostart: false
118 name: br_nat
119
120 - name: Add a new host in the dhcp pool
121 community.libvirt.virt_net:
122 name: br_nat
123 command: modify
124 xml: "<host mac='FC:C2:33:00:6c:3c' name='my_vm' ip='192.168.122.30'/>"
125 '''
126
127 try:
128 import libvirt
129 except ImportError:
130 HAS_VIRT = False
131 else:
132 HAS_VIRT = True
133
134 try:
135 from lxml import etree
136 except ImportError:
137 HAS_XML = False
138 else:
139 HAS_XML = True
140
141 from ansible.module_utils.basic import AnsibleModule
142 from ansible.module_utils._text import to_native
143
144
145 VIRT_FAILED = 1
146 VIRT_SUCCESS = 0
147 VIRT_UNAVAILABLE = 2
148
149 ALL_COMMANDS = []
150 ENTRY_COMMANDS = ['create', 'status', 'start', 'stop',
151 'undefine', 'destroy', 'get_xml', 'define',
152 'modify']
153 HOST_COMMANDS = ['list_nets', 'facts', 'info']
154 ALL_COMMANDS.extend(ENTRY_COMMANDS)
155 ALL_COMMANDS.extend(HOST_COMMANDS)
156
157 ENTRY_STATE_ACTIVE_MAP = {
158 0: "inactive",
159 1: "active"
160 }
161
162 ENTRY_STATE_AUTOSTART_MAP = {
163 0: "no",
164 1: "yes"
165 }
166
167 ENTRY_STATE_PERSISTENT_MAP = {
168 0: "no",
169 1: "yes"
170 }
171
172
173 class EntryNotFound(Exception):
174 pass
175
176
177 class LibvirtConnection(object):
178
179 def __init__(self, uri, module):
180
181 self.module = module
182
183 conn = libvirt.open(uri)
184
185 if not conn:
186 raise Exception("hypervisor connection failure")
187
188 self.conn = conn
189
190 def find_entry(self, entryid):
191 if entryid == -1: # Get active entries
192 names = self.conn.listNetworks() + self.conn.listDefinedNetworks()
193 return [self.conn.networkLookupByName(n) for n in names]
194
195 try:
196 return self.conn.networkLookupByName(entryid)
197 except libvirt.libvirtError as e:
198 if e.get_error_code() == libvirt.VIR_ERR_NO_NETWORK:
199 raise EntryNotFound("network %s not found" % entryid)
200 raise
201
202 def create(self, entryid):
203 if not self.module.check_mode:
204 return self.find_entry(entryid).create()
205 else:
206 try:
207 state = self.find_entry(entryid).isActive()
208 except Exception:
209 return self.module.exit_json(changed=True)
210 if not state:
211 return self.module.exit_json(changed=True)
212
213 def modify(self, entryid, xml):
214 network = self.find_entry(entryid)
215 # identify what type of entry is given in the xml
216 new_data = etree.fromstring(xml)
217 old_data = etree.fromstring(network.XMLDesc(0))
218 if new_data.tag == 'host':
219 mac_addr = new_data.get('mac')
220 hosts = old_data.xpath('/network/ip/dhcp/host')
221 # find the one mac we're looking for
222 host = None
223 for h in hosts:
224 if h.get('mac') == mac_addr:
225 host = h
226 break
227 if host is None:
228 # add the host
229 if not self.module.check_mode:
230 if network.isActive():
231 res = network.update(libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_LAST,
232 libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST,
233 -1, xml, libvirt.VIR_NETWORK_UPDATE_AFFECT_LIVE | libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG)
234 else:
235 res = network.update(libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_LAST,
236 libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST,
237 -1, xml, libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG)
238 else:
239 # pretend there was a change
240 res = 0
241 if res == 0:
242 return True
243 else:
244 # change the host
245 if host.get('name') == new_data.get('name') and host.get('ip') == new_data.get('ip'):
246 return False
247 else:
248 if not self.module.check_mode:
249 if network.isActive():
250 res = network.update(libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY,
251 libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST,
252 -1, xml, libvirt.VIR_NETWORK_UPDATE_AFFECT_LIVE | libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG)
253 else:
254 res = network.update(libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY,
255 libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST,
256 -1, xml, libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG)
257 else:
258 # pretend there was a change
259 res = 0
260 if res == 0:
261 return True
262 # command, section, parentIndex, xml, flags=0
263 self.module.fail_json(msg='updating this is not supported yet %s' % to_native(xml))
264
265 def destroy(self, entryid):
266 if not self.module.check_mode:
267 return self.find_entry(entryid).destroy()
268 else:
269 if self.find_entry(entryid).isActive():
270 return self.module.exit_json(changed=True)
271
272 def undefine(self, entryid):
273 entry = None
274 try:
275 entry = self.find_entry(entryid)
276 found = True
277 except EntryNotFound:
278 found = False
279
280 if found:
281 return self.find_entry(entryid).undefine()
282
283 if self.module.check_mode:
284 return self.module.exit_json(changed=found)
285
286 def get_status2(self, entry):
287 state = entry.isActive()
288 return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
289
290 def get_status(self, entryid):
291 if not self.module.check_mode:
292 state = self.find_entry(entryid).isActive()
293 return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
294 else:
295 try:
296 state = self.find_entry(entryid).isActive()
297 return ENTRY_STATE_ACTIVE_MAP.get(state, "unknown")
298 except Exception:
299 return ENTRY_STATE_ACTIVE_MAP.get("inactive", "unknown")
300
301 def get_uuid(self, entryid):
302 return self.find_entry(entryid).UUIDString()
303
304 def get_xml(self, entryid):
305 return self.find_entry(entryid).XMLDesc(0)
306
307 def get_forward(self, entryid):
308 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
309 try:
310 result = xml.xpath('/network/forward')[0].get('mode')
311 except Exception:
312 raise ValueError('Forward mode not specified')
313 return result
314
315 def get_domain(self, entryid):
316 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
317 try:
318 result = xml.xpath('/network/domain')[0].get('name')
319 except Exception:
320 raise ValueError('Domain not specified')
321 return result
322
323 def get_macaddress(self, entryid):
324 xml = etree.fromstring(self.find_entry(entryid).XMLDesc(0))
325 try:
326 result = xml.xpath('/network/mac')[0].get('address')
327 except Exception:
328 raise ValueError('MAC address not specified')
329 return result
330
331 def get_autostart(self, entryid):
332 state = self.find_entry(entryid).autostart()
333 return ENTRY_STATE_AUTOSTART_MAP.get(state, "unknown")
334
335 def get_autostart2(self, entryid):
336 if not self.module.check_mode:
337 return self.find_entry(entryid).autostart()
338 else:
339 try:
340 return self.find_entry(entryid).autostart()
341 except Exception:
342 return self.module.exit_json(changed=True)
343
344 def set_autostart(self, entryid, val):
345 if not self.module.check_mode:
346 return self.find_entry(entryid).setAutostart(val)
347 else:
348 try:
349 state = self.find_entry(entryid).autostart()
350 except Exception:
351 return self.module.exit_json(changed=True)
352 if bool(state) != val:
353 return self.module.exit_json(changed=True)
354
355 def get_bridge(self, entryid):
356 return self.find_entry(entryid).bridgeName()
357
358 def get_persistent(self, entryid):
359 state = self.find_entry(entryid).isPersistent()
360 return ENTRY_STATE_PERSISTENT_MAP.get(state, "unknown")
361
362 def get_dhcp_leases(self, entryid):
363 network = self.find_entry(entryid)
364 return network.DHCPLeases()
365
366 def define_from_xml(self, entryid, xml):
367 if not self.module.check_mode:
368 return self.conn.networkDefineXML(xml)
369 else:
370 try:
371 self.find_entry(entryid)
372 except Exception:
373 return self.module.exit_json(changed=True)
374
375
376 class VirtNetwork(object):
377
378 def __init__(self, uri, module):
379 self.module = module
380 self.uri = uri
381 self.conn = LibvirtConnection(self.uri, self.module)
382
383 def get_net(self, entryid):
384 return self.conn.find_entry(entryid)
385
386 def list_nets(self, state=None):
387 results = []
388 for entry in self.conn.find_entry(-1):
389 if state:
390 if state == self.conn.get_status2(entry):
391 results.append(entry.name())
392 else:
393 results.append(entry.name())
394 return results
395
396 def state(self):
397 results = []
398 for entry in self.list_nets():
399 state_blurb = self.conn.get_status(entry)
400 results.append("%s %s" % (entry, state_blurb))
401 return results
402
403 def autostart(self, entryid):
404 return self.conn.set_autostart(entryid, True)
405
406 def get_autostart(self, entryid):
407 return self.conn.get_autostart2(entryid)
408
409 def set_autostart(self, entryid, state):
410 return self.conn.set_autostart(entryid, state)
411
412 def create(self, entryid):
413 if self.conn.get_status(entryid) == "active":
414 return
415 try:
416 return self.conn.create(entryid)
417 except libvirt.libvirtError as e:
418 if e.get_error_code() == libvirt.VIR_ERR_NETWORK_EXIST:
419 return None
420 raise
421
422 def modify(self, entryid, xml):
423 return self.conn.modify(entryid, xml)
424
425 def start(self, entryid):
426 return self.create(entryid)
427
428 def stop(self, entryid):
429 if self.conn.get_status(entryid) == "active":
430 return self.conn.destroy(entryid)
431
432 def destroy(self, entryid):
433 return self.stop(entryid)
434
435 def undefine(self, entryid):
436 return self.conn.undefine(entryid)
437
438 def status(self, entryid):
439 return self.conn.get_status(entryid)
440
441 def get_xml(self, entryid):
442 return self.conn.get_xml(entryid)
443
444 def define(self, entryid, xml):
445 return self.conn.define_from_xml(entryid, xml)
446
447 def info(self):
448 return self.facts(facts_mode='info')
449
450 def facts(self, name=None, facts_mode='facts'):
451 results = dict()
452 if name:
453 entries = [name]
454 else:
455 entries = self.list_nets()
456 for entry in entries:
457 results[entry] = dict()
458 results[entry]["autostart"] = self.conn.get_autostart(entry)
459 results[entry]["persistent"] = self.conn.get_persistent(entry)
460 results[entry]["state"] = self.conn.get_status(entry)
461 results[entry]["bridge"] = self.conn.get_bridge(entry)
462 results[entry]["uuid"] = self.conn.get_uuid(entry)
463 try:
464 results[entry]["dhcp_leases"] = self.conn.get_dhcp_leases(entry)
465 # not supported on RHEL 6
466 except AttributeError:
467 pass
468
469 try:
470 results[entry]["forward_mode"] = self.conn.get_forward(entry)
471 except ValueError:
472 pass
473
474 try:
475 results[entry]["domain"] = self.conn.get_domain(entry)
476 except ValueError:
477 pass
478
479 try:
480 results[entry]["macaddress"] = self.conn.get_macaddress(entry)
481 except ValueError:
482 pass
483
484 facts = dict()
485 if facts_mode == 'facts':
486 facts["ansible_facts"] = dict()
487 facts["ansible_facts"]["ansible_libvirt_networks"] = results
488 elif facts_mode == 'info':
489 facts['networks'] = results
490 return facts
491
492
493 def core(module):
494
495 state = module.params.get('state', None)
496 name = module.params.get('name', None)
497 command = module.params.get('command', None)
498 uri = module.params.get('uri', None)
499 xml = module.params.get('xml', None)
500 autostart = module.params.get('autostart', None)
501
502 v = VirtNetwork(uri, module)
503 res = {}
504
505 if state and command == 'list_nets':
506 res = v.list_nets(state=state)
507 if not isinstance(res, dict):
508 res = {command: res}
509 return VIRT_SUCCESS, res
510
511 if state:
512 if not name:
513 module.fail_json(msg="state change requires a specified name")
514
515 res['changed'] = False
516 if state in ['active']:
517 if v.status(name) != 'active':
518 res['changed'] = True
519 res['msg'] = v.start(name)
520 elif state in ['present']:
521 try:
522 v.get_net(name)
523 except EntryNotFound:
524 if not xml:
525 module.fail_json(msg="network '" + name + "' not present, but xml not specified")
526 v.define(name, xml)
527 res = {'changed': True, 'created': name}
528 elif state in ['inactive']:
529 entries = v.list_nets()
530 if name in entries:
531 if v.status(name) != 'inactive':
532 res['changed'] = True
533 res['msg'] = v.destroy(name)
534 elif state in ['undefined', 'absent']:
535 entries = v.list_nets()
536 if name in entries:
537 if v.status(name) != 'inactive':
538 v.destroy(name)
539 res['changed'] = True
540 res['msg'] = v.undefine(name)
541 else:
542 module.fail_json(msg="unexpected state")
543
544 return VIRT_SUCCESS, res
545
546 if command:
547 if command in ENTRY_COMMANDS:
548 if not name:
549 module.fail_json(msg="%s requires 1 argument: name" % command)
550 if command in ('define', 'modify'):
551 if not xml:
552 module.fail_json(msg=command + " requires xml argument")
553 try:
554 v.get_net(name)
555 except EntryNotFound:
556 v.define(name, xml)
557 res = {'changed': True, 'created': name}
558 else:
559 if command == 'modify':
560 mod = v.modify(name, xml)
561 res = {'changed': mod, 'modified': name}
562 return VIRT_SUCCESS, res
563 res = getattr(v, command)(name)
564 if not isinstance(res, dict):
565 res = {command: res}
566 return VIRT_SUCCESS, res
567
568 elif hasattr(v, command):
569 if command == 'facts' and name:
570 res = v.facts(name)
571 else:
572 res = getattr(v, command)()
573 if not isinstance(res, dict):
574 res = {command: res}
575 return VIRT_SUCCESS, res
576
577 else:
578 module.fail_json(msg="Command %s not recognized" % command)
579
580 if autostart is not None:
581 if not name:
582 module.fail_json(msg="state change requires a specified name")
583
584 res['changed'] = False
585 if autostart:
586 if not v.get_autostart(name):
587 res['changed'] = True
588 res['msg'] = v.set_autostart(name, True)
589 else:
590 if v.get_autostart(name):
591 res['changed'] = True
592 res['msg'] = v.set_autostart(name, False)
593
594 return VIRT_SUCCESS, res
595
596 module.fail_json(msg="expected state or command parameter to be specified")
597
598
599 def main():
600
601 module = AnsibleModule(
602 argument_spec=dict(
603 name=dict(aliases=['network']),
604 state=dict(choices=['active', 'inactive', 'present', 'absent']),
605 command=dict(choices=ALL_COMMANDS),
606 uri=dict(default='qemu:///system'),
607 xml=dict(),
608 autostart=dict(type='bool')
609 ),
610 supports_check_mode=True,
611 required_if=[
612 ('command', 'create', ['name']),
613 ('command', 'status', ['name']),
614 ('command', 'start', ['name']),
615 ('command', 'stop', ['name']),
616 ('command', 'undefine', ['name']),
617 ('command', 'destroy', ['name']),
618 ('command', 'get_xml', ['name']),
619 ('command', 'define', ['name']),
620 ('command', 'modify', ['name']),
621 ]
622 )
623
624 if not HAS_VIRT:
625 module.fail_json(
626 msg='The `libvirt` module is not importable. Check the requirements.'
627 )
628
629 if not HAS_XML:
630 module.fail_json(
631 msg='The `lxml` module is not importable. Check the requirements.'
632 )
633
634 rc = VIRT_SUCCESS
635 try:
636 rc, result = core(module)
637 except Exception as e:
638 module.fail_json(msg=str(e))
639
640 if rc != 0: # something went wrong emit the msg
641 module.fail_json(rc=rc, msg=result)
642 else:
643 module.exit_json(**result)
644
645
646 if __name__ == '__main__':
647 main()