def update_stats(self): local_dstat_csv = os.path.join(self.stats_dir, '{0}_dstat.csv'.format(env.host)) dstat_csv = CONF._remote_stats_dir + '/dstat.csv' local_wrk_csv = os.path.join(self.stats_dir, '{0}_wrk.csv'.format(env.host)) wrk_out = CONF._remote_stats_dir + '/wrk.out' if filer.exists(dstat_csv): result = run('tail -n +6 {0}'.format(dstat_csv)) with open(local_dstat_csv, 'w') as f: f.write(str(result)) if filer.exists(wrk_out): result = run('cat {0}'.format(wrk_out)) lines = str(result).split('\n') options = lines[1].strip().split(' ') threads = options[0] connections = options[3] t_latency = re.sub(r' +', ' ', lines[3].strip()).split(' ')[1:] t_rps = re.sub(r' +', ' ', lines[4].strip()).split(' ')[1:] rps = re.sub(r' +', ' ', lines[6].strip()).split(' ')[1] tps = re.sub(r' +', ' ', lines[7].strip()).split(' ')[1] csv = 'threads,connections,rps,tps,t_latency_avg,t_latency_stdev,t_latency_max,t_latency_stdev,t_rps_avg,t_rps_stdev,t_rps_max,t_rps_stdev\n' csv += '{t},{c},{rps},{tps},{t_latency},{t_rps}'.format( t=threads, c=connections, rps=rps, tps=tps, t_latency=','.join(t_latency), t_rps=','.join(t_rps) ) with open(local_wrk_csv, 'w') as f: f.write(csv)
def setup_pcs(self): data = self.init() if env.host == data['hosts'][0]: if not filer.exists('/etc/corosync/authkey'): sudo('corosync-keygen -l') sudo('cp /etc/corosync/authkey /tmp/authkey') sudo('chmod 666 /tmp/authkey') api.get('/tmp/authkey', '/tmp/authkey') sudo('rm /tmp/authkey') else: if not filer.exists('/etc/corosync/authkey'): api.put('/tmp/authkey', '/tmp/authkey') sudo('mv /tmp/authkey /etc/corosync/authkey') sudo('chown root:root /etc/corosync/authkey') sudo('chmod 400 /etc/corosync/authkey') data['bindnetaddr'] = env['node']['ip']['default_dev']['subnet'].split( '/')[0] nodes = [] for i, host in enumerate(env.hosts): ip = socket.gethostbyname(host) nodes.append({'id': i, 'ip': ip}) data['nodes'] = nodes if filer.template('/etc/corosync/corosync.conf', data=data): sudo('systemctl restart pacemaker') sudo('systemctl restart corosync') with api.warn_only(): result = sudo("pcs cluster status") if result.return_code != 0: sudo("pcs cluster start")
def create_image(self, image_name, image_url, disk_format='qcow2', container_format='bare', property='is_public=True'): self.init() result = self.cmd( "image-list 2>/dev/null | grep ' {0} ' | awk '{{print $2}}'".format(image_name)) if len(result) > 0: return result image_file = '/tmp/{0}'.format(image_name) if not filer.exists(image_file): run('wget {0} -O {1}'.format(image_url, image_file)) create_cmd = 'image-create --name "{0}" --disk-format {1}' \ + ' --container-format {2}' \ + ' --property "{3}"' \ + ' --file {4}' result = self.cmd(create_cmd.format( image_name, disk_format, container_format, property, image_file)) result = self.cmd( "image-list 2>/dev/null | grep ' {0} ' | awk '{{print $2}}'".format(image_name)) if len(result) > 0: return result raise Exception('Failed Create Image: {0}'.format(image_name))
def setup(self): """ easy_install, pipをインストールします。 また、pipはパッケージインストール時にソースからコンパイルするため、 いくつかのdevelパッケージをインストールしておきます。 """ self.init() git.setup() self.install_packages() with api.warn_only(): result = run('which easy_install') if result.return_code != 0: sudo('sh -c "cd /tmp/ && wget https://bootstrap.pypa.io/ez_setup.py -O - | python"') with api.warn_only(): result = run('which pip') if result.return_code != 0: sudo('easy_install pip') if self.prefix != '/usr': sudo('pip install virtualenv') if not filer.exists(self.prefix): sudo('virtualenv {0} --system-site-packages'.format(self.prefix))
def setup_package(self, name, git_repos=[], exec_user='******', branch=None, is_develop=False, mk_links=[], mk_dirs=[], cp_files=[], services=[], requirements=[], **kwargs): user.add(exec_user) for git_repo in git_repos: git_dir = os.path.join(self.prefix, 'src', git_repo['name']) git_dir_parent = os.path.dirname(git_dir) filer.mkdir(git_dir_parent, mode='777') git.sync(git_repo['url'], branch=git_repo['branch'], dest=git_dir) requirements_txt = '{0}/requirements.txt'.format(git_dir) if filer.exists(requirements_txt): self.install(requirements=requirements_txt) if is_develop: sudo('sh -c "cd {0} && {1}/bin/python setup.py develop"'.format( git_dir, self.prefix)) else: sudo('sh -c "cd {0} && {1}/bin/python setup.py install"'.format( git_dir, self.prefix)) for mkdir in mk_dirs: filer.mkdir(mkdir['path'], owner=mkdir.get('owner', exec_user)) for cpfile in cp_files: if filer.exists(cpfile['dest']): continue sudo('cp -r {0} {1}'.format( os.path.join(git_dir, cpfile['src']), cpfile['dest'])) for service in services: service['user'] = exec_user filer.template( '/etc/systemd/system/{0}.service'.format(service['name']), src='systemd.service.j2', mode='755', data=service) for requirement in requirements: self.install(requirement) for link in mk_links: if not filer.exists(link['dest']): sudo('ln -s {0} {1}'.format(link['src'], link['dest']))
def create(self): data = self.data sudo('modprobe kvm') sudo('modprobe kvm_intel') for i, vm in enumerate(data['libvirt_vms']): instance_dir = os.path.join(self.instances_dir, vm['name']) filer.mkdir(instance_dir) image_path = '{0}/vm.img'.format(instance_dir) vm['image_path'] = image_path src_image_path = self.wget_src_image(vm) if not filer.exists(image_path): sudo('cp {0} {1}'.format(src_image_path, image_path)) sudo('qemu-img resize {0} {1}G'.format(image_path, vm.get('disk_size', 10))) configiso_path = self.create_configiso(vm, instance_dir) vm['configiso_path'] = configiso_path vm['mac'] = self.get_random_mac() domain_xml = self.create_domain_xml(vm, instance_dir) sudo("sed -i 's/^Defaults.*requiretty/# Defaults requiretty/' /etc/sudoers") sudo("virsh net-update default add ip-dhcp-host " "\"<host mac='{0}' name='{1}' ip='{2}' />\"".format( vm['mac'], vm['name'], vm['ip'])) sudo('virsh define {0}'.format(domain_xml)) sudo('chown -R root:root {0}'.format(instance_dir)) sudo('virsh start {0}'.format(vm['name'])) for vm in data['libvirt_vms']: while True: with api.warn_only(): if run('nmap -p 22 {0} | grep open'.format(vm['ip'])): break time.sleep(5) sudo("iptables -R FORWARD 1 -o virbr0 -s 0.0.0.0/0" " -d 192.168.122.0/255.255.255.0 -j ACCEPT") for vm in data['libvirt_vms']: for port in vm.get('ports', []): sudo("iptables -t nat -A PREROUTING -p tcp" " --dport {0[1]} -j DNAT --to {1}:{0[0]}".format( port, vm['ip'])) for ip in data['iptables']: for port in ip.get('ports', []): sudo("iptables -t nat -A PREROUTING -p tcp" " --dport {0[1]} -j DNAT --to {1}:{0[0]}".format( port, ip['ip'])) time.sleep(5)
def setup(self): data = self.init() if self.is_tag('package'): self.install_packages() self.python.setup() self.python.setup_package(**self.package) # for cinder if not filer.exists('/usr/bin/scsi_id'): sudo('ln -s /lib/udev/scsi_id /usr/bin/') if self.is_tag('conf'): # sudoersファイルは最後に改行入れないと、シンタックスエラーとなりsudo実行できなくなる # sudo: >>> /etc/sudoers.d/nova: syntax error near line 2 <<< # この場合は以下のコマンドでvisudoを実行し、編集する # $ pkexec visudo -f /etc/sudoers.d/nova if filer.template( '/etc/sudoers.d/nova', data=data, src='sudoers.j2', ): self.handlers['restart_nova'] = True if filer.template( '/etc/nova/nova.conf', src='{0}/nova.conf.j2'.format(data['version']), data=data, ): self.handlers['restart_nova'] = True if self.is_tag('data') and env.host == env.hosts[0]: if data['is_master']: sudo('nova-manage db sync') if data['version'] in ['mitaka']: sudo('nova-manage api_db sync') if self.is_tag('service'): self.enable_services().start_services(pty=False) self.exec_handlers() if self.is_tag('data') and env.host == env.hosts[0]: if data['is_master']: self.sync_flavors() return 0
def wget_src_image(self, vm): images_dir = os.path.join(self.libvirt_dir, 'images') filer.mkdir(images_dir) src_image = vm['src_image'].rsplit('/', 1)[1] src_image_path = '{0}/{1}'.format(images_dir, src_image) src_image_format = 'qcow2' if src_image_path[-3:] == '.xz': src_image_path = src_image_path[:-3] src_image_format = 'xz' if not filer.exists(src_image_path): sudo('cd {0} && wget {1}'.format(images_dir, vm['src_image'])) if src_image_format == 'xz': sudo('cd {0} && xz -d {1}'.format(images_dir, src_image)) return src_image_path
def wget_src_image(self, vm): images_dir = os.path.join(self.libvirt_dir, 'images') filer.mkdir(images_dir) src_image = vm['src_image'].rsplit('/', 1)[1] src_image_path = '{0}/{1}'.format(images_dir, src_image) src_image_format = 'qcow2' if src_image_path[-3:] == '.xz': src_image_path = src_image_path[:-3] src_image_format = 'xz' if not filer.exists(src_image_path): sudo('sh -c "cd {0} && wget {1}"'.format(images_dir, vm['src_image'])) if src_image_format == 'xz': sudo('sh -c "cd {0} && xz -d {1}"'.format(images_dir, src_image)) return src_image_path
def setup(self): data = self.init() if self.is_tag('conf'): if env.node['package_manager'] == 'yum': if filer.template('/etc/my.cnf.d/server.cnf', data=data): self.handlers['restart_mariadb'] = True elif env.node['package_manager'] == 'apt': pass if self.is_tag('service'): if self.data['hosts'][0] == env.host: with api.warn_only(): result = sudo('systemctl status mariadb') if result.return_code != 0: sudo('galera_new_cluster') else: self.exec_handlers() self.enable_services().start_services() else: self.enable_services().start_services() self.exec_handlers() if self.is_tag('data'): # init root_password if not filer.exists('/root/.my.cnf'): root_password = data['root_password'] if data['hosts'][0] == env.host: if self.is_ubuntu(): sudo('mysqladmin password {0} -uroot -ptmppass'.format( root_password)) else: sudo('mysqladmin password {0} -uroot'.format( root_password)) filer.template('/root/.my.cnf', data={'root_password': root_password}) if data['hosts'][0] == env.host: self.create_users() self.delete_default_users() self.create_databases()
def sync(url, branch='master', dest=None, user=None): if not dest: name = url.rsplit('/', 1)[1] dest = os.path.join(tmp_dest, name) if not filer.exists(dest): with api.cd('/tmp'): expect( 'git clone -b {0} {1} {2}'.format(branch, url, dest), expects=[ [ 'Are you sure you want to continue connecting (yes/no)?', 'yes\\n' ], ], user=user) else: if user is not None: sudo('cd {0} && git pull'.format(dest), user=user) else: run('cd {0} && git pull'.format(dest)) return dest
def setup(self): data = self.init() run('hostname') self.install_packages() filer.template('/tmp/pdns.sql') sudo('mysql -uroot pdns -e "show tables;" | grep domain || ' 'mysql -uroot pdns < /tmp/pdns.sql') if env.host in data['master']['hosts']: data['is_master'] = True if env.host in data['slave']['hosts']: data['is_slave'] = True filer.template('/etc/pdns/pdns.conf', data=data) self.start_services().enable_services() if not filer.exists('/var/www/html/poweradmin'): sudo('cd /tmp/ && ' 'wget http://downloads.sourceforge.net/project/poweradmin/poweradmin-2.1.7.tgz && ' 'tar xf poweradmin-2.1.7.tgz && ' 'mv poweradmin-2.1.7 /var/www/html/poweradmin && ' 'chown -R apache:apache /var/www/html/poweradmin')
def create_configiso(self, vm, instance_dir): data = self.data template_data = { 'user': CONF.job_user, 'password': CONF.job_password, 'vm': vm, 'gateway': data['libvirt']['gateway'], 'netmask': data['libvirt']['netmask'], } metadata_path = '{0}/meta-data'.format(instance_dir) userdata_path = '{0}/user-data'.format(instance_dir) configiso_path = '{0}/config.iso'.format(instance_dir) src_metadata_path = os.path.join(self.template_dir, 'meta-data') src_userdata_path = os.path.join(self.template_dir, vm['template']) filer.template(metadata_path, src_file=src_metadata_path, data=template_data) filer.template(userdata_path, src_file=src_userdata_path, data=template_data) if not filer.exists(configiso_path): sudo('genisoimage -o {0} -V cidata -r -J {1} {2}'.format( configiso_path, metadata_path, userdata_path)) return configiso_path
def create(self): data = self.data sudo('modprobe kvm') sudo('modprobe kvm_intel') network = CONF.network.libvirt_net.split(':') bridge = network[0] brctl_show = sudo('brctl show') if brctl_show.find(bridge) == -1: sudo('brctl addbr {0}'.format(bridge)) ip_network = IPNetwork(network[1]) gateway_ip = '{0}/{1}'.format(ip_network.ip + 1, ip_network.prefixlen) dhcp_ip = '{0}/{1}'.format(ip_network.ip + 2, ip_network.prefixlen) bridge_info = sudo('ip addr show dev {0}'.format(bridge)) if bridge_info.find(gateway_ip) == -1: sudo('ip addr add {0} dev {1}'.format(gateway_ip, bridge)) if bridge_info.find('DOWN') != -1: sudo('ip link set {0} up'.format(bridge)) sudo('ip route add 10.0.0.0/8 via {0}'.format(ip_network.ip + 1)) network_seg = "{0}/{1}".format(ip_network.ip, ip_network.netmask) ip_netns = sudo('ip netns show') dhcp_netns = 'dhcp-{0}'.format(bridge) dhcp_veth_br = 'ns-{0}'.format(bridge) dhcp_veth = 'veth-{0}'.format(bridge) if ip_netns.find(dhcp_netns): sudo('ip netns add {0}'.format(dhcp_netns)) if brctl_show.find(dhcp_veth_br) == -1: sudo('ip link add {0} type veth peer name {1}'.format(dhcp_veth_br, dhcp_veth)) sudo('brctl addif {0} {1}'.format(bridge, dhcp_veth_br)) sudo('ip link set {0} up'.format(dhcp_veth_br)) sudo('ip link set {0} netns {1}'.format(dhcp_veth, dhcp_netns)) sudo('ip netns exec {0} ip addr add dev {1} {2}'.format(dhcp_netns, dhcp_veth, dhcp_ip)) sudo('ip netns exec {0} ip link set {1} up'.format(dhcp_netns, dhcp_veth)) # ss_ln = sudo('ip netns exec {0} ss -ln'.format(dhcp_netns)) # if ss_ln.find('*:67') == -1: # sudo('ip netns exec {0} dnsmasq -p 0 --dhcp-range 172.16.100.3,172.16.100.254,12h'.format( # noqa # dhcp_netns, ip_network[3], ip_network[-2])) ss_ln = sudo('ss -ln'.format(dhcp_netns)) if ss_ln.find('*:67') == -1: sudo('dnsmasq -p 0 --dhcp-range=172.16.100.3,172.16.100.254') for i, vm in enumerate(data['libvirt_vms']): instance_dir = os.path.join(self.instances_dir, vm['name']) filer.mkdir(instance_dir) vm['bridge'] = bridge vm['hostname'] = '{0}.{1}'.format(vm['name'], CONF.network.domain) image_path = '{0}/vm.img'.format(instance_dir) vm['image_path'] = image_path src_image_path = self.wget_src_image(vm) if not filer.exists(image_path): sudo('cp {0} {1}'.format(src_image_path, image_path)) sudo('qemu-img resize {0} {1}G'.format(image_path, vm.get('disk_size', 10))) if 'disk_cache' not in vm: vm['disk_cache'] = 'none' elif vm['disk_cache'] not in ['none', 'writethrough', 'writeback', 'directsync', 'unsafe', 'default']: raise Exception('Invalid disk_cache: {0}'.format(vm['disk_cache'])) configiso_path = self.create_configiso(vm, instance_dir) vm['configiso_path'] = configiso_path alias_index = 0 pci_slot_num = 2 for port in vm['ports']: mac = self.get_random_mac() port['mac'] = mac port['tap'] = 'tap{0}'.format(mac.replace(':', '')) port['pci_slot'] = '0x0{0}'.format(pci_slot_num) pci_slot_num += 1 port['alias_name'] = 'net{0}'.format(alias_index) alias_index += 1 vm['memballoon'] = { 'pci_slot': '0x0{0}'.format(pci_slot_num) } domain_xml = self.create_domain_xml(vm, instance_dir) sudo("sed -i 's/^Defaults.*requiretty/# Defaults requiretty/' /etc/sudoers") for port in vm['ports']: if port['ip'] == 'none': continue # sudo("virsh net-update {3} add ip-dhcp-host " # "\"<host mac='{0}' name='{1}' ip='{2}' />\"".format( # port['mac'], vm['name'], port['ip'], bridge)) sudo('virsh define {0}'.format(domain_xml)) sudo('chown -R root:root {0}'.format(instance_dir)) sudo('virsh start {0}'.format(vm['name'])) nat_table = sudo("iptables -t nat -L") if nat_table.find(network_seg) == -1: # sudo("iptables -R FORWARD 1 -o {0} -s {1}" # " -d 0.0.0.0/0 -j ACCEPT".format(bridge, network_seg)) sudo("iptables -t filter -A FORWARD -s 0.0.0.0/0 -d {0} -j ACCEPT".format(network_seg)) sudo("iptables -t filter -A FORWARD -d 0.0.0.0/0 -s {0} -j ACCEPT".format(network_seg)) nat_table = sudo("iptables -t nat -L") if nat_table.find(network_seg) == -1: sudo("iptables -t nat -A POSTROUTING -p TCP -s {0} ! -d {0} -j MASQUERADE --to-ports 1024-65535".format( network_seg)) sudo("iptables -t nat -A POSTROUTING -p UDP -s {0} ! -d {0} -j MASQUERADE --to-ports 1024-65535".format( network_seg)) sudo("iptables -t nat -A POSTROUTING -s {0} ! -d {0} -j MASQUERADE".format( network_seg)) sudo("iptables -t nat -A POSTROUTING -s {0} -d 255.255.255.255 -j RETURN".format( network_seg)) sudo("iptables -t nat -A POSTROUTING -s {0} -d base-address.mcast.net/24 -j RETURN".format( network_seg)) for vm in data['libvirt_vms']: self.pdns.create_record(vm['name'], CONF.network.domain, 'A', vm['ports'][0]['ip']) while True: with api.warn_only(): if run('nmap -p 22 {0} | grep open'.format(vm['ports'][0]['ip'])): break time.sleep(5) for ip in data.get('iptables', {}): for port in ip.get('ports', []): if ip['ip'] == 'none': continue sudo("iptables -t nat -A PREROUTING -p tcp" " --dport {0[1]} -j DNAT --to {1}:{0[0]}".format( port, ip['ip'])) time.sleep(60)
def setup_network_bridge(self): data = self.init() if 'linuxbridge' in data['ml2']['mechanism_drivers']: sudo('modprobe bridge') elif 'openvswitch' in data['ml2']['mechanism_drivers']: sudo('modprobe -r bridge') Service('openvswitch').start().enable() sudo('ovs-vsctl br-exists {0} || ovs-vsctl add-br {0}'.format( data['ovs']['integration_bridge'])) filer.template( '/etc/sysconfig/network-scripts/ifcfg-{0}'.format( data['ovs']['integration_bridge']), src='network/ovs-ifcfg-br.j2', data=data) for mapping in data['ovs']['bridge_mappings']: pair = mapping.split(':') ovs_interface = pair[1] sudo('ovs-vsctl br-exists {0} || ovs-vsctl add-br {0}'.format(ovs_interface)) for mapping in data['ovs']['physical_interface_mappings']: pair = mapping.split(':') ovs_interface = pair[0] physical_interface = pair[1] backup_default_dev_file = '/etc/sysconfig/network-scripts/bk-ifcfg-defualt' if filer.exists(backup_default_dev_file): default = run('cat {0}'.format(backup_default_dev_file)) dev, ip, subnet, gateway = default.split(':') data['default_dev'] = { 'dev': dev, 'ip': ip, 'subnet': subnet, 'gateway': gateway, } else: sudo("echo '{0[dev]}:{0[ip]}:{0[subnet]}:{1}' > {2}".format( env.node['ip']['default_dev'], env.node['ip']['default']['ip'], backup_default_dev_file)) data['default_dev'] = env.node['ip']['default_dev'] data['default_dev']['gateway'] = env.node['ip']['default']['ip'] data['default_dev']['netmask'] = self.cidr( data['default_dev']['subnet'].split('/')[1]) if physical_interface == data['default_dev']['dev']: # create backup for default interface data['ovs_interface'] = ovs_interface filer.template( '/etc/sysconfig/network-scripts/ifcfg-{0}'.format(physical_interface), src='network/ovs-ifcfg-flat.j2', data=data) filer.template( '/etc/sysconfig/network-scripts/ifcfg-{0}'.format(ovs_interface), src='network/ovs-ifcfg-br-flat.j2', data=data) result = sudo('ovs-vsctl list-ports {0}'.format(ovs_interface)) if result.find(data['default_dev']['dev']) == -1: with api.warn_only(): api.reboot(180)
def setup(self): data = self.init() node_os = env.node['os'] if re.match('Ubuntu 14.*', node_os): with api.warn_only(): sudo('apt-get update -y') self.install_packages() self.start_services() sudo('modprobe kvm') sudo('modprobe kvm_intel') for i, vm in enumerate(data['libvirt_vms']): template_data = { 'user': CONF.test.user, 'password': CONF.test.password, 'vm': vm, 'gateway': data['libvirt']['gateway'], 'netmask': data['libvirt']['netmask'], } vm_dir = '/var/lib/libvirt/images/{0}'.format(vm['name']) image_path = '{0}/vm.img'.format(vm_dir) metadata_path = '{0}/meta-data'.format(vm_dir) userdata_path = '{0}/user-data'.format(vm_dir) configiso_path = '{0}/config.iso'.format(vm_dir) src_image = vm['src_image'].rsplit('/', 1)[1] src_image_path = '/var/lib/libvirt/images/{0}'.format(src_image) src_image_format = 'qcow2' if src_image_path[-3:] == '.xz': src_image_path = src_image_path[:-3] src_image_format = 'xz' if not filer.exists(src_image_path): sudo('cd /var/lib/libvirt/images/ && wget {0}'.format(vm['src_image'])) if src_image_format == 'xz': sudo('cd /var/lib/libvirt/images/ && xz -d {0}'.format(src_image)) with api.warn_only(): sudo("virsh list --all | grep {0} && virsh destroy {0}" " && virsh undefine {0}".format(vm['name'])) sudo('rm -rf {0}'.format(vm_dir)) filer.mkdir(vm_dir) if not filer.exists(image_path): sudo('cp {0} {1}'.format(src_image_path, image_path)) sudo('qemu-img resize {0} {1}G'.format(image_path, vm.get('disk_size', 10))) filer.template(metadata_path, src='meta-data', data=template_data) filer.template(userdata_path, src=vm['template'], data=template_data) if not filer.exists(configiso_path): sudo('genisoimage -o {0} -V cidata -r -J {1} {2}'.format( configiso_path, metadata_path, userdata_path)) sudo("sed -i 's/^Defaults.*requiretty/# Defaults requiretty/' /etc/sudoers") vm['uuid'] = str(uuid.uuid1()) vm['image_path'] = image_path vm['configiso_path'] = configiso_path vm['tap'] = 'tap{0}'.format(i) vm['mac'] = self.get_random_mac() domain_xml = '/tmp/domain-{0}.xml'.format(vm['name']) filer.template(domain_xml, src='domain.xml', data=vm) with api.warn_only(): sudo("virsh net-update default delete ip-dhcp-host \"`virsh net-dumpxml default | grep '{0}' | sed -e 's/^ *//'`\"".format(vm['ip'])) sudo("virsh net-update default add ip-dhcp-host " "\"<host mac='{0}' name='{1}' ip='{2}' />\"".format( vm['mac'], vm['name'], vm['ip'])) sudo('virsh define {0}'.format(domain_xml)) sudo('virsh start {0}'.format(vm['name'])) # sudo("virt-install" # " --connect=qemu:///system" # " --name={name} --vcpus={vcpus} --ram={ram}" # " --accelerate --hvm --virt-type=kvm" # " --cpu host" # " --network bridge=virbr0,model=virtio" # " --disk {image_path},format=qcow2 --import" # " --disk {configiso_path},device=cdrom" # " --nographics &".format( # name=vm['name'], # vcpus=vm['vcpus'], # ram=vm['ram'], # image_path=image_path, # configiso_path=configiso_path, # ip=vm['ip'], # ), pty=False) # ), pty=False) for vm in data['libvirt_vms']: while True: with api.warn_only(): if run('nmap -p 22 {0} | grep open'.format(vm['ip'])): break time.sleep(5) sudo("iptables -R FORWARD 1 -o virbr0 -s 0.0.0.0/0" " -d 192.168.122.0/255.255.255.0 -j ACCEPT") for vm in data['libvirt_vms']: for port in vm.get('ports', []): sudo("iptables -t nat -A PREROUTING -p tcp" " --dport {0[1]} -j DNAT --to {1}:{0[0]}".format( port, vm['ip'])) for ip in data['iptables']: for port in ip.get('ports', []): sudo("iptables -t nat -A PREROUTING -p tcp" " --dport {0[1]} -j DNAT --to {1}:{0[0]}".format( port, ip['ip']))