예제 #1
0
def create_snapshot(module, vm_service, snapshots_service, connection):
    changed = False
    snapshot = get_entity(
        snapshots_service.snapshot_service(module.params['snapshot_id']))
    if snapshot is None:
        if not module.check_mode:
            disk_attachments_id = set(
                get_disk_attachment(
                    disk,
                    vm_service.disk_attachments_service().list(),
                    connection).id for disk in module.params.get(
                        'disks')) if module.params.get('disks') else None

            snapshot = snapshots_service.add(
                otypes.Snapshot(
                    description=module.params.get('description'),
                    persist_memorystate=module.params.get('use_memory'),
                    disk_attachments=[
                        otypes.DiskAttachment(disk=otypes.Disk(id=da_id))
                        for da_id in disk_attachments_id
                    ] if disk_attachments_id else None))
        changed = True
        wait(
            service=snapshots_service.snapshot_service(snapshot.id),
            condition=lambda snap: snap.snapshot_status == otypes.
            SnapshotStatus.OK,
            wait=module.params['wait'],
            timeout=module.params['timeout'],
        )
    return {
        'changed': changed,
        'id': snapshot.id,
        'snapshot': get_dict_of_struct(snapshot),
    }
예제 #2
0
def create_snapshot(snapshots_service, description):
    return snapshots_service.add(
        types.Snapshot(
            description=description,
            persist_memorystate=False,
        ),
    )
예제 #3
0
    def clone_vm_from_snapshot(vms_service, snapshot, vm_name, cluster_name, logger):
        logger.info('Cloning VM from snapshot...')
        cloned_vm = vms_service.add(
            vm=otypes.Vm(
                name=vm_name,
                snapshots=[
                    otypes.Snapshot(
                        id=snapshot.id
                    )
                ],
                cluster=otypes.Cluster(
                    name=cluster_name
                )
            )
        )

        OvirtBackup.wait(
            service=vms_service.vm_service(cloned_vm.id),
            condition=lambda vm: vm.status == otypes.VmStatus.DOWN,
            logger=logger,
            wait=True,
            timeout=180000
        )
        logger.info('  --> done')
        return cloned_vm
def preview_snapshot(module, vm_service, snapshots_service):
    changed = False
    # Get the snapshot:
    snapshot = snapshots_service.snapshot_service(
        module.params['snapshot_id']).get()

    if snapshot is None:
        # Create snapshot:
        if not module.check_mode:
            snapshot = create_snapshot(module, snapshots_service)
        changed = True

    if snapshot.snapshot_status != otypes.SnapshotStatus.IN_PREVIEW:
        if not module.check_mode:
            vm_service.preview_snapshot(
                snapshot=otypes.Snapshot(id=snapshot.id),
                restore_memory=None,
                disks=None,
            )
        changed = True

    # Wait for the disk to be detached:
    if changed:
        wait(
            snapshots_service.snapshot_service(snapshot.id),
            lambda snapshot: snapshot.snapshot_status == otypes.SnapshotStatus.
            IN_PREVIEW,
        )
    return {
        'changed': changed,
        'id': snapshot.id if snapshot else None,
        'snapshot': get_dict_of_struct(snapshot),
    }
def create_snapshot(description, image_id, disk_id, vm_service):
    """
    Creates a new snapshot for the specified disk_id.
    To ensure consistency with the uploaded chain, the sepcified
    image_id will be used for the created image.
    """
    # Locate the service that manages the snapshots of the virtual machine:
    snapshots_service = vm_service.snapshots_service()

    # Add the new snapshot:
    snapshot = snapshots_service.add(
        types.Snapshot(description=description,
                       disk_attachments=[
                           types.DiskAttachment(
                               disk=types.Disk(id=disk_id, image_id=image_id))
                       ]), )

    # 'Waiting for Snapshot creation to finish'
    snapshot_service = snapshots_service.snapshot_service(snapshot.id)
    while True:
        time.sleep(5)
        snapshot = snapshot_service.get()
        if snapshot.snapshot_status == types.SnapshotStatus.OK:
            break

    return snapshot
def create_snapshot(module, vm_service, snapshots_service):
    changed = False
    # Get the snapshot:
    snapshot = snapshots_service.snapshot_service(
        module.params['snapshot_id']).get()

    # If snapshot exists, check if it should be updated:
    if snapshot:
        if snapshot.snapshot_status != otypes.SnapshotStatus.IN_PREVIEW:
            if not module.check_mode:
                vm_service.commit_snapshot()
            changed = True
    else:
        # Create snapshot of VM:
        if not module.check_mode:
            snapshot = snapshots_service.add(
                otypes.Snapshot(
                    description=module.params.get('description'), ))
        changed = True

    # Wait for the snapshot to be created:
    if changed:
        wait(
            snapshots_service.snapshot_service(snapshot.id),
            lambda snapshot: snapshot.snapshot_status == otypes.SnapshotStatus.
            OK,
        )
    return {
        'changed': changed,
        'id': snapshot.id,
        'snapshot': get_dict_of_struct(snapshot),
    }
예제 #7
0
def test_add_snapshot_for_backup(api_v4):
    engine = api_v4.system_service()

    vm2_disk_attachments_service = test_utils.get_disk_attachments_service(
        engine, VM2_NAME)
    disk = vm2_disk_attachments_service.list()[0]

    backup_snapshot_params = types.Snapshot(
        description=SNAPSHOT_FOR_BACKUP_VM,
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])

    vm2_snapshots_service = test_utils.get_vm_snapshots_service(
        engine, VM2_NAME)

    correlation_id = uuid.uuid4()
    with test_utils.TestEvent(engine, [45, 68]):
        # USER_CREATE_SNAPSHOT(41) event
        # USER_CREATE_SNAPSHOT_FINISHED_SUCCESS(68) event
        vm2_snapshots_service.add(backup_snapshot_params,
                                  query={'correlation_id': correlation_id})

        testlib.assert_true_within_long(
            lambda: test_utils.all_jobs_finished(engine, correlation_id))
        testlib.assert_true_within_long(
            lambda: vm2_snapshots_service.list()[-1].snapshot_status == types.
            SnapshotStatus.OK, )
예제 #8
0
def create_snapshot(module, vm_service, snapshots_service):
    changed = False
    snapshot = get_entity(
        snapshots_service.snapshot_service(module.params['snapshot_id'])
    )
    if snapshot is None:
        if not module.check_mode:
            snapshot = snapshots_service.add(
                otypes.Snapshot(
                    description=module.params.get('description'),
                    persist_memorystate=module.params.get('use_memory'),
                )
            )
        changed = True
        wait(
            service=snapshots_service.snapshot_service(snapshot.id),
            condition=lambda snap: snap.snapshot_status == otypes.SnapshotStatus.OK,
            wait=module.params['wait'],
            timeout=module.params['timeout'],
        )
    return {
        'changed': changed,
        'id': snapshot.id,
        'snapshot': get_dict_of_struct(snapshot),
    }
예제 #9
0
def snapshot_cold_merge(engine_api):
    engine = engine_api.system_service()
    vm1_snapshots_service = test_utils.get_vm_snapshots_service(
        engine, VM1_NAME)
    if vm1_snapshots_service is None:
        pytest.skip('Glance is not available')

    disk = engine.disks_service().list(
        search='name={} and vm_names={}'.format(DISK1_NAME, VM1_NAME))[0]

    dead_snap1_params = types.Snapshot(
        description=SNAPSHOT_DESC_1,
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])
    correlation_id = uuid.uuid4()

    vm1_snapshots_service.add(dead_snap1_params,
                              query={'correlation_id': correlation_id})

    assertions.assert_true_within_long(
        lambda: test_utils.all_jobs_finished(engine, correlation_id))
    assertions.assert_true_within_long(lambda: vm1_snapshots_service.list()[
        -1].snapshot_status == types.SnapshotStatus.OK)

    dead_snap2_params = types.Snapshot(
        description=SNAPSHOT_DESC_2,
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])
    correlation_id_snap2 = uuid.uuid4()

    vm1_snapshots_service.add(dead_snap2_params,
                              query={'correlation_id': correlation_id_snap2})

    assertions.assert_true_within_long(
        lambda: test_utils.all_jobs_finished(engine, correlation_id_snap2))
    assertions.assert_true_within_long(lambda: vm1_snapshots_service.list()[
        -1].snapshot_status == types.SnapshotStatus.OK)

    snapshot = vm1_snapshots_service.list()[-2]
    vm1_snapshots_service.snapshot_service(snapshot.id).remove()

    assertions.assert_true_within_long(
        lambda: len(vm1_snapshots_service.list()) == 2)
    assertions.assert_true_within_long(lambda: vm1_snapshots_service.list()[
        -1].snapshot_status == types.SnapshotStatus.OK)
예제 #10
0
def create_snap(idvm):
 vm_service = connection.service("vms")
 snapshots_service = vm_service.vm_service(idvm).snapshots_service()
 snapshots_service.add(types.Snapshot(description=snapname, persist_memorystate=False))
 snapid = get_snap_id(vmid)
 status = get_snap_status(idvm,snapid)
 while str(status) == "locked":
    time.sleep(10)
    print "Esperando a que termine el snapshot.."
    status = get_snap_status(idvm,snapid)
예제 #11
0
 def snapshot(self, name, base, revert=False, delete=False, listing=False):
     vmsearch = self.vms_service.list(search='name=%s' % base)
     if not vmsearch:
         common.pprint("VM %s not found" % base, color='red')
         return {'result': 'failure', 'reason': "VM %s not found" % base}
     vm = vmsearch[0]
     snapshots_service = self.vms_service.vm_service(
         vm.id).snapshots_service()
     snapshots_service.add(types.Snapshot(description=name))
     return
예제 #12
0
def clone_snapshot_to_vm(vms_service, vm, snap):
    counter = 0
    snapshots_service = vms_service.vm_service(vm.id).snapshots_service()
    new_vm_name = '{}_{}_{}'.format(vm.name, VM_MIDDLE,
                                    datetime.now().strftime('%Y%m%d_%H%M%S'))

    # It can happen, that the snapshot state gives ok,
    # but the snapshot is still not free for cloning/deleting.
    # For this case we have to wait a bit more.
    sleep(120)

    check_snapshot(snap, snapshots_service, True)

    logger.info("[{}] Create VM clone from snapshot...".format(vm.name))

    try:
        vm_clone = vms_service.add(
            vm=types.Vm(name=new_vm_name,
                        snapshots=[types.Snapshot(id=snap.id)],
                        cluster=types.Cluster(name=CLUSTER)))
    except sdk.Error as oerr:
        logger.error(oerr)
        send_mail(oerr)

        return None

    cloned_vm_service = vms_service.vm_service(vm_clone.id)
    created = True

    # check if cloned vm is down,
    # what means that the cloning process has been completed
    while vm_clone.status != types.VmStatus.DOWN:
        if counter >= MAX_OPERATION_TIME:
            logger.error("[{}] Creating VM clone from snapshot failed".format(
                vm.name))
            send_mail("Creating VM clone from snapshot failed!\n" +
                      "No backup for: <b>{}</b> at: <b>{}</b>".format(
                          vm.name,
                          datetime.now().strftime('%H:%M:%S')))
            created = None
            break

        sleep(5)
        vm_clone = cloned_vm_service.get()
        counter + 5

    if created:
        logger.info("[{}] Creating VM clone from snapshot completed!".format(
            vm.name))
        # is allways good to sleep a bit :)
        sleep(2)

        return vm_clone
    else:
        return None
예제 #13
0
def snapshot_live_merge(api):
    disk = api.vms.get(VM0_NAME).disks.list()[0]
    disk_id = disk.id
    disk_name = disk.name

    live_snap1_params = types.Snapshot(
        description='live_snap1',
        persist_memorystate=True,
        disks=types.Disks(disk=[
            types.Disk(id=disk_id, ),
        ], ),
    )
    api.vms.get(VM0_NAME).snapshots.add(live_snap1_params)
    testlib.assert_true_within_short(lambda: api.vms.get(VM0_NAME).snapshots.
                                     list()[-1].snapshot_status == 'ok')

    live_snap2_params = types.Snapshot(
        description='live_snap2',
        persist_memorystate=True,
        disks=types.Disks(disk=[
            types.Disk(id=disk_id, ),
        ], ),
    )
    api.vms.get(VM0_NAME).snapshots.add(live_snap2_params)
    for i, _ in enumerate(api.vms.get(VM0_NAME).snapshots.list()):
        testlib.assert_true_within_short(lambda: (api.vms.get(
            VM0_NAME).snapshots.list()[i].snapshot_status == 'ok'))

    api.vms.get(VM0_NAME).snapshots.list()[-2].delete()

    testlib.assert_true_within_long(
        lambda: len(api.vms.get(VM0_NAME).snapshots.list()) == 2, )

    for i, _ in enumerate(api.vms.get(VM0_NAME).snapshots.list()):
        testlib.assert_true_within_long(
            lambda: (api.vms.get(VM0_NAME).snapshots.list()[i].snapshot_status
                     == 'ok'), )
    testlib.assert_true_within_short(
        lambda: api.vms.get(VM0_NAME).status.state == 'up')

    testlib.assert_true_within_long(lambda: api.vms.get(VM0_NAME).disks.get(
        disk_name).status.state == 'ok')
예제 #14
0
def snapshot_merge(api):
    engine = api.system_service()
    vm0_snapshots_service = test_utils.get_vm_snapshots_service(
        engine, VM0_NAME)

    disk = engine.disks_service().list(
        search='name={}'.format(GLANCE_DISK_NAME))[0]

    dead_snap1_params = types.Snapshot(
        description='dead_snap1',
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])

    correlation_id = uuid.uuid4()
    vm0_snapshots_service.add(dead_snap1_params,
                              query={'correlation_id': correlation_id})
    testlib.assert_true_within_short(
        lambda: test_utils.all_jobs_finished(engine, correlation_id))
    testlib.assert_true_within_short(lambda: vm0_snapshots_service.list()[
        -1].snapshot_status == types.SnapshotStatus.OK)

    dead_snap2_params = types.Snapshot(
        description='dead_snap2',
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])

    correlation_id_snap2 = uuid.uuid4()

    vm0_snapshots_service.add(dead_snap2_params,
                              query={'correlation_id': correlation_id_snap2})
    testlib.assert_true_within_short(
        lambda: test_utils.all_jobs_finished(engine, correlation_id_snap2))
    testlib.assert_true_within_short(lambda: vm0_snapshots_service.list()[
        -1].snapshot_status == types.SnapshotStatus.OK)

    snapshot = vm0_snapshots_service.list()[-2]
    vm0_snapshots_service.snapshot_service(snapshot.id).remove()
    testlib.assert_true_within_short(
        lambda: (len(vm0_snapshots_service.list()) == 2) and
        (vm0_snapshots_service.list()[-1].snapshot_status == types.
         SnapshotStatus.OK), )
예제 #15
0
def create_snap(idvm):
 vm_service = connection.service("vms")
 snapshots_service = vm_service.vm_service(idvm).snapshots_service()
 snapshots_service.add(types.Snapshot(description=snapname, persist_memorystate=False))
 snapid = get_snap_id(vmid)
 status = get_snap_status(idvm,snapid)
 printf.INFO("Trying to create snapshot of VM: " + idvm)
 while str(status) == "locked":
    time.sleep(10)
    printf.INFO("Waiting until snapshot creation ends")
    status = get_snap_status(idvm,snapid)
 printf.OK("Snapshot created")
예제 #16
0
 def create_snap(self,vmid,snapname,my_disk):
  vm_service = self.connection.service("vms")
  snapshots_service = vm_service.vm_service(vmid).snapshots_service()
  snapshots_service.add(types.Snapshot(description=snapname,persist_memorystate=False, disk_attachments=[ types.DiskAttachment( disk=types.Disk( id=my_disk)) ]))
  snapid = self.get_snap_id(vmid)
  status = self.get_snap_status(vmid,snapid)
  printf.INFO("Trying to create snapshot of VM: " + vmid)
  while str(status) == "locked":
    time.sleep(10)
    printf.INFO("Waiting until snapshot creation ends")
    status = self.get_snap_status(vmid,snapid)
  printf.OK("Snapshot created")
예제 #17
0
    def create_snapshot(self, vm):
        # Locate the service that manages the snapshots of the virtual machine:
        vms_service = self.connection.system_service().vms_service()
        snapshots_service = vms_service.vm_service(vm.id).snapshots_service()

        vm = vms_service.vm_service(vm.id).get()

        name = vm.name
        result = snapshots_service.add(
            types.Snapshot(
                description='Snapshot to backup {} taken at {}'.format(
                    name, datetime.datetime.now()), ), )
        return result
예제 #18
0
def snapshot_cold_merge(api):
    engine = api.system_service()
    vm_service = test_utils.get_vm_service(engine, VM1_NAME)

    if vm_service is None:
        raise SkipTest('Glance is not available')

    snapshots_service = vm_service.snapshots_service()
    disk = engine.disks_service().list(search=DISK1_NAME)[0]

    dead_snap1_params = types.Snapshot(
        description=SNAPSHOT_DESC_1,
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])

    snapshots_service.add(dead_snap1_params)

    testlib.assert_true_within_long(lambda: snapshots_service.list()[-1].
                                    snapshot_status == types.SnapshotStatus.OK)

    dead_snap2_params = types.Snapshot(
        description=SNAPSHOT_DESC_2,
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])

    snapshots_service.add(dead_snap2_params)

    testlib.assert_true_within_long(lambda: snapshots_service.list()[-1].
                                    snapshot_status == types.SnapshotStatus.OK)

    snapshot = snapshots_service.list()[-2]
    snapshots_service.snapshot_service(snapshot.id).remove()

    testlib.assert_true_within_long(
        lambda: (len(snapshots_service.list()) == 2) and
        (snapshots_service.list()[-1].snapshot_status ==
         (types.SnapshotStatus.OK)), )
예제 #19
0
 def create_snapshot(snapshots_service, name, use_memory, logger):
     logger.info('Creating snapshot...')
     snapshot = snapshots_service.add(
         otypes.Snapshot(
             description=name,
             persist_memorystate=use_memory
         )
     )
     OvirtBackup.wait(
         service=snapshots_service.snapshot_service(snapshot.id),
         condition=lambda snap: snap.snapshot_status == otypes.SnapshotStatus.OK,
         logger=logger,
     )
     logger.info('  --> done')
     return snapshot
def add_snapshot_for_backup(api):
    engine = api.system_service()

    vm2_disk_attachments_service = test_utils.get_disk_attachments_service(
        engine, VM2_NAME)
    disk = vm2_disk_attachments_service.list()[0]

    backup_snapshot_params = types.Snapshot(
        description=SNAPSHOT_FOR_BACKUP_VM,
        persist_memorystate=False,
        disk_attachments=[types.DiskAttachment(disk=types.Disk(id=disk.id))])

    vm2_snapshots_service = test_utils.get_vm_snapshots_service(
        engine, VM2_NAME)
    vm2_snapshots_service.add(backup_snapshot_params)
예제 #21
0
def attach_snapshot_to_backup_vm(api):
    engine = api.system_service()
    vm2_snapshots_service = (test_utils.get_vm_snapshots_service(
        engine, VM2_NAME))
    vm2_disk_attachments_service = (test_utils.get_disk_attachments_service(
        engine, VM2_NAME))
    vm2_disk = vm2_disk_attachments_service.list()[0]
    disk_attachments_service = (test_utils.get_disk_attachments_service(
        engine, BACKUP_VM_NAME))

    disk_attachments_service.add(
        types.DiskAttachment(disk=types.Disk(
            id=vm2_disk.id,
            snapshot=types.Snapshot(id=vm2_snapshots_service.list()[-1].id)),
                             interface=types.DiskInterface.VIRTIO_SCSI,
                             bootable=False,
                             active=True))
    nt.assert_true(len(disk_attachments_service.list()) > 0)
예제 #22
0
    def _backup_snapshot_disks(self, snapshot_service, backup_vm_date_dir):
        disks_service = snapshot_service.disks_service()
        snapshot = snapshot_service.get()

        attachments_service = self._agent_vm_service.disk_attachments_service()
        for snapshot_disk in disks_service.list():
            attachment = attachments_service.add(
                attachment=types.DiskAttachment(
                    disk=types.Disk(id=snapshot_disk.id,
                                    snapshot=types.Snapshot(id=snapshot.id)),
                    active=True,
                    bootable=False,
                    interface=types.DiskInterface.VIRTIO))

            logging.info('Attaching disk {}'.format(attachment.disk.id))

            with AutoAttachmentService(attachments_service, attachment):
                self._copy_disk(attachment, backup_vm_date_dir)
예제 #23
0
def create_snap(vmid, snapname):
    """
    Create a snapshot for the specified VM
    """
    vm_service = connection.service("vms")
    snapshots_service = vm_service.vm_service(vmid).snapshots_service()
    snapshots_service.add(
        types.Snapshot(description=snapname, persist_memorystate=False))
    snapid = get_snap_id(vmid)
    status = get_snap_status(vmid, snapid)

    while str(status) == "locked":
        time.sleep(10)
        status = get_snap_status(vmid, snapid)
        printf.DEBUG(args.debug,
                     "Snapshot Creation Status (create_snap): " + str(status))

    return str(status)
예제 #24
0
def make_snapshot_with_memory(api):
    engine = api.system_service()
    vm_service = test_utils.get_vm_service(engine, VM0_NAME)
    disks_service = engine.disks_service()
    vm_disks_service = \
        test_utils.get_disk_attachments_service(engine, VM0_NAME)
    vm_disks = [
        disks_service.disk_service(attachment.disk.id).get()
        for attachment in vm_disks_service.list()
    ]
    disk_attachments = [
        types.DiskAttachment(disk=types.Disk(id=disk.id)) for disk in vm_disks
        if disk.storage_type != types.DiskStorageType.LUN
    ]
    snapshots_service = vm_service.snapshots_service()
    snapshot_params = types.Snapshot(description=SNAPSHOT_DESC_MEM,
                                     persist_memorystate=True,
                                     disk_attachments=disk_attachments)
    snapshots_service.add(snapshot_params)
예제 #25
0
def test_attach_snapshot_to_backup_vm(api_v4):
    engine = api_v4.system_service()
    vm2_snapshots_service = test_utils.get_vm_snapshots_service(
        engine, VM2_NAME)
    vm2_disk_attachments_service = test_utils.get_disk_attachments_service(
        engine, VM2_NAME)
    vm2_disk = vm2_disk_attachments_service.list()[0]
    disk_attachments_service = test_utils.get_disk_attachments_service(
        engine, BACKUP_VM_NAME)

    with test_utils.TestEvent(engine, 2016):  # USER_ATTACH_DISK_TO_VM event
        disk_attachments_service.add(
            types.DiskAttachment(disk=types.Disk(
                id=vm2_disk.id,
                snapshot=types.Snapshot(
                    id=vm2_snapshots_service.list()[-1].id)),
                                 interface=types.DiskInterface.VIRTIO_SCSI,
                                 bootable=False,
                                 active=True))
        assert len(disk_attachments_service.list()) > 0
예제 #26
0
def clone_snapshot_to_vm(cluster, vm_clone_name, vms_service, snapshot):
    logger.info("Clone into VM (%s) started ..." % vm_clone_name)

    try:
        cloned_vm = vms_service.add(
            vm=types.Vm(name=vm_clone_name,
                        snapshots=[types.Snapshot(id=snapshot.id)],
                        cluster=types.Cluster(name=cluster)))

        cloned_vm_service = vms_service.vm_service(cloned_vm.id)

        while True:
            time.sleep(5)
            cloned_vm = cloned_vm_service.get()
            if cloned_vm.status == types.VmStatus.DOWN:
                break
    except Exception as e:
        logger.info("Can't clone snapshot to VM: %s", vm_clone_name)
        logger.info("DEBUG: %s", e)

    logger.info("Snapshot cloned ...")
예제 #27
0
def create_snapshot(vms_service, vm):
    logger.info('[{}] Create snapshot...'.format(vm.name))
    snapshots_service = vms_service.vm_service(vm.id).snapshots_service()

    # when there is an old snapshot,
    # we will delete them
    snap = check_snapshot(None, snapshots_service, True)

    if snap is not None:
        logger.info(
            '[{}] Old snapshot found, wait for deleting them...'.format(
                vm.name))

        delete_snapshot(snapshots_service, snap, vm.name, True)

    sleep(120)

    # create a new snapshot
    # fail creating a snapshot should not stop the script from working
    try:
        snap = snapshots_service.add(
            types.Snapshot(
                description='snapshot for backup',
                persist_memorystate=RAM_STATE,
            ), )
    except sdk.Error as oerr:
        logger.error(oerr)
        send_mail(oerr)

        return None

    # check the snapshot again
    check_snapshot(snap, snapshots_service, True)

    if snap is not None:
        logger.info('[{}] Creating snapshot done!'.format(vm.name))
        return snap
    else:
        logger.error('[{}] Creating snapshot failed!'.format(vm.name))
        return None
예제 #28
0
    def run(self):
        backup_time = datetime.now()

        backup_vm_dir = os.path.join(self._base_backup_dir, self._data_vm_name)
        backup_vm_date_dir = os.path.join(backup_vm_dir,
                                          backup_time.strftime('%Y%m%d%H%M'))

        os.makedirs(backup_vm_date_dir)

        try:
            self._save_ovf(self._data_vm_service.get(all_content=True),
                           backup_vm_date_dir)
        except AttributeError:
            pass

        snapshots_service = self._data_vm_service.snapshots_service()
        snapshot = snapshots_service.add(snapshot=types.Snapshot(
            description='Backup {}'.format(str(backup_time)),
            persist_memorystate=False))

        logging.info("Sent request to create snapshot '{}' ({})".format(
            snapshot.description, snapshot.id))

        try:
            with AutoSnapshotService(snapshots_service,
                                     snapshot) as snapshot_service:
                self._migrate_agent_vm()
                self._backup_snapshot_disks(snapshot_service,
                                            backup_vm_date_dir)
            self._remove_old_backups(backup_vm_dir)
            logging.info("Backup VM '{}' finished".format(self._data_vm_name))
        except (sdk.Error, BackupError) as err:
            logging.exception(err)
            logging.info(
                "Backup VM '{}' failed! Current backup directory will be removed"
                .format(self._data_vm_name))
            self._remove_dir(backup_vm_date_dir)
            raise
예제 #29
0
    def snapshot(self, snapshot_name='my_snapshot', timeout=300):
        """
        Create a snapshot to VM.

        :param snapshot_name: 'my_snapshot' is default snapshot name.
        :param timeout: Time out
        """
        end_time = time.time() + timeout
        snap_params = types.Snapshot(description=snapshot_name,
                                     vm=self.instance)
        logging.info('Creating a snapshot %s for VM %s' %
                     (snapshot_name, self.name))
        self.instance.snapshots.add(snap_params)
        logging.info('Waiting for snapshot creation to finish')
        vm_snapsnop = False
        while time.time() < end_time:
            if self.state() != 'image_locked':
                vm_snapsnop = True
                break
            time.sleep(1)
        if not vm_snapsnop:
            raise WaitVMStateTimeoutError("SNAPSHOT", self.state())
        logging.info('Snapshot was created successfully')
예제 #30
0
    def _backup_snapshot_disks(self, snapshot_service, backup_vm_date_dir):
        disks_service = snapshot_service.disks_service()
        snapshot = snapshot_service.get()

        attachments_service = self._agent_vm_service.disk_attachments_service()
        for snapshot_disk in disks_service.list():
            attachment = attachments_service.add(
                attachment=types.DiskAttachment(
                    disk=types.Disk(id=snapshot_disk.id,
                                    snapshot=types.Snapshot(id=snapshot.id)),
                    active=True,
                    bootable=False,
                    interface=types.DiskInterface.VIRTIO))
            image_id = snapshot_disk.image_id
            image_size = snapshot_disk.provisioned_size
            image_description = snapshot_disk.description if snapshot_disk.description else 'None'
            logging.info('Attach disk {}'.format(attachment.disk.id))

            with AutoAttachmentService(attachments_service, attachment):
                self._copy_disk(attachment,
                                directory=backup_vm_date_dir,
                                image_id=image_id,
                                image_size=image_size,
                                image_description=image_description)