1 ##############################################################################
2 # Copyright (c) 2016 Tim Rozet (trozet@redhat.com) and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
16 import pyipmi.interfaces
19 from apex.common import (
22 from apex.network import jumphost
23 from apex.common.exceptions import ApexCleanException
24 from virtualbmc import manager as vbmc_lib
27 def clean_nodes(inventory):
28 inv_dict = utils.parse_yaml(inventory)
29 if inv_dict is None or 'nodes' not in inv_dict:
30 logging.error("Inventory file is empty or missing nodes definition")
32 for node, node_info in inv_dict['nodes'].items():
33 logging.info("Cleaning node: {}".format(node))
35 interface = pyipmi.interfaces.create_interface(
36 'ipmitool', interface_type='lanplus')
37 connection = pyipmi.create_connection(interface)
38 connection.session.set_session_type_rmcp(node_info['ipmi_ip'])
39 connection.target = pyipmi.Target(0x20)
40 connection.session.set_auth_type_user(node_info['ipmi_user'],
41 node_info['ipmi_pass'])
42 connection.session.establish()
43 connection.chassis_control_power_down()
44 except Exception as e:
45 logging.error("Failure while shutting down node {}".format(e))
50 vbmc_manager = vbmc_lib.VirtualBMCManager()
51 vbmcs = vbmc_manager.list()
53 logging.info("Deleting vbmc: {}".format(vbmc['domain_name']))
54 vbmc_manager.delete(vbmc['domain_name'])
58 logging.info('Destroying all Apex VMs')
59 conn = libvirt.open('qemu:///system')
61 raise ApexCleanException('Unable to open libvirt connection')
62 pool = conn.storagePoolLookupByName('default')
63 domains = conn.listAllDomains()
65 for domain in domains:
67 if vm != 'undercloud' and not vm.startswith('baremetal'):
69 logging.info("Cleaning domain: {}".format(vm))
71 logging.debug('Destroying domain')
73 domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
74 # delete storage volume
76 stgvol = pool.storageVolLookupByName("{}.qcow2".format(vm))
77 except libvirt.libvirtError:
78 logging.warning("Skipping volume cleanup as volume not found for "
82 logging.info('Deleting storage volume')
88 def clean_ssh_keys(key_file='/root/.ssh/authorized_keys'):
89 logging.info('Removing any stack pub keys from root authorized keys')
90 if not os.path.isfile(key_file):
91 logging.warning("Key file does not exist: ".format(key_file))
93 for line in fileinput.input(key_file, inplace=True):
94 line = line.strip('\n')
95 if 'stack@undercloud' not in line:
100 logging.debug('Cleaning all network config')
101 for network in constants.OPNFV_NETWORK_TYPES:
102 logging.info("Cleaning Jump Host Network config for network "
103 "{}".format(network))
104 jumphost.detach_interface_from_ovs(network)
105 jumphost.remove_ovs_bridge(network)
107 conn = libvirt.open('qemu:///system')
109 raise ApexCleanException('Unable to open libvirt connection')
110 logging.debug('Destroying all virsh networks')
111 for network in conn.listNetworks():
112 if network in constants.OPNFV_NETWORK_TYPES:
113 virsh_net = conn.networkLookupByName(network)
114 logging.debug("Destroying virsh network: {}".format(network))
115 if virsh_net.isActive():
119 except libvirt.libvirtError as e:
120 if 'Network not found' in e.get_error_message():
121 logging.debug('Network already undefined')
127 clean_parser = argparse.ArgumentParser()
128 clean_parser.add_argument('-i',
132 help='File which contains inventory')
133 args = clean_parser.parse_args(sys.argv[1:])
134 os.makedirs(os.path.dirname('./apex_clean.log'), exist_ok=True)
135 formatter = '%(asctime)s %(levelname)s: %(message)s'
136 logging.basicConfig(filename='./apex_clean.log',
138 datefmt='%m/%d/%Y %I:%M:%S %p',
140 console = logging.StreamHandler()
141 console.setLevel(logging.DEBUG)
142 console.setFormatter(logging.Formatter(formatter))
143 logging.getLogger('').addHandler(console)
145 if not os.path.isfile(args.inv_file):
146 logging.error("Inventory file not found: {}".format(args.inv_file))
147 raise FileNotFoundError("Inventory file does not exist")
149 logging.info("Shutting down baremetal nodes")
150 clean_nodes(args.inv_file)
155 # Clean network config
158 # clean pub keys from root's auth keys
161 logging.info('Apex clean complete!')
164 if __name__ == '__main__':