From d5b041a7907d7815ac42d1b592eeab141dcc9833 Mon Sep 17 00:00:00 2001 From: abhishek Date: Thu, 19 Aug 2010 17:59:56 -0700 Subject: [PATCH] Refactoring register commands for template and iso --- .../cloud/api/commands/RegisterIsoCmd.java | 308 ++++++++---------- .../com/cloud/template/TemplateManager.java | 3 +- .../cloud/template/TemplateManagerImpl.java | 210 ++++++++---- 3 files changed, 289 insertions(+), 232 deletions(-) diff --git a/server/src/com/cloud/api/commands/RegisterIsoCmd.java b/server/src/com/cloud/api/commands/RegisterIsoCmd.java index cdd60384665..f290eaa89b8 100644 --- a/server/src/com/cloud/api/commands/RegisterIsoCmd.java +++ b/server/src/com/cloud/api/commands/RegisterIsoCmd.java @@ -18,44 +18,18 @@ package com.cloud.api.commands; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.apache.log4j.Logger; import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.dc.DataCenterVO; -import com.cloud.storage.Storage.FileSystem; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.VMTemplateHostVO; -import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; -import com.cloud.storage.VMTemplateVO; -import com.cloud.user.Account; -import com.cloud.utils.Pair; - +import com.cloud.api.BaseCmd.Manager; + +@Implementation(method="registerIso", manager=Manager.TemplateManager) public class RegisterIsoCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterIsoCmd.class.getName()); private static final String s_name = "registerisoresponse"; - private static final List> s_properties = new ArrayList>(); - - static { - s_properties.add(new Pair(BaseCmd.Properties.BOOTABLE, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.DISPLAY_TEXT, Boolean.TRUE)); - s_properties.add(new Pair(BaseCmd.Properties.IS_FEATURED, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.IS_PUBLIC, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.NAME, Boolean.TRUE)); - s_properties.add(new Pair(BaseCmd.Properties.OS_TYPE_ID, Boolean.TRUE)); - s_properties.add(new Pair(BaseCmd.Properties.URL, Boolean.TRUE)); - s_properties.add(new Pair(BaseCmd.Properties.ZONE_ID, Boolean.TRUE)); - - s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.USER_ID, Boolean.FALSE)); - - } ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -128,142 +102,144 @@ public class RegisterIsoCmd extends BaseCmd { @Override public String getName() { return s_name; - } - @Override - public List> getProperties() { - return s_properties; - } - - @Override - public List> execute(Map params) { - Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName()); - Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName()); - String name = (String)params.get(BaseCmd.Properties.NAME.getName()); - String displayText = (String)params.get(BaseCmd.Properties.DISPLAY_TEXT.getName()); - String url = (String)params.get(BaseCmd.Properties.URL.getName()); - Boolean isPublic = (Boolean)params.get(BaseCmd.Properties.IS_PUBLIC.getName()); - Boolean featured = (Boolean)params.get(BaseCmd.Properties.IS_FEATURED.getName()); - Long guestOSId = (Long) params.get(BaseCmd.Properties.OS_TYPE_ID.getName()); - Boolean bootable = (Boolean) params.get(BaseCmd.Properties.BOOTABLE.getName()); - Long zoneId = (Long) params.get(BaseCmd.Properties.ZONE_ID.getName()); - - if (isPublic == null) { - isPublic = Boolean.FALSE; - } - - if (zoneId.longValue() == -1) { - zoneId = null; - } - - long accountId = 1L; // default to system account - if (account != null) { - accountId = account.getId().longValue(); - } - - Account accountObj; - if (account == null) { - accountObj = getManagementServer().findAccountById(accountId); - } else { - accountObj = account; - } - - boolean isAdmin = (accountObj.getType() == Account.ACCOUNT_TYPE_ADMIN); - - if (!isAdmin && zoneId == null) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid zone Id."); - } - - if((!url.toLowerCase().endsWith("iso"))&&(!url.toLowerCase().endsWith("iso.zip"))&&(!url.toLowerCase().endsWith("iso.bz2")) - &&(!url.toLowerCase().endsWith("iso.gz"))){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid iso"); - } - - boolean allowPublicUserTemplates = Boolean.parseBoolean(getManagementServer().getConfigurationValue("allow.public.user.templates")); - if (!isAdmin && !allowPublicUserTemplates && isPublic) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Only private ISOs can be created."); - } - - if (!isAdmin || featured == null) { - featured = Boolean.FALSE; - } - - // If command is executed via 8096 port, set userId to the id of System account (1) - if (userId == null) { - userId = Long.valueOf(1); - } - - if (bootable == null) { - bootable = Boolean.TRUE; - } + } - //removing support for file:// type urls (bug: 4239) - if(url.toLowerCase().contains("file://")){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "File:// type urls are currently unsupported"); - } - - Long templateId; - try { - templateId = getManagementServer().createTemplate(userId, zoneId, name, displayText, isPublic.booleanValue(), featured.booleanValue(), ImageFormat.ISO.toString(), FileSystem.cdfs.toString(), url, null, true, 64 /*bits*/, false, guestOSId, bootable); - } catch (Exception ex) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } - - - VMTemplateVO template = getManagementServer().findTemplateById(templateId); - List> isoTags = new ArrayList>(); - List iTagList = new ArrayList(); - if (template != null) { - List zones = null; - - if (zoneId != null) { - zones = new ArrayList(); - zones.add(getManagementServer().findDataCenterById(zoneId)); - } else { - zones = getManagementServer().listDataCenters(); - } - - for (DataCenterVO zone : zones) { - VMTemplateHostVO isoHostRef = getManagementServer().findTemplateHostRef(templateId, zone.getId()); + @Override + public String getResponse() { + // TODO Auto-generated method stub + return null; + } - // Use embeded object for response - List> listForEmbeddedObject = new ArrayList>(); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ID.getName(), template.getId().toString())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.NAME.getName(), template.getName())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.DISPLAY_TEXT.getName(), template.getDisplayText())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.IS_PUBLIC.getName(), Boolean.valueOf(template.isPublicTemplate()).toString())); - - if (isoHostRef != null) { - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.CREATED.getName(), getDateString(isoHostRef.getCreated()))); - } - - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.IS_READY.getName(), (isoHostRef != null && isoHostRef.getDownloadState() == Status.DOWNLOADED))); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.IS_FEATURED.getName(), Boolean.valueOf(template.isFeatured()).toString())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.BOOTABLE.getName(), Boolean.valueOf(template.isBootable()).toString())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.OS_TYPE_ID.getName(), template.getGuestOSId())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.OS_TYPE_NAME.getName(), getManagementServer().findGuestOSById(template.getGuestOSId()).getName())); - - Account owner = getManagementServer().findAccountById(template.getAccountId()); - if (owner != null) { - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ACCOUNT_ID.getName(), owner.getId())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ACCOUNT.getName(), owner.getAccountName())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.DOMAIN_ID.getName(), owner.getDomainId())); - } - - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ZONE_ID.getName(), zone.getId())); - listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ZONE_NAME.getName(), zone.getName())); - - iTagList.add(listForEmbeddedObject); - } - } - - Object[] iTag = new Object[iTagList.size()]; - for (int i = 0; i < iTagList.size(); i++) { - iTag[i] = iTagList.get(i); - } - - Pair templateTag = new Pair("iso", iTag); - isoTags.add(templateTag); - - return isoTags; - } +// @Override +// public List> execute(Map params) { +// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName()); +// Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName()); +// String name = (String)params.get(BaseCmd.Properties.NAME.getName()); +// String displayText = (String)params.get(BaseCmd.Properties.DISPLAY_TEXT.getName()); +// String url = (String)params.get(BaseCmd.Properties.URL.getName()); +// Boolean isPublic = (Boolean)params.get(BaseCmd.Properties.IS_PUBLIC.getName()); +// Boolean featured = (Boolean)params.get(BaseCmd.Properties.IS_FEATURED.getName()); +// Long guestOSId = (Long) params.get(BaseCmd.Properties.OS_TYPE_ID.getName()); +// Boolean bootable = (Boolean) params.get(BaseCmd.Properties.BOOTABLE.getName()); +// Long zoneId = (Long) params.get(BaseCmd.Properties.ZONE_ID.getName()); +// +// if (isPublic == null) { +// isPublic = Boolean.FALSE; +// } +// +// if (zoneId.longValue() == -1) { +// zoneId = null; +// } +// +// long accountId = 1L; // default to system account +// if (account != null) { +// accountId = account.getId().longValue(); +// } +// +// Account accountObj; +// if (account == null) { +// accountObj = getManagementServer().findAccountById(accountId); +// } else { +// accountObj = account; +// } +// +// boolean isAdmin = (accountObj.getType() == Account.ACCOUNT_TYPE_ADMIN); +// +// if (!isAdmin && zoneId == null) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid zone Id."); +// } +// +// if((!url.toLowerCase().endsWith("iso"))&&(!url.toLowerCase().endsWith("iso.zip"))&&(!url.toLowerCase().endsWith("iso.bz2")) +// &&(!url.toLowerCase().endsWith("iso.gz"))){ +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid iso"); +// } +// +// boolean allowPublicUserTemplates = Boolean.parseBoolean(getManagementServer().getConfigurationValue("allow.public.user.templates")); +// if (!isAdmin && !allowPublicUserTemplates && isPublic) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Only private ISOs can be created."); +// } +// +// if (!isAdmin || featured == null) { +// featured = Boolean.FALSE; +// } +// +// // If command is executed via 8096 port, set userId to the id of System account (1) +// if (userId == null) { +// userId = Long.valueOf(1); +// } +// +// if (bootable == null) { +// bootable = Boolean.TRUE; +// } +// +// //removing support for file:// type urls (bug: 4239) +// if(url.toLowerCase().contains("file://")){ +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "File:// type urls are currently unsupported"); +// } +// +// Long templateId; +// try { +// templateId = getManagementServer().createTemplate(userId, zoneId, name, displayText, isPublic.booleanValue(), featured.booleanValue(), ImageFormat.ISO.toString(), FileSystem.cdfs.toString(), url, null, true, 64 /*bits*/, false, guestOSId, bootable); +// } catch (Exception ex) { +// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); +// } +// +// +// VMTemplateVO template = getManagementServer().findTemplateById(templateId); +// List> isoTags = new ArrayList>(); +// List iTagList = new ArrayList(); +// if (template != null) { +// List zones = null; +// +// if (zoneId != null) { +// zones = new ArrayList(); +// zones.add(getManagementServer().findDataCenterById(zoneId)); +// } else { +// zones = getManagementServer().listDataCenters(); +// } +// +// for (DataCenterVO zone : zones) { +// VMTemplateHostVO isoHostRef = getManagementServer().findTemplateHostRef(templateId, zone.getId()); +// +// // Use embeded object for response +// List> listForEmbeddedObject = new ArrayList>(); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ID.getName(), template.getId().toString())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.NAME.getName(), template.getName())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.DISPLAY_TEXT.getName(), template.getDisplayText())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.IS_PUBLIC.getName(), Boolean.valueOf(template.isPublicTemplate()).toString())); +// +// if (isoHostRef != null) { +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.CREATED.getName(), getDateString(isoHostRef.getCreated()))); +// } +// +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.IS_READY.getName(), (isoHostRef != null && isoHostRef.getDownloadState() == Status.DOWNLOADED))); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.IS_FEATURED.getName(), Boolean.valueOf(template.isFeatured()).toString())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.BOOTABLE.getName(), Boolean.valueOf(template.isBootable()).toString())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.OS_TYPE_ID.getName(), template.getGuestOSId())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.OS_TYPE_NAME.getName(), getManagementServer().findGuestOSById(template.getGuestOSId()).getName())); +// +// Account owner = getManagementServer().findAccountById(template.getAccountId()); +// if (owner != null) { +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ACCOUNT_ID.getName(), owner.getId())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ACCOUNT.getName(), owner.getAccountName())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.DOMAIN_ID.getName(), owner.getDomainId())); +// } +// +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ZONE_ID.getName(), zone.getId())); +// listForEmbeddedObject.add(new Pair(BaseCmd.Properties.ZONE_NAME.getName(), zone.getName())); +// +// iTagList.add(listForEmbeddedObject); +// } +// } +// +// Object[] iTag = new Object[iTagList.size()]; +// for (int i = 0; i < iTagList.size(); i++) { +// iTag[i] = iTagList.get(i); +// } +// +// Pair templateTag = new Pair("iso", iTag); +// isoTags.add(templateTag); +// +// return isoTags; +// } } diff --git a/server/src/com/cloud/template/TemplateManager.java b/server/src/com/cloud/template/TemplateManager.java index cd6e6463e4e..26779432a56 100644 --- a/server/src/com/cloud/template/TemplateManager.java +++ b/server/src/com/cloud/template/TemplateManager.java @@ -22,6 +22,7 @@ import java.net.URISyntaxException; import java.util.List; import com.cloud.api.commands.CreateTemplateCmd; +import com.cloud.api.commands.RegisterIsoCmd; import com.cloud.api.commands.RegisterTemplateCmd; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; @@ -67,7 +68,7 @@ public interface TemplateManager extends Manager { */ Long create(long userId, Long zoneId, String name, String displayText, boolean isPublic, boolean featured, ImageFormat format, FileSystem fs, URI url, String chksum, boolean requiresHvm, int bits, boolean enablePassword, long guestOSId, boolean bootable); Long registerTemplate(RegisterTemplateCmd cmd) throws InvalidParameterValueException, URISyntaxException, ResourceAllocationException; - + Long registerIso(RegisterIsoCmd cmd) throws InvalidParameterValueException, IllegalArgumentException, ResourceAllocationException; /** * Creates a Template * diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index e352cf25bae..45665947408 100644 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -23,6 +23,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -38,6 +39,7 @@ import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.manager.AgentManager; import com.cloud.api.BaseCmd; import com.cloud.api.ServerApiException; +import com.cloud.api.commands.RegisterIsoCmd; import com.cloud.api.commands.RegisterTemplateCmd; import com.cloud.configuration.ResourceCount.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; @@ -122,6 +124,75 @@ public class TemplateManagerImpl implements TemplateManager { @Inject ConfigurationDao _configDao; protected SearchBuilder HostTemplateStatesSearch; + @Override + public Long registerIso(RegisterIsoCmd cmd) throws InvalidParameterValueException, IllegalArgumentException, ResourceAllocationException{ + Account account = (Account)UserContext.current().getAccountObject(); + Long userId = UserContext.current().getUserId(); + String name = cmd.getName(); + String displayText = cmd.getDisplayText(); + String url = cmd.getUrl(); + Boolean isPublic = cmd.isPublic(); + Boolean featured = cmd.isFeatured(); + Long guestOSId = cmd.getOsTypeId(); + Boolean bootable = cmd.isBootable(); + Long zoneId = cmd.getZoneId(); + + if (isPublic == null) { + isPublic = Boolean.FALSE; + } + + if (zoneId.longValue() == -1) { + zoneId = null; + } + + long accountId = 1L; // default to system account + if (account != null) { + accountId = account.getId().longValue(); + } + + Account accountObj; + if (account == null) { + accountObj = _accountDao.findById(accountId); + } else { + accountObj = account; + } + + boolean isAdmin = (accountObj.getType() == Account.ACCOUNT_TYPE_ADMIN); + + if (!isAdmin && zoneId == null) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid zone Id."); + } + + if((!url.toLowerCase().endsWith("iso"))&&(!url.toLowerCase().endsWith("iso.zip"))&&(!url.toLowerCase().endsWith("iso.bz2")) + &&(!url.toLowerCase().endsWith("iso.gz"))){ + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid iso"); + } + + boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); + if (!isAdmin && !allowPublicUserTemplates && isPublic) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Only private ISOs can be created."); + } + + if (!isAdmin || featured == null) { + featured = Boolean.FALSE; + } + + // If command is executed via 8096 port, set userId to the id of System account (1) + if (userId == null) { + userId = Long.valueOf(1); + } + + if (bootable == null) { + bootable = Boolean.TRUE; + } + + //removing support for file:// type urls (bug: 4239) + if(url.toLowerCase().contains("file://")){ + throw new ServerApiException(BaseCmd.PARAM_ERROR, "File:// type urls are currently unsupported"); + } + + return createTemplateOrIso(userId, zoneId, name, displayText, isPublic.booleanValue(), featured.booleanValue(), ImageFormat.ISO.toString(), FileSystem.cdfs.toString(), url, null, true, 64 /*bits*/, false, guestOSId, bootable); + } @Override public Long registerTemplate(RegisterTemplateCmd cmd) throws InvalidParameterValueException, URISyntaxException, ResourceAllocationException{ @@ -201,74 +272,83 @@ public class TemplateManagerImpl implements TemplateManager { userId = Long.valueOf(1); } - if (name.length() > 32) - { - throw new InvalidParameterValueException("Template name should be less than 32 characters"); - } - - if (!name.matches("^[\\p{Alnum} ._-]+")) { - throw new InvalidParameterValueException("Only alphanumeric, space, dot, dashes and underscore characters allowed"); - } - - ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); - if (imgfmt == null) { - throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); - } - - FileSystem fileSystem = FileSystem.valueOf("ext3"); - if (fileSystem == null) { - throw new IllegalArgumentException("File system is incorrect " + "ext3" + ". Supported file systems are " + EnumUtils.listValues(FileSystem.values())); - } - - URI uri = new URI(url); - if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { - throw new IllegalArgumentException("Unsupported scheme for url: " + url); - } - int port = uri.getPort(); - if (!(port == 80 || port == 443 || port == -1)) { - throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); - } - String host = uri.getHost(); - try { - InetAddress hostAddr = InetAddress.getByName(host); - if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress() ) { - throw new IllegalArgumentException("Illegal host specified in url"); - } - if (hostAddr instanceof Inet6Address) { - throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); - } - } catch (UnknownHostException uhe) { - throw new IllegalArgumentException("Unable to resolve " + host); - } - - // Check that the resource limit for templates/ISOs won't be exceeded - UserVO user = _userDao.findById(userId); - if (user == null) { - throw new IllegalArgumentException("Unable to find user with id " + userId); - } - - AccountVO accountVO = _accountDao.findById(user.getAccountId()); - if (_accountMgr.resourceLimitExceeded(accountVO, ResourceType.template)) { - ResourceAllocationException rae = new ResourceAllocationException("Maximum number of templates and ISOs for account: " + account.getAccountName() + " has been exceeded."); - rae.setResourceType("template"); - throw rae; - } - - // If a zoneId is specified, make sure it is valid - if (zoneId != null) { - if (_dcDao.findById(zoneId) == null) { - throw new IllegalArgumentException("Please specify a valid zone."); - } - } - VMTemplateVO systemvmTmplt = _tmpltDao.findRoutingTemplate(); - if (systemvmTmplt.getName().equalsIgnoreCase(name) || systemvmTmplt.getDisplayText().equalsIgnoreCase(displayText)) { - throw new IllegalArgumentException("Cannot use reserved names for templates"); - } - - return create(userId, zoneId, name, displayText, isPublic, featured, imgfmt, fileSystem, uri, null, requiresHVM, bits, passwordEnabled, guestOSId, true); + return createTemplateOrIso(userId, zoneId, name, displayText, isPublic, featured, format, "ext3", url, null, requiresHVM, bits, passwordEnabled, guestOSId, true); } + private Long createTemplateOrIso(long userId, Long zoneId, String name, String displayText, boolean isPublic, boolean featured, String format, String diskType, String url, String chksum, boolean requiresHvm, int bits, boolean enablePassword, long guestOSId, boolean bootable) throws InvalidParameterValueException,IllegalArgumentException, ResourceAllocationException { + try + { + if (name.length() > 32) + { + throw new InvalidParameterValueException("Template name should be less than 32 characters"); + } + + if (!name.matches("^[\\p{Alnum} ._-]+")) { + throw new InvalidParameterValueException("Only alphanumeric, space, dot, dashes and underscore characters allowed"); + } + + ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); + if (imgfmt == null) { + throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + } + + FileSystem fileSystem = FileSystem.valueOf(diskType); + if (fileSystem == null) { + throw new IllegalArgumentException("File system is incorrect " + diskType + ". Supported file systems are " + EnumUtils.listValues(FileSystem.values())); + } + + URI uri = new URI(url); + if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { + throw new IllegalArgumentException("Unsupported scheme for url: " + url); + } + int port = uri.getPort(); + if (!(port == 80 || port == 443 || port == -1)) { + throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); + } + String host = uri.getHost(); + try { + InetAddress hostAddr = InetAddress.getByName(host); + if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress() ) { + throw new IllegalArgumentException("Illegal host specified in url"); + } + if (hostAddr instanceof Inet6Address) { + throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); + } + } catch (UnknownHostException uhe) { + throw new IllegalArgumentException("Unable to resolve " + host); + } + + // Check that the resource limit for templates/ISOs won't be exceeded + UserVO user = _userDao.findById(userId); + if (user == null) { + throw new IllegalArgumentException("Unable to find user with id " + userId); + } + AccountVO account = _accountDao.findById(user.getAccountId()); + if (_accountMgr.resourceLimitExceeded(account, ResourceType.template)) { + ResourceAllocationException rae = new ResourceAllocationException("Maximum number of templates and ISOs for account: " + account.getAccountName() + " has been exceeded."); + rae.setResourceType("template"); + throw rae; + } + + // If a zoneId is specified, make sure it is valid + if (zoneId != null) { + if (_dcDao.findById(zoneId) == null) { + throw new IllegalArgumentException("Please specify a valid zone."); + } + } + VMTemplateVO systemvmTmplt = _tmpltDao.findRoutingTemplate(); + if (systemvmTmplt.getName().equalsIgnoreCase(name) || systemvmTmplt.getDisplayText().equalsIgnoreCase(displayText)) { + throw new IllegalArgumentException("Cannot use reserved names for templates"); + } + + return create(userId, zoneId, name, displayText, isPublic, featured, imgfmt, fileSystem, uri, chksum, requiresHvm, bits, enablePassword, guestOSId, bootable); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid URL " + url); + } + } + + @Override public Long create(long userId, Long zoneId, String name, String displayText, boolean isPublic, boolean featured, ImageFormat format, FileSystem fs, URI url, String chksum, boolean requiresHvm, int bits, boolean enablePassword, long guestOSId, boolean bootable) { Long id = _tmpltDao.getNextInSequence(Long.class, "id");