예제 #1
0
파일: __init__.py 프로젝트: likid0/kcli
 def add_nic(self, name, network):
     conn = self.conn
     networks = self.list_networks()
     if network not in networks:
         print("Network %s not found" % network)
         return {'result': 'failure', 'reason': "Network %s not found" % network}
     networktype = networks[network]['type']
     try:
         vm = conn.find_machine(name)
     except:
         common.pprint("VM %s not found" % name, color='red')
         return {'result': 'failure', 'reason': "VM %s not found" % name}
     if self.status(name) == 'up':
         print("VM %s must be down" % name)
         return {'result': 'failure', 'reason': "VM %s must be down" % name}
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     for n in range(7):
         nic = machine.get_network_adapter(n)
         if not nic.enabled:
             nic.enabled = True
             nic.nat_network = network
             if networktype == 'internal':
                 nic.attachment_type = library.NetworkAttachmentType.internal
                 nic.internal_network = network
             else:
                 nic.attachment_type = library.NetworkAttachmentType.nat_network
                 nic.nat_network = network
             break
     machine.save_settings()
     session.unlock_machine()
     return {'result': 'success'}
예제 #2
0
파일: __init__.py 프로젝트: goffinet/kcli
 def delete_disk(self, name, diskname):
     conn = self.conn
     try:
         vm = conn.find_machine(name)
     except:
         print("VM %s not found" % name)
         return
     if status[str(vm.state)] == "up":
         print("VM %s up. Leaving" % name)
         return
     for index in range(10):
         try:
             disk = vm.get_medium('SATA', index, 0)
         except:
             continue
         if disk.name == diskname:
             session = Session()
             vm.lock_machine(session, library.LockType.write)
             machine = session.machine
             machine.detach_device("SATA", index, 0)
             machine.save_settings()
             session.unlock_machine()
             disk.delete_storage()
             return
     print("Disk %s not found in %s" % (diskname, name))
예제 #3
0
    def delete_disk(self, name=None, diskname=None, pool=None):
        """

        :param name:
        :param diskname:
        :param pool:
        :return:
        """
        conn = self.conn
        try:
            vm = conn.find_machine(name)
        except:
            common.pprint("VM %s not found" % name, color='red')
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        if status[str(vm.state)] == "up":
            print("VM %s up. Leaving" % name)
            return {'result': 'failure', 'reason': "VM %s is up" % name}
        for index in range(10):
            try:
                disk = vm.get_medium('SATA', index, 0)
            except:
                continue
            if disk.name == diskname:
                session = Session()
                vm.lock_machine(session, library.LockType.write)
                machine = session.machine
                machine.detach_device("SATA", index, 0)
                machine.save_settings()
                session.unlock_machine()
                disk.delete_storage()
                return {'result': 'success'}
        print("Disk %s not found in %s" % (diskname, name))
        return {'result': 'failure', 'reason': "Disk %s not found in %s" % (diskname, name)}
예제 #4
0
    def delete_nic(self, name, interface):
        """

        :param name:
        :param interface:
        :return:
        """
        conn = self.conn
        try:
            vm = conn.find_machine(name)
        except:
            common.pprint("VM %s not found" % name, color='red')
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        if self.status(name) == 'up':
            print("VM %s must be down" % name)
            return {'result': 'failure', 'reason': "VM %s nust be down" % name}
        session = Session()
        vm.lock_machine(session, library.LockType.write)
        machine = session.machine
        number = int(interface[-1])
        nic = machine.get_network_adapter(number)
        nic.enabled = False
        machine.save_settings()
        session.unlock_machine()
        return {'result': 'success'}
예제 #5
0
def turn_off(uuid, box, timeout):
    ret = False
    try:
        log_string(
            uuid, "{} Status {}".format(box["vm"],
                                        show_status(uuid, box["vm"])),
            "Yellow")
        timeout_start = time()
        virtual_machine = VirtualBox().find_machine(box["vm"])
        if Session().state == SessionState(2):
            Session().unlock_machine()
        if virtual_machine.state != MachineState.aborted:
            with virtual_machine.create_session() as session:
                if virtual_machine.state == MachineState.saved:
                    session.machine.discard_saved_state(True)
                elif virtual_machine.state != MachineState.powered_off:
                    session.console.power_down()
                    while virtual_machine.state != MachineState.powered_off and (
                            time() < timeout_start + timeout):
                        log_string(uuid, "Waiting on {}".format(box["vm"]),
                                   "Yellow")
                        sleep(2)
            if virtual_machine.state == MachineState.powered_off:
                log_string(uuid, "VM is powered off {}".format(box["vm"]),
                           "Yellow")
        ret = True
    except Exception as e:
        log_string(uuid, "turn_off Failed {}".format(e), "Red")
    return ret
예제 #6
0
파일: pool.py 프로젝트: mjdorma/pyvbox
    def acquire(self, username, password, frontend='headless'):
        """Acquire a Machine resource."""
        with self._lock() as root_session:
            for clone in self._clones:
                # Search for a free clone
                session = Session()
                try:
                    clone.lock_machine(session, LockType.write)
                except Exception:
                    continue
                else:
                    try:
                        p = session.machine.restore_snapshot()
                        p.wait_for_completion(60 * 1000)
                    except Exception:
                        pass
                    session.unlock_machine()
                    break
            else:
                # Build a new clone
                machine = root_session.machine
                clone = machine.clone(name="%s Pool" % self.machine_name)
                p = clone.launch_vm_process(type_p=frontend)
                p.wait_for_completion(60 * 1000)
                session = clone.create_session()
                console = session.console
                guest = console.guest
                try:
                    guest_session = guest.create_session(username, password,
                                                         timeout_ms=300 * 1000)
                    idle_count = 0
                    timeout = 60
                    while idle_count < 5 and timeout > 0:
                        act = console.get_device_activity([DeviceType.hard_disk])
                        if act[0] == DeviceActivity.idle:
                            idle_count += 1
                        time.sleep(0.5)
                        timeout -= 0.5
                    guest_session.close()
                    console.pause()
                    p, id_p = console.machine.take_snapshot('initialised',
                                                            'machine pool',
                                                            True)
                    p.wait_for_completion(60 * 1000)
                    self._power_down(session)
                finally:
                    if session.state == SessionState.locked:
                        session.unlock_machine()

            # Launch our clone
            p = clone.launch_vm_process(type_p=frontend)
            p.wait_for_completion(60 * 1000)
            session = clone.create_session()
            return session
예제 #7
0
파일: __init__.py 프로젝트: goffinet/kcli
 def update_ip(self, name, ip):
     conn = self.conn
     try:
         vm = conn.find_machine(name)
     except:
         print("VM %s not found" % name)
         return
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     machine.set_extra_data('ip', ip)
     machine.save_settings()
     session.unlock_machine()
예제 #8
0
 def add_disk(self,
              name,
              size,
              pool=None,
              thin=True,
              template=None,
              shareable=False,
              existing=None):
     conn = self.conn
     # diskformat = 'qcow2'
     if size < 1:
         print("Incorrect size.Leaving...")
         return {'result': 'failure', 'reason': "Incorrect size"}
     # if not thin:
     #     diskformat = 'raw'
     try:
         vm = conn.find_machine(name)
     except:
         common.pprint("VM %s not found" % name, color='red')
         return {'result': 'failure', 'reason': "VM %s not found" % name}
     disks = []
     for index, dev in enumerate(string.lowercase[:10]):
         try:
             vm.get_medium('SATA', index, 0)
             disks.append(0)
         except:
             continue
     index = len(disks)
     if existing is None:
         storagename = "%s_%d" % (name, index)
         diskpath = self.create_disk(name=storagename,
                                     size=size,
                                     pool=pool,
                                     thin=thin,
                                     template=template)
     else:
         disks = self.list_disks()
         if existing in disks:
             diskpath = disks[existing]['path']
         else:
             diskpath = existing
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     disk = conn.open_medium(diskpath, library.DeviceType.hard_disk,
                             library.AccessMode.read_write, True)
     machine.attach_device("SATA", index, 0, library.DeviceType.hard_disk,
                           disk)
     machine.save_settings()
     session.unlock_machine()
     return {'result': 'success'}
예제 #9
0
 def update_metadata(self, name, metatype, metavalue):
     conn = self.conn
     try:
         vm = conn.find_machine(name)
     except:
         common.pprint("VM %s not found" % name, color='red')
         return {'result': 'failure', 'reason': "VM %s not found" % name}
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     machine.set_extra_data(metatype, metavalue)
     machine.save_settings()
     session.unlock_machine()
     return {'result': 'success'}
예제 #10
0
파일: __init__.py 프로젝트: goffinet/kcli
 def update_memory(self, name, memory):
     conn = self.conn
     memory = str(int(memory) * 1024)
     try:
         vm = conn.find_machine(name)
     except:
         print("VM %s not found" % name)
         return
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     machine.memory_size = memory
     machine.save_settings()
     session.unlock_machine()
예제 #11
0
 def update_memory(self, name, memory):
     conn = self.conn
     memory = int(memory)
     try:
         vm = conn.find_machine(name)
     except:
         common.pprint("VM %s not found" % name, color='red')
         return {'result': 'failure', 'reason': "VM %s not found" % name}
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     machine.memory_size = memory
     machine.save_settings()
     session.unlock_machine()
     return {'result': 'success'}
예제 #12
0
    def init(self):
        with open("run.json", "r") as file:
            run = json.load(file)
            for commands in run:
                vbox = VirtualBox()
                session = Session()
                vm = vbox.find_machine(VBOX_MACHINE_NAME)
                p = vm.launch_vm_process(session, 'gui', '')
                p.wait_for_completion(60 * 1000)
                session = vm.create_session()
                gs = session.console.guest.create_session(VBOX_USER_NAME,
                                                          VBOX_PASSWORD,
                                                          timeout_ms=300 *
                                                          1000)
                for command in commands:
                    print("Command: %s" % (command['command']))
                    print("Parameters: %s" % (command['parameters']))
                    print("Sleep: %s" % (command['sleep']))
                    try:
                        process, stdout, stderr = gs.execute(
                            command['command'],
                            command['parameters'],
                            timeout_ms=30 * 1000)
                        print(stdout)
                        time.sleep(int(command['sleep']))
                    except:
                        pass

                self._power_down(session)
                self._extract_victims(
                    VICTIMS_FOLDER_IN,
                    datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
                self._delete_victims(VICTIMS_FOLDER_IN)
예제 #13
0
파일: __init__.py 프로젝트: goffinet/kcli
 def delete_nic(self, name, interface):
     conn = self.conn
     try:
         vm = conn.find_machine(name)
     except:
         print("VM %s not found" % name)
         return
     if self.status(name) == 'up':
         print("VM %s must be down" % name)
         return
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     number = int(interface[-1])
     nic = machine.get_network_adapter(number)
     nic.enabled = False
     machine.save_settings()
     session.unlock_machine()
예제 #14
0
파일: pool.py 프로젝트: maxfragg/pyvbox
 def _lock(self, timeout_ms=-1):
     "Exclusive lock over root machine"
     vbox = VirtualBox()
     machine = vbox.find_machine(self.machine_name)
     wait_time = 0
     while True:
         session = Session()
         try:
             machine.lock_machine(session, LockType.write)
         except Exception as exc:
             if timeout_ms != -1 and wait_time > timeout_ms:
                 raise ValueError("Failed to acquire lock - %s" % exc)
             time.sleep(1)
             wait_time += 1000
         else:
             try:
                 yield session
             finally:
                 session.unlock_machine()
             break
예제 #15
0
파일: pool.py 프로젝트: dwattttt/pyvbox
 def _lock(self, timeout_ms=-1):
     "Exclusive lock over root machine"
     vbox = VirtualBox()
     machine = vbox.find_machine(self.machine_name)
     wait_time = 0
     while True:
         session = Session()
         try:
             machine.lock_machine(session, LockType.write)
         except Exception as exc:
             if timeout_ms != -1 and wait_time > timeout_ms:
                 raise ValueError("Failed to acquire lock - %s" % exc)
             time.sleep(1)
             wait_time += 1000
         else:
             try:
                 yield session
             finally: 
                 session.unlock_machine()
             break
예제 #16
0
파일: pool.py 프로젝트: dwattttt/pyvbox
    def acquire(self, username, password):
        "Acquire a Machine resource"
        with self._lock() as root_session:
            for clone in self._clones:
                # Search for a free clone 
                session = Session()
                try:
                    clone.lock_machine(session, LockType.write)
                except:
                    continue
                else:
                    session.unlock_machine()
                    break
            else:
                # Build a new clone
                machine = root_session.machine
                clone = machine.clone(name="%s Pool" % self.machine_name)
                p = clone.launch_vm_process(type_p='headless')
                p.wait_for_completion(60*1000)
                session = clone.create_session()
                console = session.console
                guest = console.guest
                try:
                    guest_session = guest.create_session(username, password)
                    guest_session.close()
                    console.pause()
                    p = console.take_snapshot('initialised', 'machine pool')
                    p.wait_for_completion(60*1000)
                    self._power_down(session)
                finally:
                    if session.state == SessionState.locked:
                        session.unlock_machine()

            # Launch our clone
            p = clone.launch_vm_process(type_p='headless')
            p.wait_for_completion(60*1000)
            session = clone.create_session()
            return session
예제 #17
0
    def acquire(self, username, password, frontend='headless'):
        "Acquire a Machine resource."
        with self._lock() as root_session:
            for clone in self._clones:
                # Search for a free clone
                session = Session()
                try:
                    clone.lock_machine(session, LockType.write)
                except:
                    continue
                else:
                    try:
                        p = session.console.restore_snapshot()
                        p.wait_for_completion(60 * 1000)
                    except:
                        pass
                    session.unlock_machine()
                    break
            else:
                # Build a new clone
                machine = root_session.machine
                clone = machine.clone(name="%s Pool" % self.machine_name)
                p = clone.launch_vm_process(type_p=frontend)
                p.wait_for_completion(60 * 1000)
                session = clone.create_session()
                console = session.console
                guest = console.guest
                try:
                    guest_session = guest.create_session(username,
                                                         password,
                                                         timeout_ms=5 * 60 *
                                                         1000)
                    idle_count = 0
                    timeout = 60
                    while idle_count < 5 and timeout > 0:
                        act = console.get_device_activity(
                            [DeviceType.hard_disk])
                        if act[0] == DeviceActivity.idle:
                            idle_count += 1
                        time.sleep(0.5)
                        timeout -= 0.5
                    guest_session.close()
                    console.pause()
                    id_p, p = console.machine.take_snapshot(
                        'initialised', 'machine pool', True)
                    time.sleep(10)
                    self._power_down(session)
                finally:
                    if session.state == SessionState.locked:
                        session.unlock_machine()

            # Launch our clone
            p = clone.launch_vm_process(type_p=frontend)
            p.wait_for_completion(60 * 1000)
            session = clone.create_session()
            return session
예제 #18
0
def startVm(vm):
    try:
        with Session() as session:
            vm.launch_vm_process(session, 'gui', '')
    except OleErrorUnexpected as e:
        print("OleErrorUnexpected")
    except OleErrorInvalidarg as e:
        print("OleErrorInvalidarg")
    except VBoxErrorObjectNotFound as e:
        print("VBoxErrorObjectNotFound")
    except VBoxErrorInvalidObjectState as e:
        print("VBoxErrorInvalidObjectState")
    except VBoxErrorInvalidVmState as e:
        print("VBoxErrorInvalidVmState")
    except VBoxErrorIprtError as e:
        print("VBoxErrorIprtError")
    except VBoxErrorHostError as e:
        print("VBoxErrorHostError")
    except  VBoxErrorFileError as e:
        print("VBoxErrorFileError")
예제 #19
0
    def launch_headless(self):
        session = Session()
        progress = self.machine.launch_vm_process(session, 'headless', '')
        progress.wait_for_completion()

        self.instance = session
예제 #20
0
    def create(self, name, virttype='vbox', profile='kvirt', flavor=None, plan='kvirt', cpumodel='', cpuflags=[],
               cpupinning=[], numcpus=2, memory=512, guestid='Linux_64', pool='default', image=None,
               disks=[{'size': 10}], disksize=10, diskthin=True, diskinterface='virtio', nets=['default'], iso=None,
               vnc=False, cloudinit=True, reserveip=False, reservedns=False, reservehost=False, start=True, keys=None,
               cmds=[], ips=None, netmasks=None, gateway=None, nested=True, dns=None, domain=None, tunnel=False,
               files=[], enableroot=True, alias=[], overrides={}, tags=None, dnsclient=None, autostart=False,
               cpuhotplug=False, memoryhotplug=False, numamode=None, numa=[]):
        """

        :param name:
        :param virttype:
        :param profile:
        :param flavor:
        :param plan:
        :param cpumodel:
        :param cpuflags:
        :param cpupinning:
        :param numcpus:
        :param memory:
        :param guestid:
        :param pool:
        :param image:
        :param disks:
        :param disksize:
        :param diskthin:
        :param diskinterface:
        :param nets:
        :param iso:
        :param vnc:
        :param cloudinit:
        :param reserveip:
        :param reservedns:
        :param reservehost:
        :param start:
        :param keys:
        :param cmds:
        :param ips:
        :param netmasks:
        :param gateway:
        :param nested:
        :param dns:
        :param domain:
        :param tunnel:
        :param files:
        :param enableroot:
        :param alias:
        :param overrides:
        :param tags:
        :param cpuhotplug:
        :param memoryhotplug:
        :param numamode:
        :param numa:
        :return:
        """
        if self.exists(name):
            return {'result': 'failure', 'reason': "VM %s already exists" % name}
        guestid = 'Linux_64'
        default_diskinterface = diskinterface
        default_diskthin = diskthin
        default_disksize = disksize
        default_pool = pool
        default_poolpath = '/tmp'
        conn = self.conn
        vm = conn.create_machine("", name, [], guestid, "")
        vm.cpu_count = numcpus
        vm.add_storage_controller('SATA', library.StorageBus(2))
        vm.add_storage_controller('IDE', library.StorageBus(1))
        vm.memory_size = memory
        vm.description = plan
        vm.set_extra_data('profile', profile)
        creationdate = time.strftime("%d-%m-%Y %H:%M", time.gmtime())
        vm.set_extra_data('creationdate', creationdate)
        serial = vm.get_serial_port(0)
        serial.server = True
        serial.enabled = True
        serial.path = str(common.get_free_port())
        serial.host_mode = library.PortMode.tcp
        nat_networks = [network.network_name for network in conn.nat_networks]
        internal_networks = [network for network in conn.internal_networks]
        for index, net in enumerate(nets):
            ip = None
            nic = vm.get_network_adapter(index)
            nic.adapter_type = library.NetworkAdapterType.virtio
            nic.enabled = True
            if isinstance(net, str):
                network = net
            elif isinstance(net, dict) and 'name' in net:
                network = net['name']
                if ips and len(ips) > index and ips[index] is not None:
                    ip = ips[index]
                    vm.set_extra_data('ip', ip)
                    nets[index]['ip'] = ip
                elif 'ip' in nets[index]:
                    ip = nets[index]['ip']
                    vm.set_extra_data('ip', ip)
                if 'mac' in nets[index]:
                    nic.mac_address = nets[index]['mac'].replace(':', '')
            if network in internal_networks:
                nic.attachment_type = library.NetworkAttachmentType.internal
                nic.internal_network = network
            elif network in nat_networks:
                nic.attachment_type = library.NetworkAttachmentType.nat_network
                nic.nat_network = network
                if index == 0:
                    natengine = nic.nat_engine
                    nat_network = [n for n in conn.nat_networks if n.network_name == network][0]
                    nat_network.add_port_forward_rule(False, 'ssh_%s' % name, library.NATProtocol.tcp, '',
                                                      common.get_free_port(), '', 22)
            else:
                nic.attachment_type = library.NetworkAttachmentType.nat
                if index == 0:
                    natengine = nic.nat_engine
                    natengine.add_redirect('ssh_%s' % name, library.NATProtocol.tcp, '', common.get_free_port(), '', 22)
        vm.save_settings()
        conn.register_machine(vm)
        session = Session()
        vm.lock_machine(session, library.LockType.write)
        machine = session.machine
        if iso is None and cloudinit:
            if image is not None:
                guestcmds = self.guestinstall(image)
                if not cmds:
                    cmds = guestcmds
                elif 'rhel' in image:
                    register = [c for c in cmds if 'subscription-manager' in c]
                    if register:
                        index = cmds.index(register[-1])
                        cmds[index + 1:index + 1] = guestcmds
                    else:
                        cmds = guestcmds + cmds
                else:
                    cmds = guestcmds + cmds
                cmds = cmds + ['reboot']
            common.cloudinit(name=name, keys=keys, cmds=cmds, nets=nets, gateway=gateway, dns=dns, domain=domain,
                             reserveip=reserveip, files=files, enableroot=enableroot)
            medium = conn.create_medium('RAW', '/tmp/%s.ISO' % name, library.AccessMode.read_only,
                                        library.DeviceType.dvd)
            progress = medium.create_base_storage(368, [library.MediumVariant.fixed])
            progress.wait_for_completion()
            dvd = conn.open_medium('/tmp/%s.ISO' % name, library.DeviceType.dvd, library.AccessMode.read_only, False)
            machine.attach_device("IDE", 0, 0, library.DeviceType.dvd, dvd)
        for index, disk in enumerate(disks):
            if disk is None:
                disksize = default_disksize
                diskthin = default_diskthin
                diskinterface = default_diskinterface
                diskpool = default_pool
                # diskpoolpath = default_poolpath
            elif isinstance(disk, int):
                disksize = disk
                diskthin = default_diskthin
                diskinterface = default_diskinterface
                diskpool = default_pool
                # diskpoolpath = default_poolpath
            elif isinstance(disk, str) or disk.isdigit():
                disksize = int(disk)
                diskthin = default_diskthin
                diskinterface = default_diskinterface
                diskpool = default_pool
                # diskpoolpath = default_poolpath
            elif isinstance(disk, dict):
                disksize = disk.get('size', default_disksize)
                diskthin = disk.get('thin', default_diskthin)
                diskinterface = disk.get('interface', default_diskinterface)
                diskpool = disk.get('pool', default_pool)
                # diskpoolpath = default_poolpath
            else:
                return {'result': 'failure', 'reason': "Invalid disk entry"}
            diskname = "%s_%d" % (name, index)
            if image is not None and index == 0:
                diskpath = self.create_disk(diskname, disksize, pool=diskpool, thin=diskthin, image=image)
                machine.set_extra_data('image', image)
                # return {'result': 'failure', 'reason': "Invalid image %s" % image}
            else:
                diskpath = self.create_disk(diskname, disksize, pool=diskpool, thin=diskthin, image=None)
            disk = conn.open_medium(diskpath, library.DeviceType.hard_disk, library.AccessMode.read_write, False)
            disksize = disksize * 1024 * 1024 * 1024
            progress = disk.resize(disksize)
            progress.wait_for_completion()
            machine.attach_device("SATA", index, 0, library.DeviceType.hard_disk, disk)
        poolpath = default_poolpath
        for p in self._pool_info():
            poolname = p['name']
            if poolname == pool:
                poolpath = p['path']
        if iso is not None:
            if not os.path.isabs(iso):
                iso = "%s/%s" % (poolpath, iso)
            if not os.path.exists(iso):
                return {'result': 'failure', 'reason': "Invalid iso %s" % iso}
            medium = conn.create_medium('RAW', iso, library.AccessMode.read_only, library.DeviceType.dvd)
            Gb = 1 * 1024 * 1024 * 1024
            progress = medium.create_base_storage(Gb, [library.MediumVariant.fixed])
            progress.wait_for_completion()
            dvd = conn.open_medium(iso, library.DeviceType.dvd, library.AccessMode.read_only, False)
            machine.attach_device("IDE", 0, 0, library.DeviceType.dvd, dvd)
        # if nested and virttype == 'kvm':
        #    print "prout"
        # else:
        #    print "prout"
        # if reserveip:
        #    vmxml = ''
        #    macs = []
        #    for element in vmxml.getiterator('interface'):
        #        mac = element.find('mac').get('address')
        #        macs.append(mac)
        #    self._reserve_ip(name, nets, macs)
        # if reservedns:
        #    self.reserve_dns(name, nets, domain)
        machine.save_settings()
        session.unlock_machine()
        if start:
            self.start(name)
        # if reservehost:
        #    common.reserve_host(name, nets, domain)
        return {'result': 'success'}
예제 #21
0
파일: __init__.py 프로젝트: goffinet/kcli
 def create(self, name, virttype='vbox', title='', description='kvirt', numcpus=2, memory=512, guestid='Linux_64', pool='default', template=None, disks=[{'size': 10}], disksize=10, diskthin=True, diskinterface='virtio', nets=['default'], iso=None, vnc=False, cloudinit=True, reserveip=False, reservedns=False, start=True, keys=None, cmds=None, ips=None, netmasks=None, gateway=None, nested=True, dns=None, domain=None, tunnel=False, files=[]):
     guestid = 'Linux_64'
     default_diskinterface = diskinterface
     default_diskthin = diskthin
     default_disksize = disksize
     default_pool = pool
     default_poolpath = '/tmp'
     conn = self.conn
     vm = conn.create_machine("", name, [], guestid, "")
     vm.cpu_count = numcpus
     vm.add_storage_controller('SATA', library.StorageBus(2))
     vm.add_storage_controller('IDE', library.StorageBus(1))
     vm.memory_size = memory
     vm.description = description
     vm.set_extra_data('profile', title)
     serial = vm.get_serial_port(0)
     serial.server = True
     serial.enabled = True
     serial.path = str(common.get_free_port())
     serial.host_mode = library.PortMode.tcp
     for index, net in enumerate(nets):
         nic = vm.get_network_adapter(index)
         nic.enabled = True
         nic.attachment_type = library.NetworkAttachmentType.nat
         if index == 0:
             natengine = nic.nat_engine
             natengine.add_redirect('ssh', library.NATProtocol.tcp, '', common.get_free_port(), '', 22)
         if isinstance(net, str):
             # nic.attachment_type = library.NetworkAttachmentType.internal
             # nic.attachment_type = library.NetworkAttachmentType.nat
             # nic.attachment_type = library.NetworkAttachmentType.nat_network
             # nic.internal_network = net
             # nic.nat_network = net
             continue
         elif isinstance(net, dict) and 'name' in net:
             # nic.internal_network = net['name']
             # nic.nat_network = net['name']
             ip = None
             if ips and len(ips) > index and ips[index] is not None:
                 ip = ips[index]
                 nets[index]['ip'] = ip
             elif 'ip' in nets[index]:
                 ip = nets[index]['ip']
             if 'mac' in nets[index]:
                 nic.mac_address = nets[index]['mac'].replace(':', '')
     vm.save_settings()
     conn.register_machine(vm)
     session = Session()
     vm.lock_machine(session, library.LockType.write)
     machine = session.machine
     if cloudinit:
         common.cloudinit(name=name, keys=keys, cmds=cmds, nets=nets, gateway=gateway, dns=dns, domain=domain, reserveip=reserveip, files=files)
         medium = conn.create_medium('RAW', '/tmp/%s.iso' % name, library.AccessMode.read_only, library.DeviceType.dvd)
         progress = medium.create_base_storage(368, [library.MediumVariant.fixed])
         progress.wait_for_completion()
         dvd = conn.open_medium('/tmp/%s.iso' % name, library.DeviceType.dvd, library.AccessMode.read_only, False)
         machine.attach_device("IDE", 0, 0, library.DeviceType.dvd, dvd)
     for index, disk in enumerate(disks):
         if disk is None:
             disksize = default_disksize
             diskthin = default_diskthin
             diskinterface = default_diskinterface
             diskpool = default_pool
             # diskpoolpath = default_poolpath
         elif isinstance(disk, int):
             disksize = disk
             diskthin = default_diskthin
             diskinterface = default_diskinterface
             diskpool = default_pool
             # diskpoolpath = default_poolpath
         elif isinstance(disk, dict):
             disksize = disk.get('size', default_disksize)
             diskthin = disk.get('thin', default_diskthin)
             diskinterface = disk.get('interface', default_diskinterface)
             diskpool = disk.get('pool', default_pool)
             # diskpoolpath = default_poolpath
         else:
             return {'result': 'failure', 'reason': "Invalid disk entry"}
         diskname = "%s_%d" % (name, index)
         if template is not None and index == 0:
             diskpath = self.create_disk(diskname, disksize, pool=diskpool, thin=diskthin, template=template)
             machine.set_extra_data('template', template)
             # return {'result': 'failure', 'reason': "Invalid template %s" % template}
         else:
             diskpath = self.create_disk(diskname, disksize, pool=diskpool, thin=diskthin, template=None)
         disk = conn.open_medium(diskpath, library.DeviceType.hard_disk, library.AccessMode.read_write, False)
         print disksize
         disksize = disksize * 1024 * 1024 * 1024
         progress = disk.resize(disksize)
         progress.wait_for_completion()
         machine.attach_device("SATA", index, 0, library.DeviceType.hard_disk, disk)
     machine.save_settings()
     session.unlock_machine()
     if start:
         self.start(name)
     return {'result': 'success'}
     if iso is None:
         if cloudinit:
             iso = "%s/%s.iso" % (default_poolpath, name)
         else:
             iso = ''
     else:
         try:
             if os.path.isabs(iso):
                 shortiso = os.path.basename(iso)
             else:
                 shortiso = iso
             # iso = "%s/%s" % (default_poolpath, iso)
             # iso = "%s/%s" % (isopath, iso)
             print shortiso
         except:
             return {'result': 'failure', 'reason': "Invalid iso %s" % iso}
     # if nested and virttype == 'kvm':
     #    print "prout"
     # else:
     #    print "prout"
     # if reserveip:
     #    vmxml = ''
     #    macs = []
     #    for element in vmxml.getiterator('interface'):
     #        mac = element.find('mac').get('address')
     #        macs.append(mac)
     #    self._reserve_ip(name, nets, macs)
     # if reservedns:
     #    self._reserve_dns(name, nets, domain)
     return {'result': 'success'}
예제 #22
0
from virtualbox import Session, VirtualBox
from virtualbox.library import MachineState


import time
import sys

poll_time = 30

try:
    vbox = VirtualBox()
    session = Session()
except ModuleNotFoundError as e:
    if "vboxapi" in e.msg:
        print("Module 'vboxapi' is missing. Installation steps:")
        print("1. Download the VirtualBox SDK at https://www.virtualbox.org/wiki/Downloads")
        print("2. Extract ZIP")
        print("3. Navigate to installer directory")
        print("4. Run python vboxapisetup.py install")
        sys.exit(-1)
    else:
        raise e

# https://raw.githubusercontent.com/sethmlarson/virtualbox-python/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py

while True:
    machines = list(filter(lambda machine: machine.name.startswith("PIAV"), vbox.machines))
    print("{} VMs found".format(len(machines)))
    for machine in machines:
        print("{}'s state: {}".format(machine.name, machine.state))
        if machine.state == MachineState.powered_off: