#!/usr/bin/python # mclu (mini cluster) # Copyright (C) 2014 Red Hat Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import argparse import os import re import subprocess import sys import libvirt import config import lib import libvirt_xml def cmdline (subparsers): p = subparsers.add_parser ( 'build', help='build and run a new virtual machine', ) p.add_argument ( '--memory', default=1024, type=int, help='RAM to give to guest (default unit is megabytes)' ) p.add_argument ( '--vcpus', default=4, type=int, help='virtual CPUs to give to guest' ) p.add_argument ( '--virtio', default=True, help='use virtio disks and network' ) p.add_argument ( '--size', required=True, help='size of disk' ) p.add_argument ( 'name', help='name of the new VM (or use "vm:name")' ) p.add_argument ( 'os_version', help='OS & version of guest (see virt-builder docs)' ) p.add_argument ( 'vbargs', nargs='*', help='virt-builder arguments (after "--")' ) p.set_defaults (run=run) def run (c, args): # Did the user request a particular node? If not, we'll run it # on any node which is up. m = re.match (r'^(.*):(.*)$', args.name) if m: node_name = m.group (1) vm_name = m.group (2) else: node = lib.pick_any_node_which_is_up (c) vm_name = args.name # Get all the guests, so we can tell if the name is a duplicate. running, inactive = lib.get_all_guests (c) if vm_name in running or vm_name in inactive: sys.exit ("error: node name (%s) already exists" % vm_name) output = '%s/%s.img' % (c['images_dir'], vm_name) # Call out to virt-builder to build the disk image. vbargs = [ config.VIRT_BUILDER, args.os_version, '--output', output, '--format', 'qcow2', ] if args.size: vbargs.extend (['--size', args.size]) if args.vbargs: vbargs.extend (args.vbargs) subprocess.check_call (vbargs) # XXX Unfortunately this is necessary so qemu can access the disk. os.chmod (output, 0666) # Generate the XML. Would be nice to use virt-install here, but # it doesn't work: RHBZ#1095789 xml = libvirt_xml.generate_libvirt_xml (vm_name, args.memory, args.vcpus, args.virtio, output) # Write the XML to the xmls_dir. fp = open ("%s/%s.xml" % (c['xmls_dir'], vm_name), "w") fp.write (xml) fp.close () # Start the guest. lib.start_guest (c, node_name, vm_name) print "guest built and started on node %s" % node_name