Python libvirt.VIR_DOMAIN_RUNNING Examples

The following are 22 code examples of libvirt.VIR_DOMAIN_RUNNING(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module libvirt , or try the search function .
Example #1
Source File: test_create_VM_overlay.py    From elijah-provisioning with Apache License 2.0 6 votes vote down vote up
def test_create_vm_overlay(self):
        disk_path=self.base_vm_path
        dbconn, matching_basevm = PackagingUtil._get_matching_basevm(disk_path)
        base_diskpath = matching_basevm.disk_path
        options = Options()
        options.TRIM_SUPPORT = True
        options.ZIP_CONTAINER = True
        options.FREE_SUPPORT = False
        options.DISK_ONLY = False
        try:
            vm_overlay = synthesis.VM_Overlay(base_diskpath, options)
            machine = vm_overlay.resume_basevm()
            VM_status = VMUtility.get_VM_status(machine)
            self.assertEqual(VM_status, libvirt.VIR_DOMAIN_RUNNING)

            # wait for VM running
            time.sleep(10)
            vm_overlay.create_overlay()
            self.overlay_filepath = vm_overlay.overlay_zipfile
            self.assertTrue(os.path.exists(self.overlay_filepath), True)
        except Exception as e:
            self.assertTrue(False, "cannot create VM overlay: %s" % str(e)) 
Example #2
Source File: create_xml_with_files.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def create_xml_with_files_clean(params):
    logger = params['logger']
    guestname = params['guestname']

    for i in range(len(files)):
        ret = utils.del_file("/tmp/libvirt-test-api-create-file-%d" % i, logger)
    ret = utils.del_file("/tmp/libvirt_passfile_check", logger)

    conn = libvirt.open("lxc:///")
    dom = conn.lookupByName(guestname)
    guest_state = dom.info()[0]
    if guest_state == libvirt.VIR_DOMAIN_RUNNING:
        logger.debug("destroy guest: %s." % guestname)
        time.sleep(5)
        dom.destroyFlags()
        define_list = conn.listDefinedDomains()
        if guestname in define_list:
            time.sleep(3)
            dom.undefine()
            time.sleep(3)
    elif guest_state == libvirt.VIR_DOMAIN_SHUTOFF:
        time.sleep(5)
        dom.undefine()
        time.sleep(3) 
Example #3
Source File: create_with_files.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def create_with_files_clean(params):
    logger = params['logger']
    for i in range(len(files)):
        ret = utils.del_file("/tmp/libvirt-test-api-create-file-%d" % i, logger)
    ret = utils.del_file("/tmp/libvirt_passfile_check", logger)

    conn = libvirt.open("lxc:///")
    dom = conn.lookupByName(guestname)
    guest_state = dom.info()[0]
    if guest_state == libvirt.VIR_DOMAIN_RUNNING:
        logger.debug("destroy guest: %s." % guestname)
        time.sleep(5)
        dom.destroyFlags()
        define_list = conn.listDefinedDomains()
        if guestname in define_list:
            time.sleep(3)
            dom.undefine()
            time.sleep(3)
    elif guest_state == libvirt.VIR_DOMAIN_SHUTOFF:
        time.sleep(5)
        dom.undefine()
        time.sleep(3) 
Example #4
Source File: migrate.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def get_state(state):
    dom_state = ''
    if state == libvirt.VIR_DOMAIN_NOSTATE:
        dom_state = 'nostate'
    elif state == libvirt.VIR_DOMAIN_RUNNING:
        dom_state = 'running'
    elif state == libvirt.VIR_DOMAIN_BLOCKED:
        dom_state = 'blocked'
    elif state == libvirt.VIR_DOMAIN_PAUSED:
        dom_state = 'paused'
    elif state == libvirt.VIR_DOMAIN_SHUTDOWN:
        dom_state = 'shutdown'
    elif state == libvirt.VIR_DOMAIN_SHUTOFF:
        dom_state = 'shutoff'
    elif state == libvirt.VIR_DOMAIN_CRASHED:
        dom_state = 'crashed'
    else:
        dom_state = 'no sure'
    return dom_state 
Example #5
Source File: migrate_tls.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def get_state(state):
    dom_state = ''
    if state == libvirt.VIR_DOMAIN_NOSTATE:
        dom_state = 'nostate'
    elif state == libvirt.VIR_DOMAIN_RUNNING:
        dom_state = 'running'
    elif state == libvirt.VIR_DOMAIN_BLOCKED:
        dom_state = 'blocked'
    elif state == libvirt.VIR_DOMAIN_PAUSED:
        dom_state = 'paused'
    elif state == libvirt.VIR_DOMAIN_SHUTDOWN:
        dom_state = 'shutdown'
    elif state == libvirt.VIR_DOMAIN_SHUTOFF:
        dom_state = 'shutoff'
    elif state == libvirt.VIR_DOMAIN_CRASHED:
        dom_state = 'crashed'
    else:
        dom_state = 'no sure'
    return dom_state 
Example #6
Source File: managedsave_define_xml.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def managedsave_define_xml_clean(params):
    guestname = params['guestname']
    logger = params['logger']
    conn = libvirt.open()
    dom = conn.lookupByName(guestname)
    state = dom.info()[0]
    if state == libvirt.VIR_DOMAIN_RUNNING:
        dom.destroy()
    dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) 
Example #7
Source File: test_synthesis.py    From elijah-provisioning with Apache License 2.0 5 votes vote down vote up
def test_synthesis_step_by_step(self):
        # decompress VM overlay
        overlay_filename = NamedTemporaryFile(prefix="cloudlet-test-overlay-file-")
        meta_info = compression.decomp_overlayzip(self.overlay_url,
                                                  overlay_filename.name)
        self.assertIsInstance(meta_info, dict)
        self.assertTrue(meta_info.has_key(Cloudlet_Const.META_OVERLAY_FILES))

        # recover launch VM
        launch_disk, launch_mem, fuse, delta_proc, fuse_thread = \
            synthesis.recover_launchVM(self.base_vm_path, meta_info, overlay_filename.name)
        self.assertTrue(os.path.exists(launch_disk))
        self.assertTrue(os.path.exists(launch_mem))
        self.assertIsInstance(fuse, CloudletFS)

        # resume launch VM
        synthesized_VM = synthesis.SynthesizedVM(
            launch_disk, launch_mem, fuse, disk_only=False
        )
        delta_proc.start()
        fuse_thread.start()
        delta_proc.join()
        fuse_thread.join()
        synthesized_VM.resume()

        # check VM's status
        VM_status = VMUtility.get_VM_status(synthesized_VM.machine)
        self.assertEqual(VM_status, libvirt.VIR_DOMAIN_RUNNING)

        # cleanup
        synthesized_VM.monitor.terminate()
        synthesized_VM.monitor.join()
        synthesized_VM.terminate() 
Example #8
Source File: domain_common.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_dom_state(domobj):
    state = domobj.info()[0]
    expect_states = [libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_RUNNING]
    if state in expect_states:
        return state
    return -1 
Example #9
Source File: save_image_define_xml.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_dom_state(domobj):
    state = domobj.info()[0]
    expect_states = [libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_RUNNING]
    if state in expect_states:
        return state
    return 0 
Example #10
Source File: set_perf_events.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_events(events, event_list, guestname, flags, domstate, dom, logger):
    values = {}
    if ((domstate == libvirt.VIR_DOMAIN_RUNNING) and
        ((flags == libvirt.VIR_DOMAIN_AFFECT_CURRENT) or
         (flags == libvirt.VIR_DOMAIN_AFFECT_LIVE))):
        xmlstr = minidom.parse("%s%s.xml" % (XML_PATH, guestname))
    else:
        guestxml = dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
        xmlstr = minidom.parseString(guestxml)

    perf = xmlstr.getElementsByTagName('perf')
    if perf:
        perf = xmlstr.getElementsByTagName('perf')[0]
        for item in perf.getElementsByTagName('event'):
            for i in event_list:
                if item.getAttribute('name') == i:
                    if item.getAttribute('enabled') == "yes":
                        values[i] = True
                    elif item.getAttribute('enabled') == "no":
                        values[i] = False

    logger.info("values: %s" % values)
    for i in event_list:
        if i in list(values.keys()) and i in list(events.keys()):
            if values[i] != events[i]:
                return 1

    return 0 
Example #11
Source File: snapshot_revert.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_domain_state(*args):
    """ check if the domain state after revert """

    (flagn, domobj, snapshot) = args
    state = domobj.info()[0]

    if snapshot.isCurrent(0):
        logger.info("Successfull revert to given snapshotname")

        # The passed flags include "running"
        if (flagn == 1) or (flagn == 5):
            logger.info("After reverting, change state to running")
            expect_states = [libvirt.VIR_DOMAIN_RUNNING,
                             libvirt.VIR_DOMAIN_RUNNING_FROM_SNAPSHOT,
                             libvirt.VIR_DOMAIN_RUNNING_BOOTED]
            if state in expect_states:
                logger.info("Successful revert.The domain state is running.")
                return True
            else:
                logger.error("Failed to revert.The domain state isn't running")
                return False
        # The passed flags include "paused"
        elif (flagn == 2) or (flagn == 6):
            expect_states = [libvirt.VIR_DOMAIN_PAUSED,
                             libvirt.VIR_DOMAIN_PAUSED_FROM_SNAPSHOT,
                             libvirt.VIR_DOMAIN_PAUSED_SNAPSHOT]
            if state in expect_states:
                logger.info("Successful revert.The domain state is paused.")
                return True
            else:
                logger.error("Failed to revert.The domain state isn't paused")
                return False
    else:
        logger.error("Failed to revert to given snapshotname ")
        return False 
Example #12
Source File: managedsave_get_xml_desc.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def managedsave_get_xml_desc_clean(params):
    guestname = params['guestname']
    logger = params['logger']
    conn = libvirt.open()
    dom_list = conn.listAllDomains()
    for dom in dom_list:
        if dom.name() == guestname:
            if dom.info()[0] == libvirt.VIR_DOMAIN_RUNNING:
                dom.destroy()
            dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) 
Example #13
Source File: managedsave_define_xml.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_dom_state(domobj):
    state = domobj.info()[0]
    expect_states = [libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_RUNNING]
    if state in expect_states:
        return state
    return 0 
Example #14
Source File: create_xml_with_files.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_dom_state(domobj):
    state = domobj.info()[0]
    expect_states = [libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_NOSTATE,
                     libvirt.VIR_DOMAIN_BLOCKED]

    if state in expect_states:
        return 1
    return 0 
Example #15
Source File: virtual_machine.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def _get_power_state(self):
        """Return the power state of the VM in the form of a PowerStates enum."""
        if self.isRegistered():
            remote_libvirt = (self.isRegisteredRemotely() and not self.po__cluster_disabled)
            libvirt_object = self._get_libvirt_domain_object(allow_remote=remote_libvirt)
            if libvirt_object.state()[0] == libvirt.VIR_DOMAIN_RUNNING:
                return PowerStates.RUNNING
            else:
                return PowerStates.STOPPED
        else:
            return PowerStates.UNKNOWN 
Example #16
Source File: kvm_virtualisation.py    From igcollect with MIT License 5 votes vote down vote up
def main():
    args = parse_args()
    conn = libvirt.openReadOnly(None)
    now = str(int(time()))
    core2node = get_cpu_core_to_numa_node_mapping()

    total_mem_used = 0

    for dom in conn.listAllDomains():
        name = dom.name()
        if args.trim_domain:
            if name.endswith('.' + args.trim_domain):
                name = name[:-len('.' + args.trim_domain)]
        # Strip objectid from domain name to get the hostname
        if '_' in name:
            name = name.split('_', 1)[1]
        # Make hostname save for graphite
        name = name.replace('.', '_')

        dom_state, dom_reason = dom.state()
        if dom_state == libvirt.VIR_DOMAIN_RUNNING:
            get_dom_vcpu_stats(dom, args.prefix, name, now, core2node)
            get_dom_network_stats(dom, args.prefix, name, now)
            get_dom_disk_stats(dom, args.prefix, name, now)

        total_mem_used += get_dom_memory_stats(dom, args.prefix, name, now)
        get_dom_storage_usage(conn, dom, args.prefix, name, now)

    get_hv_storage_usage(conn, args.prefix, now)
    get_hv_memory_usage(conn, args.prefix, now, total_mem_used) 
Example #17
Source File: host_thread.py    From openmano with Apache License 2.0 4 votes vote down vote up
def update_servers_status(self):
                            # # virDomainState
                            # VIR_DOMAIN_NOSTATE = 0
                            # VIR_DOMAIN_RUNNING = 1
                            # VIR_DOMAIN_BLOCKED = 2
                            # VIR_DOMAIN_PAUSED = 3
                            # VIR_DOMAIN_SHUTDOWN = 4
                            # VIR_DOMAIN_SHUTOFF = 5
                            # VIR_DOMAIN_CRASHED = 6
                            # VIR_DOMAIN_PMSUSPENDED = 7   #TODO suspended
    
        if self.test or len(self.server_status)==0:
            return            
        
        try:
            conn = libvirt.open("qemu+ssh://"+self.user+"@"+self.host+"/system")
            domains=  conn.listAllDomains() 
            domain_dict={}
            for domain in domains:
                uuid = domain.UUIDString() ;
                libvirt_status = domain.state()
                #print libvirt_status
                if libvirt_status[0] == libvirt.VIR_DOMAIN_RUNNING or libvirt_status[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
                    new_status = "ACTIVE"
                elif libvirt_status[0] == libvirt.VIR_DOMAIN_PAUSED:
                    new_status = "PAUSED"
                elif libvirt_status[0] == libvirt.VIR_DOMAIN_SHUTOFF:
                    new_status = "INACTIVE"
                elif libvirt_status[0] == libvirt.VIR_DOMAIN_CRASHED:
                    new_status = "ERROR"
                else:
                    new_status = None
                domain_dict[uuid] = new_status
            conn.close
        except libvirt.libvirtError as e:
            print self.name, ": get_state() Exception '", e.get_error_message()
            return

        for server_id, current_status in self.server_status.iteritems():
            new_status = None
            if server_id in domain_dict:
                new_status = domain_dict[server_id]
            else:
                new_status = "INACTIVE"
                            
            if new_status == None or new_status == current_status:
                continue
            if new_status == 'INACTIVE' and current_status == 'ERROR':
                continue #keep ERROR status, because obviously this machine is not running
            #change status
            print self.name, ": server ", server_id, "status change from ", current_status, "to", new_status
            STATUS={'progress':100, 'status':new_status}
            if new_status == 'ERROR':
                STATUS['last_error'] = 'machine has crashed'
            self.db_lock.acquire()
            r,_ = self.db.update_rows('instances', STATUS, {'uuid':server_id}, log=False)
            self.db_lock.release()
            if r>=0:
                self.server_status[server_id] = new_status 
Example #18
Source File: perf_events.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def check_events(events, guestname, flags, domstate, dom, logger):
    if utils.version_compare("libvirt-python", 3, 2, 0, logger):
        values = {'cmt': False, 'mbml': False, 'mbmt': False, 'cpu_cycles': False,
                  'instructions': False, 'cache_references': False,
                  'cache_misses': False, 'branch_instructions': False,
                  'branch_misses': False, 'bus_cycles': False,
                  'ref_cpu_cycles': False, 'stalled_cycles_backend': False,
                  'stalled_cycles_frontend': False, 'alignment_faults': False,
                  'context_switches': False, 'cpu_clock': False,
                  'cpu_migrations': False, 'emulation_faults': False,
                  'page_faults': False, 'page_faults_maj': False,
                  'page_faults_min': False, 'task_clock': False}
        event_list = ('cmt', 'mbmt', 'mbml', 'cpu_cycles', 'instructions',
                      'cache_references', 'cache_misses', 'branch_instructions',
                      'branch_misses', 'bus_cycles', 'ref_cpu_cycles',
                      'stalled_cycles_backend', 'stalled_cycles_frontend',
                      'alignment_faults', 'context_switches', 'cpu_clock',
                      'cpu_migrations', 'emulation_faults', 'page_faults',
                      'page_faults_maj', 'page_faults_min', 'task_clock')
    else:
        values = {'cmt': False, 'mbml': False, 'mbmt': False}
        event_list = ('cmt', 'mbmt', 'mbml')

    if ((domstate == libvirt.VIR_DOMAIN_RUNNING) and
        ((flags == libvirt.VIR_DOMAIN_AFFECT_CURRENT) or
         (flags == libvirt.VIR_DOMAIN_AFFECT_LIVE))):
        xmlstr = minidom.parse("%s%s.xml" % (XML_PATH, guestname))
    else:
        guestxml = dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
        xmlstr = minidom.parseString(guestxml)

    perf = xmlstr.getElementsByTagName('perf')
    if perf:
        perf = xmlstr.getElementsByTagName('perf')[0]
        for item in perf.getElementsByTagName('event'):
            for i in event_list:
                if item.getAttribute('name') == i:
                    if item.getAttribute('enabled') == "yes":
                        values[i] = True
                    elif item.getAttribute('enabled') == "no":
                        values[i] = False

    logger.info("values: %s" % values)
    for i in event_list:
        if values[i] != events[i]:
            return 1

    return 0 
Example #19
Source File: test_nova.py    From dwarf with Apache License 2.0 4 votes vote down vote up
def test_nova_servers(self):
        # Preload an image
        self.create_image(server1_image)

        self.exec_verify(['nova', 'boot', '--flavor', server1['flavor_id'],
                          '--image', server1['image_id'], server1['name']],
                         filename=cwd('nova_boot'))

        self.exec_verify(['nova', 'list'],
                         filename=cwd('nova_list.building'))

        libvirt.DOMAIN_STATE = libvirt.VIR_DOMAIN_RUNNING
        libvirt.IP_ADDRESS = server1['ip']
        time.sleep(3)

        # Should show the IP and status 'active'
        self.exec_verify(['nova', 'list'],
                         filename=cwd('nova_list'))

        self.exec_verify(['nova', 'show', server1['id']],
                         filename=cwd('nova_show'))

        self.exec_verify(['nova', 'console-log', server1['id']],
                         stdout='Test server console log\n')

        self.exec_verify(['nova', 'stop', server1['id']],
                         stdout='Request to stop server %s has been '
                         'accepted.\n' % server1['id'])

        # Should show status 'stopped'
        self.exec_verify(['nova', 'show', server1['id']],
                         filename=cwd('nova_show.stopped'))

        self.exec_verify(['nova', 'start', server1['id']],
                         stdout='Request to start server %s has been '
                         'accepted.\n' % server1['id'])

        # Should show status 'active'
        self.exec_verify(['nova', 'show', server1['id']],
                         filename=cwd('nova_show'))

        self.exec_verify(['nova', 'reboot', server1['id']],
                         stdout='Request to reboot server <Server: %s> has '
                         'been accepted.\n' % server1['name']) 
Example #20
Source File: resume.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def resume(params):
    """Resume domain

        Argument is a dictionary with two keys:
        {'logger': logger, 'guestname': guestname}

        logger -- an object of utils/log.py
        guestname -- same as the domain name

        Return 0 on SUCCESS or 1 on FAILURE
    """
    domname = params['guestname']
    logger = params['logger']

    # Resume domain
    conn = sharedmod.libvirtobj['conn']
    domobj = conn.lookupByName(domname)
    logger.info('resume domain')
    try:
        domobj.resume()
    except libvirtError as e:
        logger.error("API error message: %s, error code is %s"
                     % (e.get_error_message(), e.get_error_code()))
        logger.error("resume failed")
        return 1

    state = domobj.info()[0]
    expect_states = [libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_NOSTATE, libvirt.VIR_DOMAIN_BLOCKED]

    if state not in expect_states:
        logger.error('The domain state is not equal to "paused"')
        return 1

    mac = utils.get_dom_mac_addr(domname)
    logger.info("get ip by mac address")
    ip = utils.mac_to_ip(mac, 120)

    logger.info('ping guest')
    if not utils.do_ping(ip, 300):
        logger.error('Failed on ping guest, IP: ' + str(ip))
        return 1

    logger.info("PASS")
    return 0 
Example #21
Source File: disk_hotplug.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def disk_hotplug(params):
    """Loop attach/detach disk through xml on domain with all supported
       flags
    """
    logger = params['logger']
    guestname = params['guestname']
    imageformat = params['imageformat']
    hddriver = params['hddriver']
    xmlstr = params['xml']
    out = 0

    imagesize = int(params.get('imagesize', 1))
    diskpath = params.get('diskpath', '/var/lib/libvirt/images/attacheddisk')

    if create_image(diskpath, imagesize, imageformat, logger):
        logger.error("fail to create a image file")
        return 1

    conn = sharedmod.libvirtobj['conn']
    domobj = conn.lookupByName(guestname)

    state = domobj.info()[0]
    logger.debug("current guest status: %s" % state)
    if not (state == libvirt.VIR_DOMAIN_SHUTOFF or
            state == libvirt.VIR_DOMAIN_RUNNING):
        logger.error("guest not in shutoff or running state")
        return 1

    if hddriver == 'virtio':
        xmlstr = xmlstr.replace('DEV', 'vdb')
        target = 'vdb'
    elif hddriver == 'ide':
        xmlstr = xmlstr.replace('DEV', 'hdb')
        target = 'hdb'
    elif hddriver == 'scsi':
        xmlstr = xmlstr.replace('DEV', 'sdb')
        target = 'sdb'

    logger.debug("disk xml:\n%s" % xmlstr)

    disk_num1 = utils.dev_num(guestname, "disk")
    logger.debug("original disk number: %s" % disk_num1)

    for i in reversed(list(range(4))):
        attach_ret = attach_disk(domobj, guestname, state, xmlstr, i, target,
                                 disk_num1, logger)
        time.sleep(5)
        detach_ret = detach_disk(domobj, guestname, state, xmlstr, i, target,
                                 disk_num1, logger)
        time.sleep(5)
        ret = int(attach_ret) + int(detach_ret)
        out += ret

    if out:
        return 1
    else:
        return 0 
Example #22
Source File: virtual_machine.py    From MCVirt with GNU General Public License v2.0 4 votes vote down vote up
def duplicate(self, duplicate_vm_name, storage_backend=None, retain_mac=False):
        """Duplicates a VM, creating an identical machine, making a
           copy of the storage."""
        ArgumentValidator.validate_hostname(duplicate_vm_name)

        # Check the user has permission to create VMs
        self.po__get_registered_object('auth').assert_permission(PERMISSIONS.DUPLICATE_VM, self)

        # Ensure VM is registered locally
        self.ensureRegisteredLocally()

        # Ensure VM is unlocked
        self.ensureUnlocked()

        # Determine if VM is running
        if self._get_libvirt_domain_object().state()[0] == libvirt.VIR_DOMAIN_RUNNING:
            raise VmAlreadyStartedException('Can\'t duplicate running VM')

        # Ensure new VM name doesn't already exist
        if self.po__get_registered_object(
                'virtual_machine_factory').check_exists_by_name(duplicate_vm_name):
            raise VmAlreadyExistsException('VM already exists with name %s' % duplicate_vm_name)

        # Create new VM for clone, without hard disks
        virtual_machine_factory = self.po__get_registered_object('virtual_machine_factory')

        new_vm_object = virtual_machine_factory._create(duplicate_vm_name, self.get_cpu(),
                                                        self.get_ram(), [], [],
                                                        available_nodes=self.getAvailableNodes(),
                                                        node=self.getNode(),
                                                        storage_backend=storage_backend)

        network_adapter_factory = self.po__get_registered_object('network_adapter_factory')
        network_adapters = network_adapter_factory.getNetworkAdaptersByVirtualMachine(self)
        for network_adapter in network_adapters:
            network_adapter_factory.create(new_vm_object, network_adapter.get_network_object(),
                                           network_adapter.getMacAddress() if retain_mac else None)

        # Set current user as an owner of the new VM, so that they have permission
        # to perform functions on the VM
        self.po__get_registered_object('auth').copy_permissions(self, new_vm_object)

        # Clone the hard drives of the VM
        disk_objects = self.get_hard_drive_objects()
        for disk_object in disk_objects:
            disk_object.duplicate(new_vm_object, storage_backend=storage_backend)

        return new_vm_object