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')
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 for line in fileinput.input(key_file, inplace=True):
91 line = line.strip('\n')
92 if 'stack@undercloud' not in line:
97 clean_parser = argparse.ArgumentParser()
98 clean_parser.add_argument('-i',
102 help='File which contains inventory')
103 args = clean_parser.parse_args(sys.argv[1:])
104 os.makedirs(os.path.dirname('./apex_clean.log'), exist_ok=True)
105 formatter = '%(asctime)s %(levelname)s: %(message)s'
106 logging.basicConfig(filename='./apex_clean.log',
108 datefmt='%m/%d/%Y %I:%M:%S %p',
110 console = logging.StreamHandler()
111 console.setLevel(logging.DEBUG)
112 console.setFormatter(logging.Formatter(formatter))
113 logging.getLogger('').addHandler(console)
115 if not os.path.isfile(args.inv_file):
116 logging.error("Inventory file not found: {}".format(args.inv_file))
117 raise FileNotFoundError("Inventory file does not exist")
119 logging.info("Shutting down baremetal nodes")
120 clean_nodes(args.inv_file)
125 # Clean network config
126 for network in constants.ADMIN_NETWORK, constants.EXTERNAL_NETWORK:
127 logging.info("Cleaning Jump Host Network config for network "
128 "{}".format(network))
129 jumphost.detach_interface_from_ovs(network)
130 jumphost.remove_ovs_bridge(network)
132 # clean pub keys from root's auth keys
135 logging.info('Apex clean complete!')
137 if __name__ == '__main__':