Package com.cloud.agent.api.to

Examples of com.cloud.agent.api.to.DataTO


        }
        return file.length();
    }

    protected Answer copyFromNfsToS3(CopyCommand cmd) {
        final DataTO srcData = cmd.getSrcTO();
        final DataTO destData = cmd.getDestTO();
        DataStoreTO srcDataStore = srcData.getDataStore();
        NfsTO srcStore = (NfsTO) srcDataStore;
        DataStoreTO destDataStore = destData.getDataStore();

        final S3TO s3 = (S3TO) destDataStore;

        try {
            final String templatePath = determineStorageTemplatePath(srcStore.getUrl(), srcData.getPath());

            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Found " + srcData.getObjectType() + " from directory " + templatePath
                        + " to upload to S3.");
            }

            final String bucket = s3.getBucketName();
            File srcFile = _storage.getFile(templatePath);
            // guard the case where templatePath does not have file extension, since we are not completely sure
            // about hypervisor, so we check each extension
            if (!srcFile.exists()) {
                srcFile = _storage.getFile(templatePath + ".qcow2");
                if (!srcFile.exists()) {
                    srcFile = _storage.getFile(templatePath + ".vhd");
                    if (!srcFile.exists()) {
                        srcFile = _storage.getFile(templatePath + ".ova");
                        if (!srcFile.exists()) {
                            return new CopyCmdAnswer("Can't find src file:" + templatePath);
                        }
                    }
                }
            }

            long srcSize = srcFile.length();
            ImageFormat format = this.getTemplateFormat(srcFile.getName());
            String key = destData.getPath() + S3Utils.SEPARATOR + srcFile.getName();
            if (!s3.getSingleUpload(srcSize)){
                mputFile(s3, srcFile, bucket, key);
            } else{
                putFile(s3, srcFile, bucket, key);
            }

            DataTO retObj = null;
            if (destData.getObjectType() == DataObjectType.TEMPLATE) {
                TemplateObjectTO newTemplate = new TemplateObjectTO();
                newTemplate.setPath(key);
                newTemplate.setSize(getVirtualSize(srcFile, format));
                newTemplate.setPhysicalSize(srcFile.length());
View Full Code Here


    private String determineSnapshotLockId(final Long accountId, final Long volumeId) {
        return join("_", "SNAPSHOT", accountId, volumeId);
    }

    protected Answer deleteSnapshot(final DeleteCommand cmd) {
        DataTO obj = cmd.getData();
        DataStoreTO dstore = obj.getDataStore();
        if (dstore instanceof NfsTO) {
            NfsTO nfs = (NfsTO) dstore;
            String parent = getRootDir(nfs.getUrl());
            if (!parent.endsWith(File.separator)) {
                parent += File.separator;
            }
            String snapshotPath = obj.getPath();
            if (snapshotPath.startsWith(File.separator)) {
                snapshotPath = snapshotPath.substring(1);
            }
            // check if the passed snapshot path is a directory or not. For ImageCache, path is stored as a directory instead of
            // snapshot file name. If so, since backupSnapshot process has already deleted snapshot in cache, so we just do nothing
            // and return true.
            String fullSnapPath = parent + snapshotPath;
            File snapDir = new File(fullSnapPath);
            if (snapDir.exists() && snapDir.isDirectory()) {
                s_logger.debug("snapshot path " + snapshotPath + " is a directory, already deleted during backup snapshot, so no need to delete");
                return new Answer(cmd, true, null);
            }
            // passed snapshot path is a snapshot file path, then get snapshot directory first
            int index = snapshotPath.lastIndexOf("/");
            String snapshotName = snapshotPath.substring(index + 1);
            snapshotPath = snapshotPath.substring(0, index);
            String absoluteSnapshotPath = parent + snapshotPath;
            // check if snapshot directory exists
            File snapshotDir = new File(absoluteSnapshotPath);
            String details = null;
            if (!snapshotDir.exists()) {
                details = "snapshot directory " + snapshotDir.getName() + " doesn't exist";
                s_logger.debug(details);
                return new Answer(cmd, false, details);
            }
            // delete snapshot in the directory if exists
            String lPath = absoluteSnapshotPath + "/*" + snapshotName + "*";
            String result = deleteLocalFile(lPath);
            if (result != null) {
                details = "failed to delete snapshot " + lPath + " , err=" + result;
                s_logger.warn(details);
                return new Answer(cmd, false, details);
            }
            return new Answer(cmd, true, null);
        } else if (dstore instanceof S3TO) {
            final S3TO s3 = (S3TO) dstore;
            final String path = obj.getPath();
            final String bucket = s3.getBucketName();
            try {
                S3Utils.deleteObject(s3, bucket, path);
                return new Answer(cmd, true, String.format("Deleted snapshot %1%s from bucket %2$s.", path, bucket));
            } catch (Exception e) {
                final String errorMessage = String.format(
                        "Failed to delete snapshot %1$s from bucket %2$s due to the following error: %3$s", path,
                        bucket, e.getMessage());
                s_logger.error(errorMessage, e);
                return new Answer(cmd, false, errorMessage);
            }
        } else if (dstore instanceof SwiftTO) {
            SwiftTO swiftTO = (SwiftTO)dstore;
            String path = obj.getPath();
            SwiftUtil.deleteObject(swiftTO, path);

            return new Answer(cmd, true, "Deleted snapshot " + path + " from swift");
        } else {
            return new Answer(cmd, false, "Unsupported image data store: " + dstore);
View Full Code Here

            return new GetStorageStatsAnswer(cmd, totalSize, usedSize);
        }
    }

    protected Answer execute(final DeleteCommand cmd) {
        DataTO obj = cmd.getData();
        DataObjectType objType = obj.getObjectType();
        switch (objType) {
        case TEMPLATE:
            return deleteTemplate(cmd);
        case VOLUME:
            return deleteVolume(cmd);
View Full Code Here

        }
        return Answer.createUnsupportedCommandAnswer(cmd);
    }

    protected Answer deleteTemplate(DeleteCommand cmd) {
        DataTO obj = cmd.getData();
        DataStoreTO dstore = obj.getDataStore();
        if (dstore instanceof NfsTO) {
            NfsTO nfs = (NfsTO) dstore;
            String relativeTemplatePath = obj.getPath();
            String parent = getRootDir(nfs.getUrl());

            if (relativeTemplatePath.startsWith(File.separator)) {
                relativeTemplatePath = relativeTemplatePath.substring(1);
            }

            if (!parent.endsWith(File.separator)) {
                parent += File.separator;
            }
            String absoluteTemplatePath = parent + relativeTemplatePath;
            File tmpltParent = new File(absoluteTemplatePath).getParentFile();
            String details = null;
            if (!tmpltParent.exists()) {
                details = "template parent directory " + tmpltParent.getName() + " doesn't exist";
                s_logger.debug(details);
                return new Answer(cmd, true, details);
            }
            File[] tmpltFiles = tmpltParent.listFiles();
            if (tmpltFiles == null || tmpltFiles.length == 0) {
                details = "No files under template parent directory " + tmpltParent.getName();
                s_logger.debug(details);
            } else {
                boolean found = false;
                for (File f : tmpltFiles) {
                    if (!found && f.getName().equals("template.properties")) {
                        found = true;
                    }

                    // KVM HA monitor makes a mess in the templates with its
                    // heartbeat tests
                    // Don't let this stop us from cleaning up the template
                    if (f.isDirectory() && f.getName().equals("KVMHA")) {
                        s_logger.debug("Deleting KVMHA directory contents from template location");
                        File[] haFiles = f.listFiles();
                        for (File haFile : haFiles) {
                            haFile.delete();
                        }
                    }

                    if (!f.delete()) {
                        return new Answer(cmd, false, "Unable to delete file " + f.getName() + " under Template path "
                                + relativeTemplatePath);
                    }
                }

                if (!found) {
                    details = "Can not find template.properties under " + tmpltParent.getName();
                    s_logger.debug(details);
                }
            }
            if (!tmpltParent.delete()) {
                details = "Unable to delete directory " + tmpltParent.getName() + " under Template path "
                        + relativeTemplatePath;
                s_logger.debug(details);
                return new Answer(cmd, false, details);
            }
            return new Answer(cmd, true, null);
        } else if (dstore instanceof S3TO) {
            final S3TO s3 = (S3TO) dstore;
            final String path = obj.getPath();
            final String bucket = s3.getBucketName();
            try {
                S3Utils.deleteDirectory(s3, bucket, path);
                return new Answer(cmd, true, String.format("Deleted template %1$s from bucket %2$s.", path, bucket));
            } catch (Exception e) {
                final String errorMessage = String.format(
                        "Failed to delete template %1$s from bucket %2$s due to the following error: %3$s", path,
                        bucket, e.getMessage());
                s_logger.error(errorMessage, e);
                return new Answer(cmd, false, errorMessage);
            }
        } else if (dstore instanceof SwiftTO) {
            SwiftTO swift = (SwiftTO) dstore;
            String container = "T-" + obj.getId();
            String object = "";

            try {
                String result = swiftDelete(swift, container, object);
                if (result != null) {
View Full Code Here

            return new Answer(cmd, false, "Unsupported image data store: " + dstore);
        }
    }

    protected Answer deleteVolume(final DeleteCommand cmd) {
        DataTO obj = cmd.getData();
        DataStoreTO dstore = obj.getDataStore();
        if (dstore instanceof NfsTO) {
            NfsTO nfs = (NfsTO) dstore;
            String relativeVolumePath = obj.getPath();
            String parent = getRootDir(nfs.getUrl());

            if (relativeVolumePath.startsWith(File.separator)) {
                relativeVolumePath = relativeVolumePath.substring(1);
            }

            if (!parent.endsWith(File.separator)) {
                parent += File.separator;
            }
            String absoluteVolumePath = parent + relativeVolumePath;
            File volPath = new File(absoluteVolumePath);
            File tmpltParent = null;
            if (volPath.exists() && volPath.isDirectory()) {
                // for vmware, absoluteVolumePath represents a directory where volume files are located.
                tmpltParent = volPath;
            } else{
                // for other hypervisors, the volume .vhd or .qcow2 file path is passed
                tmpltParent = new File(absoluteVolumePath).getParentFile();
            }
            String details = null;
            if (!tmpltParent.exists()) {
                details = "volume parent directory " + tmpltParent.getName() + " doesn't exist";
                s_logger.debug(details);
                return new Answer(cmd, true, details);
            }
            File[] tmpltFiles = tmpltParent.listFiles();
            if (tmpltFiles == null || tmpltFiles.length == 0) {
                details = "No files under volume parent directory " + tmpltParent.getName();
                s_logger.debug(details);
            } else {
                boolean found = false;
                for (File f : tmpltFiles) {
                    if (!found && f.getName().equals("volume.properties")) {
                        found = true;
                    }

                    // KVM HA monitor makes a mess in the templates with its
                    // heartbeat tests
                    // Don't let this stop us from cleaning up the template
                    if (f.isDirectory() && f.getName().equals("KVMHA")) {
                        s_logger.debug("Deleting KVMHA directory contents from template location");
                        File[] haFiles = f.listFiles();
                        for (File haFile : haFiles) {
                            haFile.delete();
                        }
                    }

                    if (!f.delete()) {
                        return new Answer(cmd, false, "Unable to delete file " + f.getName() + " under Volume path "
                                + tmpltParent.getPath());
                    }
                }
                if (!found) {
                    details = "Can not find volume.properties under " + tmpltParent.getName();
                    s_logger.debug(details);
                }
            }
            if (!tmpltParent.delete()) {
                details = "Unable to delete directory " + tmpltParent.getName() + " under Volume path "
                        + tmpltParent.getPath();
                s_logger.debug(details);
                return new Answer(cmd, false, details);
            }
            return new Answer(cmd, true, null);
        } else if (dstore instanceof S3TO) {
            final S3TO s3 = (S3TO) dstore;
            final String path = obj.getPath();
            final String bucket = s3.getBucketName();
            try {
                S3Utils.deleteDirectory(s3, bucket, path);
                return new Answer(cmd, true, String.format("Deleted volume %1%s from bucket %2$s.", path, bucket));
            } catch (Exception e) {
                final String errorMessage = String.format(
                        "Failed to delete volume %1$s from bucket %2$s due to the following error: %3$s", path, bucket,
                        e.getMessage());
                s_logger.error(errorMessage, e);
                return new Answer(cmd, false, errorMessage);
            }
        } else if (dstore instanceof SwiftTO) {
            Long volumeId = obj.getId();
            String path = obj.getPath();
            String filename = StringUtils.substringAfterLast(path, "/"); // assuming
            // that
            // the
            // filename
            // is
View Full Code Here

    }

    @Override
    public AttachAnswer attachIso(AttachCommand cmd) {
        DiskTO disk = cmd.getDisk();
        DataTO data = disk.getData();
        DataStoreTO store = data.getDataStore();

        String isoURL = null;
        if (store == null) {
            TemplateObjectTO iso = (TemplateObjectTO)disk.getData();
            isoURL = iso.getName();
        } else {
            if (!(store instanceof NfsTO)) {
                s_logger.debug("Can't attach a iso which is not created on nfs: ");
                return new AttachAnswer("Can't attach a iso which is not created on nfs: ");
            }
            NfsTO nfsStore = (NfsTO)store;
            isoURL = nfsStore.getUrl() + File.separator + data.getPath();
        }

        String vmName = cmd.getVmName();
        try {
            Connection conn = this.hypervisorResource.getConnection();
View Full Code Here

    @Override
    public AttachAnswer attachVolume(AttachCommand cmd) {
        String vmName = cmd.getVmName();
        DiskTO disk = cmd.getDisk();
        DataTO data = disk.getData();

        try {
            Connection conn = this.hypervisorResource.getConnection();
            // Look up the VDI
            VDI vdi = null;

            if (cmd.isManaged()) {
                vdi = this.hypervisorResource.handleSrAndVdiAttach(cmd.get_iScsiName(), cmd.getStorageHost(),
                        cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword());
            }
            else {
                vdi = this.hypervisorResource.mount(conn, null, null, data.getPath());
            }

            // Look up the VM
            VM vm = this.hypervisorResource.getVM(conn, vmName);
            /* For HVM guest, if no pv driver installed, no attach/detach */
            boolean isHVM;
            if (vm.getPVBootloader(conn).equalsIgnoreCase("")) {
                isHVM = true;
            } else {
                isHVM = false;
            }
            VMGuestMetrics vgm = vm.getGuestMetrics(conn);
            boolean pvDrvInstalled = false;
            if (!this.hypervisorResource.isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) {
                pvDrvInstalled = true;
            }
            if (isHVM && !pvDrvInstalled) {
                s_logger.warn(": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected");
                return new AttachAnswer("You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso.");
            }

            // Figure out the disk number to attach the VM to
            String diskNumber = null;
            Long deviceId = disk.getDiskSeq();
            if( deviceId != null ) {
                if( deviceId.longValue() == 3 ) {
                    String msg = "Device 3 is reserved for CD-ROM, choose other device";
                    return new AttachAnswer(msg);
                }
                if(this.hypervisorResource.isDeviceUsed(conn, vm, deviceId)) {
                    String msg = "Device " + deviceId + " is used in VM " + vmName;
                    return new AttachAnswer(msg);
                }
                diskNumber = deviceId.toString();
            } else {
                diskNumber = this.hypervisorResource.getUnusedDeviceNum(conn, vm);
            }
            // Create a new VBD
            VBD.Record vbdr = new VBD.Record();
            vbdr.VM = vm;
            vbdr.VDI = vdi;
            vbdr.bootable = false;
            vbdr.userdevice = diskNumber;
            vbdr.mode = Types.VbdMode.RW;
            vbdr.type = Types.VbdType.DISK;
            vbdr.unpluggable = true;
            VBD vbd = VBD.create(conn, vbdr);

            // Attach the VBD to the VM
            vbd.plug(conn);

            // Update the VDI's label to include the VM name
            vdi.setNameLabel(conn, vmName + "-DATA");
            DiskTO newDisk = new DiskTO(disk.getData(), Long.parseLong(diskNumber), vdi.getUuid(conn), disk.getType());
            return new AttachAnswer(newDisk);

        } catch (XenAPIException e) {
            String msg = "Failed to attach volume" + " for uuid: " + data.getPath() + "  due to " + e.toString();
            s_logger.warn(msg, e);
            return new AttachAnswer(msg);
        } catch (Exception e) {
            String msg = "Failed to attach volume" + " for uuid: " + data.getPath() + "  due to "  + e.getMessage();
            s_logger.warn(msg, e);
            return new AttachAnswer(msg);
        }
    }
View Full Code Here

    }

    @Override
    public Answer dettachIso(DettachCommand cmd) {
        DiskTO disk = cmd.getDisk();
        DataTO data = disk.getData();
        DataStoreTO store = data.getDataStore();

        String isoURL = null;
        if (store == null) {
            TemplateObjectTO iso = (TemplateObjectTO)disk.getData();
            isoURL = iso.getName();
        } else {
            if (!(store instanceof NfsTO)) {
                s_logger.debug("Can't attach a iso which is not created on nfs: ");
                return new AttachAnswer("Can't attach a iso which is not created on nfs: ");
            }
            NfsTO nfsStore = (NfsTO)store;
            isoURL = nfsStore.getUrl() + File.separator + data.getPath();
        }

        try {
            Connection conn = this.hypervisorResource.getConnection();
            // Find the VM
            VM vm = this.hypervisorResource.getVM(conn, cmd.getVmName());
            String vmUUID = vm.getUuid(conn);

            // Find the ISO VDI
            VDI isoVDI = this.hypervisorResource.getIsoVDIByURL(conn, cmd.getVmName(), isoURL);

            SR sr = isoVDI.getSR(conn);

            // Look up all VBDs for this VDI
            Set<VBD> vbds = isoVDI.getVBDs(conn);

            // Iterate through VBDs, and if the VBD belongs the VM, eject
            // the ISO from it
            for (VBD vbd : vbds) {
                VM vbdVM = vbd.getVM(conn);
                String vbdVmUUID = vbdVM.getUuid(conn);

                if (vbdVmUUID.equals(vmUUID)) {
                    // If an ISO is already inserted, eject it
                    if (!vbd.getEmpty(conn)) {
                        vbd.eject(conn);
                    }
                    break;
                }
            }

            if (!sr.getNameLabel(conn).startsWith("XenServer Tools")) {
                this.hypervisorResource.removeSR(conn, sr);
            }

            return new DettachAnswer(disk);
        } catch (XenAPIException e) {
            String msg = "Failed to dettach volume" + " for uuid: " + data.getPath() + "  due to " + e.toString();
            s_logger.warn(msg, e);
            return new DettachAnswer(msg);
        } catch (Exception e) {
            String msg = "Failed to dettach volume" + " for uuid: " + data.getPath() + "  due to "  + e.getMessage();
            s_logger.warn(msg, e);
            return new DettachAnswer(msg);
        }
    }
View Full Code Here

    @Override
    public Answer dettachVolume(DettachCommand cmd) {
        String vmName = cmd.getVmName();
        DiskTO disk = cmd.getDisk();
        DataTO data = disk.getData();
        try {
            Connection conn = this.hypervisorResource.getConnection();
            // Look up the VDI
            VDI vdi = this.hypervisorResource.mount(conn, null, null, data.getPath());
            // Look up the VM
            VM vm = this.hypervisorResource.getVM(conn, vmName);
            /* For HVM guest, if no pv driver installed, no attach/detach */
            boolean isHVM;
            if (vm.getPVBootloader(conn).equalsIgnoreCase("")) {
                isHVM = true;
            } else {
                isHVM = false;
            }
            VMGuestMetrics vgm = vm.getGuestMetrics(conn);
            boolean pvDrvInstalled = false;
            if (!this.hypervisorResource.isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) {
                pvDrvInstalled = true;
            }
            if (isHVM && !pvDrvInstalled) {
                s_logger.warn(": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected");
                return new DettachAnswer("You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso.");
            }


            // Look up all VBDs for this VDI
            Set<VBD> vbds = vdi.getVBDs(conn);

            // Detach each VBD from its VM, and then destroy it
            for (VBD vbd : vbds) {
                VBD.Record vbdr = vbd.getRecord(conn);

                if (vbdr.currentlyAttached) {
                    vbd.unplug(conn);
                }

                vbd.destroy(conn);
            }

            // Update the VDI's label to be "detached"
            vdi.setNameLabel(conn, "detached");

            this.hypervisorResource.umount(conn, vdi);

            if (cmd.isManaged()) {
                this.hypervisorResource.handleSrAndVdiDetach(cmd.get_iScsiName());
            }

            return new DettachAnswer(disk);
        } catch(Exception e) {
            s_logger.warn("Failed dettach volume: " + data.getPath());
            return new DettachAnswer("Failed dettach volume: " + data.getPath() + ", due to " + e.toString());
        }
    }
View Full Code Here

        return new CreateObjectAnswer(details);
    }

    @Override
    public Answer deleteVolume(DeleteCommand cmd) {
        DataTO volume = cmd.getData();
        Connection conn = hypervisorResource.getConnection();
        String errorMsg = null;
        try {
            VDI vdi = VDI.getByUuid(conn, volume.getPath());
            deleteVDI(conn, vdi);
            return new Answer(null);
        } catch (BadServerResponse e) {
            s_logger.debug("Failed to delete volume", e);
            errorMsg = e.toString();
View Full Code Here

TOP

Related Classes of com.cloud.agent.api.to.DataTO

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.