Package com.cloud.agent.api

Examples of com.cloud.agent.api.CreateVMSnapshotAnswer


        when(vmMock.getState()).thenReturn(State.Running);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);

        when(_vmSnapshotDao.findCurrentSnapshotByVmId(anyLong())).thenReturn(null);
        doReturn(new ArrayList<VolumeTO>()).when(_vmSnapshotMgr).getVolumeTOList(anyLong());
        doReturn(new CreateVMSnapshotAnswer(null,true,"")).when(_vmSnapshotMgr).sendToPool(anyLong(), any(CreateVMSnapshotCommand.class));
        doNothing().when(_vmSnapshotMgr).processAnswer(any(VMSnapshotVO.class),
                any(UserVmVO.class), any(Answer.class), anyLong());
        doReturn(true).when(_vmSnapshotMgr).vmSnapshotStateTransitTo(any(VMSnapshotVO.class),any(VMSnapshot.Event.class));
        _vmSnapshotMgr.createVmSnapshotInternal(vmMock, mock(VMSnapshotVO.class), 5L);
    }
View Full Code Here


        try {
            // check if VM snapshot already exists
            Set<VM> vmSnapshots = VM.getByNameLabel(conn, cmd.getTarget().getSnapshotName());
            if(vmSnapshots.size() > 0)
                return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
           
            // check if there is already a task for this VM snapshot
            Task task = null;
            Set<Task> tasks = Task.getByNameLabel(conn, "Async.VM.snapshot");
            tasks.addAll(Task.getByNameLabel(conn, "Async.VM.checkpoint"));
            for (Task taskItem : tasks) {
                if(taskItem.getOtherConfig(conn).containsKey("CS_VM_SNAPSHOT_KEY")){
                    String vmSnapshotTaskName = taskItem.getOtherConfig(conn).get("CS_VM_SNAPSHOT_KEY");
                    if(vmSnapshotTaskName != null && vmSnapshotTaskName.equals(cmd.getTarget().getSnapshotName())){
                        task = taskItem;
                    }
                }
            }
           
            // create a new task if there is no existing task for this VM snapshot
            if(task == null){
                try {
                    vm = getVM(conn, vmName);
                } catch (Exception e) {
                    if (!snapshotMemory) {
                        vm = createWorkingVM(conn, vmName, guestOSType, listVolumeTo);
                    }
                }
   
                if (vm == null) {
                    return new CreateVMSnapshotAnswer(cmd, false,
                            "Creating VM Snapshot Failed due to can not find vm: "
                                    + vmName);
                }
               
                // call Xenserver API
                if (!snapshotMemory) {
                    task = vm.snapshotAsync(conn, vmSnapshotName);
                } else {
                    Set<VBD> vbds = vm.getVBDs(conn);
                    Pool pool = Pool.getByUuid(conn, _host.pool);
                    for (VBD vbd: vbds){
                        VBD.Record vbdr = vbd.getRecord(conn);
                        if (vbdr.userdevice.equals("0")){
                            VDI vdi = vbdr.VDI;
                            SR sr = vdi.getSR(conn);
                            // store memory image on the same SR with ROOT volume
                            pool.setSuspendImageSR(conn, sr);
                        }
                    }
                    task = vm.checkpointAsync(conn, vmSnapshotName);
                }
                task.addToOtherConfig(conn, "CS_VM_SNAPSHOT_KEY", vmSnapshotName);
            }
           
            waitForTask(conn, task, 1000, timeout * 1000);
            checkForSuccess(conn, task);
            String result = task.getResult(conn);
           
            // extract VM snapshot ref from result
            String ref = result.substring("<value>".length(), result.length() - "</value>".length());
            vmSnapshot = Types.toVM(ref);
            try {
                Thread.sleep(5000);
            } catch (final InterruptedException ex) {

            }
            // calculate used capacity for this VM snapshot
            for (VolumeTO volumeTo : cmd.getVolumeTOs()){
                long size = getVMSnapshotChainSize(conn,volumeTo,cmd.getVmName());
                volumeTo.setChainSize(size);
            }
           
            success = true;
            return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
        } catch (Exception e) {
            String msg = "";
            if(e instanceof BadAsyncResult){
                String licenseKeyWord = "LICENCE_RESTRICTION";
                BadAsyncResult errorResult = (BadAsyncResult)e;
                if(errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)){
                    msg = licenseKeyWord;
                }
            }else{
                msg = e.getMessage();
            }
            s_logger.error("Creating VM Snapshot " + cmd.getTarget().getSnapshotName() + " failed due to: " + msg);
            return new CreateVMSnapshotAnswer(cmd, false, msg);
        } finally {
            try {
                if (!success) {
                    if (vmSnapshot != null) {
                        s_logger.debug("Delete exsisting VM Snapshot "
View Full Code Here

                    .getStockObject(VmwareManager.CONTEXT_STOCK_NAME);

            return mgr.getStorageManager().execute(this, cmd);
        } catch (Exception e) {
            e.printStackTrace();
            return new CreateVMSnapshotAnswer(cmd, false, "");
        }
    }
View Full Code Here

    public Answer createVmSnapshot(CreateVMSnapshotCommand cmd) {
        String vmName = cmd.getVmName();
        String vmSnapshotName = cmd.getTarget().getSnapshotName();

        s_logger.debug("Created snapshot " +vmSnapshotName+ " for vm " + vmName);
        return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
    }
View Full Code Here

        }
        return createVmSnapshotInternal(userVm, vmSnapshot, hostId);
    }

    protected VMSnapshot createVmSnapshotInternal(UserVmVO userVm, VMSnapshotVO vmSnapshot, Long hostId) {
        CreateVMSnapshotAnswer answer = null;
        try {
            GuestOSVO guestOS = _guestOSDao.findById(userVm.getGuestOSId());
           
            // prepare snapshotVolumeTos
            List<VolumeTO> volumeTOs = getVolumeTOList(userVm.getId());
           
            // prepare target snapshotTO and its parent snapshot (current snapshot)
            VMSnapshotTO current = null;
            VMSnapshotVO currentSnapshot = _vmSnapshotDao.findCurrentSnapshotByVmId(userVm.getId());
            if (currentSnapshot != null)
                current = getSnapshotWithParents(currentSnapshot);
            VMSnapshotTO target = new VMSnapshotTO(vmSnapshot.getId(),  vmSnapshot.getName(), vmSnapshot.getType(), null, vmSnapshot.getDescription(), false,
                    current);
            if (current == null)
                vmSnapshot.setParent(null);
            else
                vmSnapshot.setParent(current.getId());

            CreateVMSnapshotCommand ccmd = new CreateVMSnapshotCommand(userVm.getInstanceName(),target ,volumeTOs, guestOS.getDisplayName(),userVm.getState());
            ccmd.setWait(_wait);
           
            answer = (CreateVMSnapshotAnswer) sendToPool(hostId, ccmd);
            if (answer != null && answer.getResult()) {
                processAnswer(vmSnapshot, userVm, answer, hostId);
                s_logger.debug("Create vm snapshot " + vmSnapshot.getName() + " succeeded for vm: " + userVm.getInstanceName());
            }else{
               
                String errMsg = "Creating VM snapshot: " + vmSnapshot.getName() + " failed";
                if(answer != null && answer.getDetails() != null)
                    errMsg = errMsg + " due to " + answer.getDetails();
                s_logger.error(errMsg);
                vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed);
                throw new CloudRuntimeException(errMsg);
            }
            return vmSnapshot;
        } catch (Exception e) {
            if(e instanceof AgentUnavailableException){
                try {
                    vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed);
                } catch (NoTransitionException e1) {
                    s_logger.error("Cannot set vm snapshot state due to: " + e1.getMessage());
                }
            }
            String msg = e.getMessage();
            s_logger.error("Create vm snapshot " + vmSnapshot.getName() + " failed for vm: " + userVm.getInstanceName() + " due to " + msg);
            throw new CloudRuntimeException(msg);
        } finally{
            if(vmSnapshot.getState() == VMSnapshot.State.Allocated){
                s_logger.warn("Create vm snapshot " + vmSnapshot.getName() + " failed for vm: " + userVm.getInstanceName());
                _vmSnapshotDao.remove(vmSnapshot.getId());
            }
            if(vmSnapshot.getState() == VMSnapshot.State.Ready && answer != null){
                for (VolumeTO volumeTo : answer.getVolumeTOs()){
                    publishUsageEvent(EventTypes.EVENT_VM_SNAPSHOT_CREATE,vmSnapshot,userVm,volumeTo);
                }
            }
        }
    }
View Full Code Here

    protected void processAnswer(VMSnapshotVO vmSnapshot, UserVmVO  userVm, Answer as, Long hostId) {
        final Transaction txn = Transaction.currentTxn();
        try {
            txn.start();
            if (as instanceof CreateVMSnapshotAnswer) {
                CreateVMSnapshotAnswer answer = (CreateVMSnapshotAnswer) as;
                finalizeCreate(vmSnapshot, answer.getVolumeTOs());
                vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
            } else if (as instanceof RevertToVMSnapshotAnswer) {
                RevertToVMSnapshotAnswer answer = (RevertToVMSnapshotAnswer) as;
                finalizeRevert(vmSnapshot, answer.getVolumeTOs());
                vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
            } else if (as instanceof DeleteVMSnapshotAnswer) {
                DeleteVMSnapshotAnswer answer = (DeleteVMSnapshotAnswer) as;
                finalizeDelete(vmSnapshot, answer.getVolumeTOs());
                _vmSnapshotDao.remove(vmSnapshot.getId());
            }
            txn.commit();
        } catch (Exception e) {
            String errMsg = "Error while process answer: " + as.getClass() + " due to " + e.getMessage();
View Full Code Here

                vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
            }
            if (vmMo == null) {
                String msg = "Unable to find VM for CreateVMSnapshotCommand";
                s_logger.debug(msg);
                return new CreateVMSnapshotAnswer(cmd, false, msg);
            } else {
                if (vmMo.getSnapshotMor(vmSnapshotName) != null){
                    s_logger.debug("VM snapshot " + vmSnapshotName + " already exists");
                }else if (!vmMo.createSnapshot(vmSnapshotName, vmSnapshotDesc, snapshotMemory, true)) {
                    return new CreateVMSnapshotAnswer(cmd, false,
                            "Unable to create snapshot due to esxi internal failed");
                }
                // find VM disk file path after creating snapshot
                VirtualDisk[] vdisks = vmMo.getAllDiskDevice();
                for (int i = 0; i < vdisks.length; i ++){
                    List<Pair<String, ManagedObjectReference>> vmdkFiles = vmMo.getDiskDatastorePathChain(vdisks[i], false);
                    for(Pair<String, ManagedObjectReference> fileItem : vmdkFiles) {
                        String vmdkName = fileItem.first().split(" ")[1];
                        if (vmdkName.endsWith(".vmdk")){
                            vmdkName = vmdkName.substring(0, vmdkName.length() - (".vmdk").length());
                        }
                        if(vmdkName.contains("/")) {
                            vmdkName = vmdkName.substring(vmdkName.indexOf ("/") + 1,vmdkName.length());
                        }
                        String baseName = extractSnapshotBaseFileName(vmdkName);
                        mapNewDisk.put(baseName, vmdkName);
                    }
                }
                for (VolumeTO volumeTO : volumeTOs) {
                    String baseName = extractSnapshotBaseFileName(volumeTO.getPath());
                    String newPath = mapNewDisk.get(baseName);
                    // get volume's chain size for this VM snapshot, exclude current volume vdisk
                    long size = getVMSnapshotChainSize(context,hyperHost,baseName + "*.vmdk",
                            volumeTO.getPoolUuid(), newPath);

                    if(volumeTO.getType()== Volume.Type.ROOT){
                        // add memory snapshot size
                        size = size + getVMSnapshotChainSize(context,hyperHost,cmd.getVmName()+"*.vmsn",volumeTO.getPoolUuid(),null);
                    }

                    volumeTO.setChainSize(size);
                    volumeTO.setPath(newPath);
                }
                return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), volumeTOs);
            }
        } catch (Exception e) {
            String msg = e.getMessage();
            s_logger.error("failed to create snapshot for vm:" + vmName + " due to " + msg);
            try {
                if (vmMo.getSnapshotMor(vmSnapshotName) != null) {
                    vmMo.removeSnapshot(vmSnapshotName, false);
                }
            } catch (Exception e1) {
            }
            return new CreateVMSnapshotAnswer(cmd, false, e.getMessage());
        }
    }
View Full Code Here

                    .getStockObject(VmwareManager.CONTEXT_STOCK_NAME);

            return mgr.getStorageManager().execute(this, cmd);
        } catch (Exception e) {
            e.printStackTrace();
            return new CreateVMSnapshotAnswer(cmd, false, "");
        }
    }
View Full Code Here

        try {
            // check if VM snapshot already exists
            Set<VM> vmSnapshots = VM.getByNameLabel(conn, cmd.getTarget().getSnapshotName());
            if (vmSnapshots.size() > 0)
                return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());

            // check if there is already a task for this VM snapshot
            Task task = null;
            Set<Task> tasks = Task.getByNameLabel(conn, "Async.VM.snapshot");
            tasks.addAll(Task.getByNameLabel(conn, "Async.VM.checkpoint"));
            for (Task taskItem : tasks) {
                if (taskItem.getOtherConfig(conn).containsKey("CS_VM_SNAPSHOT_KEY")) {
                    String vmSnapshotTaskName = taskItem.getOtherConfig(conn).get("CS_VM_SNAPSHOT_KEY");
                    if (vmSnapshotTaskName != null && vmSnapshotTaskName.equals(cmd.getTarget().getSnapshotName())) {
                        task = taskItem;
                    }
                }
            }

            // create a new task if there is no existing task for this VM snapshot
            if (task == null) {
                try {
                    vm = getVM(conn, vmName);
                } catch (Exception e) {
                    if (!snapshotMemory) {
                        vm = createWorkingVM(conn, vmName, guestOSType, platformEmulator, listVolumeTo);
                    }
                }

                if (vm == null) {
                    return new CreateVMSnapshotAnswer(cmd, false, "Creating VM Snapshot Failed due to can not find vm: " + vmName);
                }

                // call Xenserver API
                if (!snapshotMemory) {
                    task = vm.snapshotAsync(conn, vmSnapshotName);
                } else {
                    Set<VBD> vbds = vm.getVBDs(conn);
                    Pool pool = Pool.getByUuid(conn, _host.pool);
                    for (VBD vbd : vbds) {
                        VBD.Record vbdr = vbd.getRecord(conn);
                        if (vbdr.userdevice.equals("0")) {
                            VDI vdi = vbdr.VDI;
                            SR sr = vdi.getSR(conn);
                            // store memory image on the same SR with ROOT volume
                            pool.setSuspendImageSR(conn, sr);
                        }
                    }
                    task = vm.checkpointAsync(conn, vmSnapshotName);
                }
                task.addToOtherConfig(conn, "CS_VM_SNAPSHOT_KEY", vmSnapshotName);
            }

            waitForTask(conn, task, 1000, timeout * 1000);
            checkForSuccess(conn, task);
            String result = task.getResult(conn);

            // extract VM snapshot ref from result
            String ref = result.substring("<value>".length(), result.length() - "</value>".length());
            vmSnapshot = Types.toVM(ref);
            try {
                Thread.sleep(5000);
            } catch (final InterruptedException ex) {

            }
            // calculate used capacity for this VM snapshot
            for (VolumeObjectTO volumeTo : cmd.getVolumeTOs()) {
                long size = getVMSnapshotChainSize(conn, volumeTo, cmd.getVmName());
                volumeTo.setSize(size);
            }

            success = true;
            return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
        } catch (Exception e) {
            String msg = "";
            if (e instanceof Types.BadAsyncResult) {
                String licenseKeyWord = "LICENCE_RESTRICTION";
                Types.BadAsyncResult errorResult = (Types.BadAsyncResult)e;
                if (errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)) {
                    msg = licenseKeyWord;
                }
            } else {
                msg = e.getMessage();
            }
            s_logger.error("Creating VM Snapshot " + cmd.getTarget().getSnapshotName() + " failed due to: " + msg);
            return new CreateVMSnapshotAnswer(cmd, false, msg);
        } finally {
            try {
                if (!success) {
                    if (vmSnapshot != null) {
                        s_logger.debug("Delete exsisting VM Snapshot " + vmSnapshotName + " after making VolumeTO failed");
View Full Code Here

            VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);

            return mgr.getStorageManager().execute(this, cmd);
        } catch (Exception e) {
            e.printStackTrace();
            return new CreateVMSnapshotAnswer(cmd, false, "");
        }
    }
View Full Code Here

TOP

Related Classes of com.cloud.agent.api.CreateVMSnapshotAnswer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.