Package com.abiquo.am.model.ovf

Source Code of com.abiquo.am.model.ovf.TemplateFromOVFEnvelope

/**
* Licensed to Abiquo Holdings S.L. (Abiquo) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.abiquo.am.model.ovf;

import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.dmtf.schemas.ovf.envelope._1.ContentType;
import org.dmtf.schemas.ovf.envelope._1.DiskSectionType;
import org.dmtf.schemas.ovf.envelope._1.EnvelopeType;
import org.dmtf.schemas.ovf.envelope._1.FileType;
import org.dmtf.schemas.ovf.envelope._1.MsgType;
import org.dmtf.schemas.ovf.envelope._1.OperatingSystemSectionType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType.Icon;
import org.dmtf.schemas.ovf.envelope._1.RASDType;
import org.dmtf.schemas.ovf.envelope._1.VirtualDiskDescType;
import org.dmtf.schemas.ovf.envelope._1.VirtualHardwareSectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemCollectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemType;
import org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_resourceallocationsettingdata.ResourceType;
import org.dmtf.schemas.wbem.wscim._1.common.CimString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.abiquo.am.model.MemorySizeUnit;
import com.abiquo.am.model.TemplateDto;
import com.abiquo.am.model.error.AMError;
import com.abiquo.am.model.error.AMException;
import com.abiquo.model.enumerator.DiskControllerType;
import com.abiquo.model.enumerator.DiskFormatType;
import com.abiquo.model.enumerator.EthernetDriverType;
import com.abiquo.model.enumerator.OSType;
import com.abiquo.ovfmanager.cim.CIMTypesUtils.CIMResourceTypeEnum;
import com.abiquo.ovfmanager.ovf.OVFEnvelopeUtils;
import com.abiquo.ovfmanager.ovf.exceptions.EmptyEnvelopeException;
import com.abiquo.ovfmanager.ovf.exceptions.IdAlreadyExistsException;
import com.abiquo.ovfmanager.ovf.exceptions.IdNotFoundException;
import com.abiquo.ovfmanager.ovf.exceptions.InvalidSectionException;
import com.abiquo.ovfmanager.ovf.exceptions.RequiredAttributeException;
import com.abiquo.ovfmanager.ovf.exceptions.SectionAlreadyPresentException;
import com.abiquo.ovfmanager.ovf.exceptions.SectionNotPresentException;
import com.abiquo.ovfmanager.ovf.section.DiskFormat;

public class TemplateFromOVFEnvelope
{
    private final static Logger LOG = LoggerFactory.getLogger(TemplateFromOVFEnvelope.class);

    public static VirtualDiskDescType getDisk(final EnvelopeType envelope)
    {
        DiskSectionType diskSection = null;
        try
        {
            diskSection = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
        }
        catch (Exception e)// SectionNotPresentException InvalidSectionException
        {
            throw new AMException(AMError.TEMPLATE_INVALID, "missing DiskSection");
        }

        List<VirtualDiskDescType> disks = diskSection.getDisk();

        if (disks == null || disks.isEmpty() || disks.size() != 1)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, "multiple Disk not supported");
        }

        return disks.get(0);

    }

    /**
     * TODO re-DOC <br>
     * REQUIRE THE OVFID IS PLACED ON A REMOTE LOCATION (WARINING on generation)<BR>
     * Creates a list of VirtualInfo relative to the VirtualDisk (from the disk section) and
     * requirements (from the VirtualHardwareSection) contained on the provided OVF envelope. Used
     * to add VirtualImage on database once an OVFPackage completes its download. No duplicated Disk
     * are returned.
     *
     * @param ovfDescription, the OVF description of the required OVF package.
     * @return an array containing all the DiskInfo properties and requirements.
     * @throws RepositoryException, if the envelope do not contain the required info to get
     *             VirtualDisk information.
     **/
    public static TemplateDto createTemplateDto(final String ovfId, EnvelopeType envelope)
    // TODO String userID, String category
        throws AMException
    {
        envelope = checkEnvelopeIsValid(envelope);

        TemplateDto diskInfo = null;

        Map<String, VirtualDiskDescType> diskIdToDiskFormat =
            new HashMap<String, VirtualDiskDescType>();
        Map<String, FileType> fileIdToFileType = new HashMap<String, FileType>();
        Map<String, List<String>> diskIdToVSs = new HashMap<String, List<String>>();
        Map<String, TemplateDto> requiredByVSs = new HashMap<String, TemplateDto>();
        DiskSectionType diskSectionType;

        try
        {
            ContentType contentType = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

            ProductSectionType product =
                OVFEnvelopeUtils.getSection(contentType, ProductSectionType.class);
            OperatingSystemSectionType ossection = null;
            try
            {
                ossection =
                    OVFEnvelopeUtils.getSection(contentType, OperatingSystemSectionType.class);
            }
            catch (Exception e) // no such section
            {

            }

            String description = null;
            if (product.getInfo() != null && product.getInfo().getValue() != null)
            {
                description = product.getInfo().getValue();
            }

            String categoryName = null;
            if (product.getOtherAttributes().containsKey(new QName("CategoryName")))
            {
                categoryName = product.getOtherAttributes().get(new QName("CategoryName"));
            }

            String iconPath = getIconPath(product, fileIdToFileType, ovfId);

            diskSectionType = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

            for (FileType fileType : envelope.getReferences().getFile())
            {
                fileIdToFileType.put(fileType.getId(), fileType);
            }
            // Create a hash
            for (VirtualDiskDescType virtualDiskDescType : diskSectionType.getDisk())
            {
                diskIdToDiskFormat.put(virtualDiskDescType.getDiskId(), virtualDiskDescType);
            }

            if (contentType instanceof VirtualSystemType)
            {

                VirtualSystemType vs = (VirtualSystemType) contentType;
                TemplateDto req = getDiskInfo(vs, diskIdToDiskFormat, diskIdToVSs);

                requiredByVSs.put(vs.getId(), req);
            }
            else if (contentType instanceof VirtualSystemCollectionType)
            {
                List<VirtualSystemType> virtualSystems =
                    OVFEnvelopeUtils.getVirtualSystems((VirtualSystemCollectionType) contentType);

                for (VirtualSystemType virtualSystemType : virtualSystems)
                {
                    TemplateDto req =
                        getDiskInfo(virtualSystemType, diskIdToDiskFormat, diskIdToVSs);

                    requiredByVSs.put(virtualSystemType.getId(), req);
                }
            }

            for (VirtualDiskDescType diskDescType : diskIdToDiskFormat.values())
            {

                String diskId = diskDescType.getDiskId();
                String fileId = diskDescType.getFileRef();

                if (!fileIdToFileType.containsKey(fileId))
                {
                    String msg = "File Id [" + fileId + "] not found on the ReferencesSection";
                    throw new IdNotFoundException(msg);
                }

                FileType file = fileIdToFileType.get(fileId);
                final String filePath = file.getHref();
                final Long fileSize = file.getSize().longValue();

                String format = diskDescType.getFormat(); // XXX using the same format on the OVF
                // disk

                if (!diskIdToVSs.containsKey(diskId))
                {
                    throw new IdNotFoundException("Any virtualSystem is using diskId[" + diskId
                        + "]"); // XXX warning ??
                }

                if (diskIdToVSs.size() != 1)
                {
                    throw new AMException(AMError.TEMPLATE_INVALID, String.format(
                        "There are more than one virtual system on the OVF Envelope [%s]", ovfId));
                }

                for (String vssName : diskIdToVSs.get(diskId))
                {
                    diskInfo = new TemplateDto();
                    diskInfo.setName(vssName);
                    diskInfo.setUrl(ovfId);
                    diskInfo.setLoginUser(getProductPropertyValue(product, "user"));
                    diskInfo.setLoginPassword(getProductPropertyValue(product, "password"));
                    diskInfo.setOsType(getOSType(ossection));
                    diskInfo.setOsVersion(getOSVersion(ossection));

                    DiskFormat diskFormat = DiskFormat.fromValue(format);
                    DiskFormatType ovfDiskFormat = DiskFormatType.valueOf(diskFormat.name());

                    diskInfo.setDiskFileFormat(ovfDiskFormat);
                    diskInfo.setDiskFileSize(fileSize);

                    // Note that getHRef() will now return the relative path
                    // of the file at the downloaded repository space

                    if (filePath.startsWith("http:"))
                    {
                        diskInfo.setDiskFilePath(FilenameUtils.getName(filePath));
                    }
                    else
                    {
                        diskInfo.setDiskFilePath(filePath);
                    }

                    diskInfo.setIconPath(iconPath);
                    diskInfo.setDescription(description);
                    diskInfo.setCategoryName(categoryName);
                    // XXX diskInfo.setSO(value);

                    if (!requiredByVSs.containsKey(vssName))
                    {
                        throw new IdNotFoundException("VirtualSystem id not found [" + vssName
                            + "]");
                    }

                    TemplateDto requirement = requiredByVSs.get(vssName);

                    // XXX disk format ::: diskInfo.setImageType(requirement.getImageType());

                    diskInfo.setCpu(requirement.getCpu());
                    diskInfo.setRam(requirement.getRam());
                    diskInfo.setHd(requirement.getHd());

                    diskInfo.setRamSizeUnit(requirement.getRamSizeUnit());
                    diskInfo.setHdSizeUnit(requirement.getHdSizeUnit());

                    diskInfo.setEthernetDriverType(requirement.getEthernetDriverType());
                    diskInfo.setDiskControllerType(requirement.getDiskControllerType());

                    // TODO diskInfo.setEnterpriseId(enterpriseId);
                    // diskInfo.setUserId(userId); TODO user ID
                    // diskInfo.getCategories().add(category); TODO category

                }// all vss
            }// all disks
        }
        catch (EmptyEnvelopeException e)
        {
            String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
            throw new AMException(AMError.TEMPLATE_INVALID, msg, e);
        }
        catch (Exception e)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, e);
        }

        if (diskInfo == null)
        {
            String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
            throw new AMException(AMError.TEMPLATE_INVALID, msg);
        }

        return diskInfo;
    }

    /**
     * Adds a simple ProductSection if its not found
     */
    public static EnvelopeType fixOVfDocument(final String ovfId, EnvelopeType envelope)
    {
        try
        {
            envelope = fixDiskFormtatUriAndFileSizes(envelope, ovfId);
            envelope = fixMissingProductSection(envelope);
        }
        catch (Exception e)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, e);
        }

        return envelope;
    }

    /**
     * Check for all the abiquo required attributes in the ovf document.
     */
    public static EnvelopeType checkEnvelopeIsValid(final EnvelopeType envelope)
    {
        try
        {
            Map<String, VirtualDiskDescType> diskIdToDiskFormat =
                new HashMap<String, VirtualDiskDescType>();
            Map<String, FileType> fileIdToFileType = new HashMap<String, FileType>();

            DiskSectionType diskSectionType =
                OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

            if (diskSectionType.getDisk().size() != 1)
            {
                // more than one disk in disk section
                throw new AMException(AMError.TEMPLATE_INVALID_MULTIPLE_DISKS);
            }
            else
            {
                int references = 0;
                for (FileType fileType : envelope.getReferences().getFile())
                {
                    fileIdToFileType.put(fileType.getId(), fileType);
                    if (diskSectionType.getDisk().get(0).getFileRef().equals(fileType.getId()))
                    {
                        references++;
                    }
                }
                if (references != 1)
                {
                    // file referenced in diskSection isn't found in file references or found more
                    // than one
                    throw new AMException(AMError.TEMPLATE_INVALID_MULTIPLE_FILES);
                }
            }
            // Create a hash
            for (VirtualDiskDescType virtualDiskDescType : diskSectionType.getDisk())
            {
                diskIdToDiskFormat.put(virtualDiskDescType.getDiskId(), virtualDiskDescType);
            }

            // /

            ContentType content = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

            if (content instanceof VirtualSystemCollectionType)
            {
                throw new EmptyEnvelopeException(
                    "Current OVF description document includes a VirtualSystemCollection, "
                        + "abicloud only deal with single virtual system based OVFs");
            }

            VirtualSystemType vsystem = (VirtualSystemType) content;

            VirtualHardwareSectionType hardwareSectionType;
            Integer cpu = null;
            Long hd = null;
            Long ram = null;

            try
            {
                hardwareSectionType =
                    OVFEnvelopeUtils.getSection(vsystem, VirtualHardwareSectionType.class);
            }
            catch (InvalidSectionException e)
            {
                throw new SectionNotPresentException("VirtualHardware on a virtualSystem", e);
            }

            for (RASDType rasdType : hardwareSectionType.getItem())
            {

                ResourceType resourceType = rasdType.getResourceType();
                if (resourceType == null) // empty rasd element
                {
                    continue;
                }
                int resTnumeric = Integer.parseInt(resourceType.getValue());

                // Get the information on the ram
                if (CIMResourceTypeEnum.Processor.getNumericResourceType() == resTnumeric)
                {
                    try
                    {
                        String cpuVal = rasdType.getVirtualQuantity().getValue().toString();

                        cpu = Integer.parseInt(cpuVal);
                    }
                    catch (Exception e)
                    {
                        throw new AMException(AMError.TEMPLATE_INVALID,
                            "Invalid CPU virtualQuantity");
                    }
                }
                else if (CIMResourceTypeEnum.Memory.getNumericResourceType() == resTnumeric)
                {
                    try
                    {
                        BigInteger ramVal = rasdType.getVirtualQuantity().getValue();

                        ram = ramVal.longValue();
                    }
                    catch (Exception e)
                    {
                        throw new AMException(AMError.TEMPLATE_INVALID,
                            "Invalid RAM virtualQuantity");
                    }

                    if (rasdType.getAllocationUnits() != null
                        & rasdType.getAllocationUnits().getValue() != null)
                    {
                        final String allocationUnits = rasdType.getAllocationUnits().getValue();

                        final MemorySizeUnit ramSizeUnit = getMemoryUnitsFromOVF(allocationUnits);
                    }
                }
                else if (CIMResourceTypeEnum.Disk_Drive.getNumericResourceType() == resTnumeric)
                {
                    // HD requirements are extracted from the associated Disk on ''hostResource''
                    String diskId = getVirtualSystemDiskId(rasdType.getHostResource());

                    if (!diskIdToDiskFormat.containsKey(diskId))
                    {
                        throw new RequiredAttributeException(
                            "Virtual System makes reference to an undeclared disk " + diskId);
                    }

                    VirtualDiskDescType diskDescType = diskIdToDiskFormat.get(diskId);

                    String capacity = diskDescType.getCapacity();

                    hd = Long.parseLong(capacity);

                    final String allocationUnits = diskDescType.getCapacityAllocationUnits();
                    final MemorySizeUnit hdSizeUnit = getMemoryUnitsFromOVF(allocationUnits);
                }
            }// rasd

            if (cpu == null)
            {
                throw new RequiredAttributeException("Not CPU RASD element found on the envelope");
            }
            if (ram == null)
            {
                throw new RequiredAttributeException("Not RAM RASD element found on the envelope");
            }
            if (hd == null)
            {
                throw new RequiredAttributeException("Not HD RASD element found on the envelope");
            }

        }

        catch (AMException amException)
        {
            throw amException;
        }
        catch (Exception e)
        {
            throw new AMException(AMError.TEMPLATE_INVALID, e);
        }

        return envelope;
    }

    /**
     * Only the first icon on product section is used
     */
    private static String getIconPath(final ProductSectionType product,
        final Map<String, FileType> fileIdToFileType, final String ovfId)
    {
        List<Icon> icons = product.getIcon();
        if (icons == null || icons.size() == 0)
        {
            return null;
        }

        final Icon icon = icons.get(0);
        final String iconRef = icon.getFileRef();

        if (iconRef.startsWith("http"))
        {
            return iconRef;
        }

        if (!fileIdToFileType.containsKey(iconRef))
        {
            return null; // XXX log cause
        }

        final String iconPathRelative = fileIdToFileType.get(iconRef).getHref();

        if (iconPathRelative.startsWith("http"))
        {
            return iconPathRelative;
        }

        final String ovfAbs = ovfId.substring(0, ovfId.lastIndexOf('/'));

        return ovfAbs + '/' + iconPathRelative;
    }

    private static String getProductPropertyValue(final ProductSectionType product,
        final String propertyKey)
    {
        for (Object obj : product.getCategoryOrProperty())
        {
            if (obj instanceof ProductSectionType.Property)
            {
                ProductSectionType.Property prop = (ProductSectionType.Property) obj;
                if (propertyKey.equalsIgnoreCase(prop.getKey()))
                {
                    return prop.getValue();
                }
            }
        }
        return null;
    }

    private static OSType getOSType(OperatingSystemSectionType ossection)
    {
        try
        {
            return ossection != null ? OSType.fromCode(ossection.getId()) : OSType.UNRECOGNIZED;
        }
        catch (Exception e)
        {
            return OSType.UNRECOGNIZED;
        }
    }

    private static String getOSVersion(OperatingSystemSectionType ossection)
    {
        try
        {
            return ossection != null ? ossection.getVersion() : null;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    /**
     * TODO TBD
     **/
    private static TemplateDto getDiskInfo(final VirtualSystemType vsystem,
        final Map<String, VirtualDiskDescType> diskDescByName,
        final Map<String, List<String>> diskIdToVSs) throws IdAlreadyExistsException,
        RequiredAttributeException, SectionNotPresentException
    {
        TemplateDto dReq = new TemplateDto();
        VirtualHardwareSectionType hardwareSectionType;

        try
        {
            hardwareSectionType =
                OVFEnvelopeUtils.getSection(vsystem, VirtualHardwareSectionType.class);
        }
        catch (InvalidSectionException e)
        {
            throw new SectionNotPresentException("VirtualHardware on a virtualSystem", e);
        }

        dReq.setCpu(-1);
        dReq.setHd(Long.valueOf(-1));
        dReq.setRam(Long.valueOf(-1));

        // XXX now we are using ONLY the Disk format

        // XXX String vsType = hardwareSectionType.getSystem().getVirtualSystemType().getValue();
        // XXX dReq.setImageType(vsType);
        // XXX log.debug("Using ''virtualSystemType'' [{}]", vsType);

        for (RASDType rasdType : hardwareSectionType.getItem())
        {
            ResourceType resourceType = rasdType.getResourceType();
            int resTnumeric = Integer.parseInt(resourceType.getValue());

            // TODO use CIMResourceTypeEnum from value and then a SWITCH

            // Get the information on the ram
            if (CIMResourceTypeEnum.Processor.getNumericResourceType() == resTnumeric)
            {
                String cpuVal = rasdType.getVirtualQuantity().getValue().toString();

                dReq.setCpu(Integer.parseInt(cpuVal));

                // TODO if(rasdType.getAllocationUnits()!= null)
            }
            else if (CIMResourceTypeEnum.Memory.getNumericResourceType() == resTnumeric)
            {
                BigInteger ramVal = rasdType.getVirtualQuantity().getValue();

                dReq.setRam(ramVal.longValue());

                if (rasdType.getAllocationUnits() != null
                    & rasdType.getAllocationUnits().getValue() != null)
                {
                    final String allocationUnits = rasdType.getAllocationUnits().getValue();

                    final MemorySizeUnit ramSizeUnit = getMemoryUnitsFromOVF(allocationUnits);

                    dReq.setRamSizeUnit(ramSizeUnit);
                }
            }
            else if (CIMResourceTypeEnum.Disk_Drive.getNumericResourceType() == resTnumeric)
            {
                // HD requirements are extracted from the associated Disk on ''hostResource''
                String diskId = getVirtualSystemDiskId(rasdType.getHostResource());

                if (!diskDescByName.containsKey(diskId))
                {
                    String msg = "DiskId [" + diskId + "] not found on disk section";
                    throw new IdAlreadyExistsException(msg);
                }

                if (!diskIdToVSs.containsKey(diskId))
                {
                    List<String> vss = new LinkedList<String>();
                    vss.add(vsystem.getId()); // XXX

                    diskIdToVSs.put(diskId, vss);
                }
                else
                {
                    diskIdToVSs.get(diskId).add(vsystem.getId());
                }

                VirtualDiskDescType diskDescType = diskDescByName.get(diskId);

                String capacity = diskDescType.getCapacity();

                dReq.setHd(Long.parseLong(capacity));

                final String allocationUnits = diskDescType.getCapacityAllocationUnits();
                final MemorySizeUnit hdSizeUnit = getMemoryUnitsFromOVF(allocationUnits);

                dReq.setHdSizeUnit(hdSizeUnit);
                // dReq.setImageSize(diskDescType.get);
            }
            else if (CIMResourceTypeEnum.Ethernet_Adapter.getNumericResourceType() == resTnumeric)
            {
                String ethDriver = null;
                EthernetDriverType ethDriverType = null;
                try
                {
                    ethDriver = rasdType.getResourceSubType().getValue();
                    ethDriverType = EthernetDriverType.valueOf(ethDriver);
                }
                catch (Exception e)
                {
                    LOG.error("Invalid ethernet adapter type {}", ethDriver != null ? ethDriver
                        : "-ResourceSubType- not found");
                }

                if (dReq.getEthernetDriverType() != null && ethDriverType != null)
                {
                    LOG.warn("Overwrite ethernet adapter type form {} to {}", dReq
                        .getEthernetDriverType().name(), ethDriverType.name());
                }
                else if (ethDriverType != null)
                {
                    dReq.setEthernetDriverType(ethDriverType);
                }
            }
            else if (CIMResourceTypeEnum.IDE_Controller.getNumericResourceType() == resTnumeric)
            {
                if (dReq.getDiskControllerType() != null)
                {
                    LOG.warn("Overwrite disk controller type form {} to {}", dReq
                        .getDiskControllerType().name(), DiskControllerType.IDE.name());
                }

                dReq.setDiskControllerType(DiskControllerType.IDE);
            }
            else if (CIMResourceTypeEnum.Parallel_SCSI_HBA.getNumericResourceType() == resTnumeric)
            {
                if (dReq.getDiskControllerType() != null)
                {
                    LOG.warn("Overwrite disk controller type form {} to {}", dReq
                        .getDiskControllerType().name(), DiskControllerType.SCSI.name());
                }

                dReq.setDiskControllerType(DiskControllerType.SCSI);
            }
        }// rasd

        // if the Ethernet/Disk controller is not specified let the API properties be used as default

        if (dReq.getCpu() == -1)
        {
            throw new RequiredAttributeException("Not CPU RASD element found on the envelope");
        }
        if (dReq.getRam() == -1)
        {
            throw new RequiredAttributeException("Not RAM RASD element found on the envelope");
        }
        if (dReq.getHd() == -1)
        {
            throw new RequiredAttributeException("Not HD RASD element found on the envelope");
        }

        return dReq;
    }

    /**
     * default is byte
     *
     * @throws RequiredAttributeException
     */
    private static MemorySizeUnit getMemoryUnitsFromOVF(final String allocationUnits)
        throws RequiredAttributeException
    {

        if (allocationUnits == null || "byte".equalsIgnoreCase(allocationUnits)
            || "bytes".equalsIgnoreCase(allocationUnits))
        {
            return MemorySizeUnit.BYTE;
        }
        else if ("byte * 2^10".equals(allocationUnits) || "KB".equalsIgnoreCase(allocationUnits)
            || "KILOBYTE".equalsIgnoreCase(allocationUnits)
            || "KILOBYTES".equalsIgnoreCase(allocationUnits)) // kb
        {
            return MemorySizeUnit.KILOBYTE;
        }
        else if ("byte * 2^20".equals(allocationUnits) || "MB".equalsIgnoreCase(allocationUnits)
            || "MEGABYTE".equalsIgnoreCase(allocationUnits)
            || "MEGABYTES".equalsIgnoreCase(allocationUnits)) // mb
        {
            return MemorySizeUnit.MEGABYTE;
        }
        else if ("byte * 2^30".equals(allocationUnits) || "GB".equalsIgnoreCase(allocationUnits)
            || "GIGABYTE".equalsIgnoreCase(allocationUnits)
            || "GIGABYTES".equalsIgnoreCase(allocationUnits)) // gb
        {
            return MemorySizeUnit.GIGABYTE;
        }
        else if ("byte * 2^40".equals(allocationUnits) || "TB".equalsIgnoreCase(allocationUnits)
            || "TERABYTE".equalsIgnoreCase(allocationUnits)
            || "TERABYTES".equalsIgnoreCase(allocationUnits)) // tb
        {
            return MemorySizeUnit.TERABYTE;
        }
        else
        {
            final String msg =
                "Unknow disk capacityAllocationUnits factor [" + allocationUnits + "]";

            throw new RequiredAttributeException(msg);
        }
    }

    /**
     * Decode CimStrings (on the OVF namespce) on the Disk RASD's HostResource attribute to delete
     * the ''ovf://disk/'' prefix
     **/
    private static String getVirtualSystemDiskId(final List<CimString> cimStrs)
    {
        String cimStringVal = "";
        for (CimString cimString : cimStrs)
        {
            cimStringVal = cimString.getValue();

            if (cimStringVal.startsWith("ovf:/disk/"))
            {
                cimStringVal = cimStringVal.replace("ovf:/disk/", "");
                break;
            }
            else if (cimStringVal.startsWith("/disk/"))
            {
                cimStringVal = cimStringVal.replace("/disk/", "");
                break;
            }
        }

        return cimStringVal;
    }

    private static EnvelopeType fixDiskFormtatUriAndFileSizes(final EnvelopeType envelope,
        final String ovfId) throws SectionNotPresentException, InvalidSectionException
    {

        DiskSectionType diskSection = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

        if (diskSection.getDisk().size() != 1)
        {
            final String message =
                "abicloud only supports single disk definition on the OVF, the current envelope contains multiple disk";
            throw new InvalidSectionException(message);
        }

        VirtualDiskDescType vdisk = diskSection.getDisk().get(0);

        String formatUri = vdisk.getFormat();

        if (StringUtils.isEmpty(formatUri))
        {
            final String message = "Missing ''format'' attribute for the Disk element";
            throw new InvalidSectionException(message);
        }

        DiskFormatType format = DiskFormatType.fromURI(formatUri);

        if (format == null) // the format URI isn't on the abicloud enumeration. FIX it
        {
            // vbox/vmware
            // http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized
            // abiquo
            // http://www.vmware.com/technical-resources/interfaces/vmdk_access.html#streamOptimized

            if (formatUri.contains("interfaces/specifications/vmdk.html"))
            {
                formatUri =
                    formatUri.replace("interfaces/specifications/vmdk.html",
                        "technical-resources/interfaces/vmdk_access.html");

                format = DiskFormatType.fromURI(formatUri);

                if (format == null)
                {
                    throw new InvalidSectionException(String.format(
                        "Invalid disk format type [%s]", formatUri));
                }

                vdisk.setFormat(formatUri);
            }

        }

        // try
        // {
        // for (FileType ftype : envelope.getReferences().getFile())
        // {
        // if (ftype.getSize() == null)
        // {
        // String fileUrl = getFileUrl(ftype.getHref(), ovfId);
        // Long size = new ExternalHttpConnection().headFile(fileUrl);
        //
        // ftype.setSize(BigInteger.valueOf(size));
        // }
        // }
        // }
        // catch (Exception e)
        // {
        // throw new InvalidSectionException(String.format("Invalid File References section "
        // + "(check all the files on the OVF document contains the ''size'' attribute):\n",
        // e.toString()));
        // }

        return envelope;
    }

    /**
     * If product section is not present use the VirtualSystemType to set it.
     *
     * @throws EmptyEnvelopeException
     */
    private static EnvelopeType fixMissingProductSection(final EnvelopeType envelope)
        throws InvalidSectionException, EmptyEnvelopeException
    {

        ContentType contentType = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

        if (!(contentType instanceof VirtualSystemType))
        {
            throw new InvalidSectionException(
                "abicloud only suport single virtual system definition,"
                    + " current OVF envelope defines a VirtualSystemCollection");
        }

        VirtualSystemType vsystem = (VirtualSystemType) contentType;

        try
        {
            OVFEnvelopeUtils.getSection(vsystem, ProductSectionType.class);
        }
        catch (SectionNotPresentException e)
        {

            String vsystemName =
                vsystem.getName() != null && !StringUtils.isEmpty(vsystem.getName().getValue())
                    ? vsystem.getName().getValue() : vsystem.getId();

            MsgType prod = new MsgType();
            prod.setValue(vsystemName);

            ProductSectionType product = new ProductSectionType();
            product.setInfo(vsystem.getInfo());
            product.setProduct(prod);

            try
            {
                OVFEnvelopeUtils.addSection(vsystem, product);
            }
            catch (SectionAlreadyPresentException e1)
            {
            }
        }

        return envelope;
    }

    /**
     * Gets an URL from the hRef attribute on a File's (References section). Try to interpret the
     * hRef attribute as an absolute URL (like http://some.where.com/file.vmdk), and if it fails try
     * to interpret the hRef as OVF package URI relative.
     *
     * @param relativeFilePath, the value on the hRef attribute for the File.
     * @param ovfId, the OVF Package identifier (and locator).
     * @throws DownloadException, it the URL can not be created.
     */
    private static String getFileUrl(final String relativeFilePath, final String ovfId)
    {
        URL fileURL;

        try
        {
            fileURL = new URL(relativeFilePath);
        }
        catch (MalformedURLException e1)
        {
            // its a relative path
            if (e1.getMessage().startsWith("no protocol"))
            {
                try
                {
                    String packageURL = ovfId.substring(0, ovfId.lastIndexOf('/'));
                    fileURL = new URL(packageURL + '/' + relativeFilePath);
                }
                catch (MalformedURLException e)
                {
                    final String msg = "Invalid file reference " + ovfId + '/' + relativeFilePath;
                    throw new AMException(AMError.TEMPLATE_INVALID, msg, e1);
                }
            }
            else
            {
                final String msg = "Invalid file reference " + relativeFilePath;
                throw new AMException(AMError.TEMPLATE_INVALID, msg, e1);
            }
        }
        return fileURL.toExternalForm();
    }

}
TOP

Related Classes of com.abiquo.am.model.ovf.TemplateFromOVFEnvelope

TOP
Copyright © 2018 www.massapi.com. 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.