From 16cccf4f590a822ea6b0f7bc48332f571ab7a9d2 Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Sat, 4 Dec 2010 16:46:30 -0800 Subject: [PATCH] ip address modifications. removed old deploy --- .../com/cloud/api/commands/DeployVMCmd.java | 47 +- .../com/cloud/api/commands/DeployVm2Cmd.java | 232 -------- .../com/cloud/server/ManagementService.java | 36 -- api/src/com/cloud/vm/UserVmService.java | 3 +- server/src/com/cloud/dc/dao/VlanDaoImpl.java | 4 +- .../com/cloud/network/dao/IPAddressDao.java | 6 +- .../cloud/network/dao/IPAddressDaoImpl.java | 61 +- .../router/DomainRouterManagerImpl.java | 2 +- .../com/cloud/server/ManagementServer.java | 9 - .../cloud/server/ManagementServerImpl.java | 555 ------------------ .../src/com/cloud/vm/UserVmManagerImpl.java | 10 +- 11 files changed, 65 insertions(+), 900 deletions(-) delete mode 100644 api/src/com/cloud/api/commands/DeployVm2Cmd.java diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java index 0e3c9a5e9b3..e4e4fe6cee6 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/com/cloud/api/commands/DeployVMCmd.java @@ -23,7 +23,7 @@ import java.util.List; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.BaseAsyncCreateCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; @@ -33,16 +33,13 @@ import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -import com.cloud.utils.exception.ExecutionException; @Implementation(description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class) -public class DeployVMCmd extends BaseAsyncCmd { +public class DeployVMCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); private static final String s_name = "deployvirtualmachineresponse"; @@ -205,41 +202,49 @@ public class DeployVMCmd extends BaseAsyncCmd { return "deploying Vm"; } + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.VirtualMachine; } @Override public void execute(){ + UserVm result; try { - String password = null; - if (templateId != null ) { - VirtualMachineTemplate template = _responseGenerator.findTemplateById(templateId); - if (template.getEnablePassword()) { - password = _mgr.generateRandomPassword(); - } - } - UserVm result = _mgr.deployVirtualMachine(this, password); - if (result != null){ - UserVmResponse response = _responseGenerator.createUserVmResponse(result); + result = _userVmService.startVirtualMachine(this); + if (result != null) { + UserVmResponse response = _responseGenerator.createUserVm2Response(result); response.setPassword(password); response.setResponseName(getName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); } - } catch (ResourceAllocationException ex) { - s_logger.info(ex); - throw new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); + } catch (ResourceUnavailableException ex) { + throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + } catch (ConcurrentOperationException ex) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + } catch (InsufficientCapacityException ex) { + throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + } + } + + @Override + public void callCreate() { + try { + UserVm result = _userVmService.createVirtualMachine(this); + if (result != null){ + setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); + } } catch (InsufficientCapacityException ex) { s_logger.info(ex); + s_logger.trace(ex); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); - } catch (ExecutionException ex) { - s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); diff --git a/api/src/com/cloud/api/commands/DeployVm2Cmd.java b/api/src/com/cloud/api/commands/DeployVm2Cmd.java deleted file mode 100644 index a42bbe159e0..00000000000 --- a/api/src/com/cloud/api/commands/DeployVm2Cmd.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. - * - * This software is licensed under the GNU General Public License v3 or later. - * - * It is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package com.cloud.api.commands; - -import java.util.List; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -import com.cloud.uservm.UserVm; - -@Implementation(description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class) -public class DeployVm2Cmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); - - private static final String s_name = "deployvirtualmachineresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the virtual machine. Must be used with domainId.") - private String accountName; - - @Parameter(name=ApiConstants.DISK_OFFERING_ID, type=CommandType.LONG, description="the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to dinidcate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") - private Long diskOfferingId; - - @Parameter(name=ApiConstants.DISPLAY_NAME, type=CommandType.STRING, description="an optional user generated name for the virtual machine") - private String displayName; - - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") - private Long domainId; - - @Parameter(name=ApiConstants.GROUP, type=CommandType.STRING, description="an optional group for the virtual machine") - private String group; - - @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor on which to deploy the virtual machine") - private String hypervisor; - - @Parameter(name=ApiConstants.NETWORK_GROUP_LIST, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of network groups that going to be applied to the virtual machine. Should be passed only when vm is created from service offering with Direct Attach Network support") - private List networkGroupList; - - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the ID of the service offering for the virtual machine") - private Long serviceOfferingId; - - @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, description="the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId") - private Long size; - - @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, required=true, description="the ID of the template for the virtual machine") - private Long templateId; - - @Parameter(name=ApiConstants.USER_DATA, type=CommandType.STRING, description="an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding.") - private String userData; - - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="availability zone for the virtual machine") - private Long zoneId; - - // unexposed parameter needed for serializing/deserializing the command - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, expose=false) - private String password; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getAccountName() { - return accountName; - } - - public Long getDiskOfferingId() { - return diskOfferingId; - } - - public String getDisplayName() { - return displayName; - } - - public Long getDomainId() { - return domainId; - } - - public String getGroup() { - return group; - } - - public String getHypervisor() { - return hypervisor; - } - - public List getNetworkGroupList() { - return networkGroupList; - } - - public Long getServiceOfferingId() { - return serviceOfferingId; - } - - public Long getSize() { - return size; - } - - public Long getTemplateId() { - return templateId; - } - - public String getUserData() { - return userData; - } - - public Long getZoneId() { - return zoneId; - } - - // not exposed parameter - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - @Override - public void execute(){ - UserVm result; - try { - result = _userVmService.startVirtualMachine(this); - if (result != null) { - UserVmResponse response = _responseGenerator.createUserVm2Response(result); - response.setPassword(password); - response.setResponseName(getName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); - } - } catch (ResourceUnavailableException ex) { - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); - } catch (ConcurrentOperationException ex) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } catch (InsufficientCapacityException ex) { - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); - } - } - - @Override - public void callCreate() { -// try { -// UserVm vm = _userVmService.createVirtualMachine(this); -// if (vm != null) { -// this.setId(vm.getId()); -// } else { -// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); -// } -// } catch (ResourceUnavailableException ex) { -// throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); -// } catch (ConcurrentOperationException ex) { -// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); -// } catch (InsufficientCapacityException ex) { -// throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); -// } - } - - - @Override - public String getName() { - return s_name; - } - - public static String getResultObjectName() { - return "virtualmachine"; - } - - @Override - public long getEntityOwnerId() { - Account account = UserContext.current().getAccount(); - if ((account == null) || isAdmin(account.getType())) { - if ((domainId != null) && (accountName != null)) { - Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId); - if (userAccount != null) { - return userAccount.getId(); - } - } - } - - if (account != null) { - return account.getId(); - } - - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked - } - - @Override - public String getEventType() { - return EventTypes.EVENT_VM_CREATE; - } - - @Override - public String getEventDescription() { - return "deploying Vm"; - } -} diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 009fe7ae061..ebb3cdc97a0 100644 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -27,7 +27,6 @@ import com.cloud.api.ServerApiException; import com.cloud.api.commands.CreateDomainCmd; import com.cloud.api.commands.DeleteDomainCmd; import com.cloud.api.commands.DeletePreallocatedLunCmd; -import com.cloud.api.commands.DeployVMCmd; import com.cloud.api.commands.ExtractVolumeCmd; import com.cloud.api.commands.GetCloudIdentifierCmd; import com.cloud.api.commands.ListAccountsCmd; @@ -52,7 +51,6 @@ import com.cloud.api.commands.ListPublicIpAddressesCmd; import com.cloud.api.commands.ListRemoteAccessVpnsCmd; import com.cloud.api.commands.ListRoutersCmd; import com.cloud.api.commands.ListServiceOfferingsCmd; -import com.cloud.api.commands.ListSnapshotsCmd; import com.cloud.api.commands.ListStoragePoolsCmd; import com.cloud.api.commands.ListSystemVMsCmd; import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; @@ -84,15 +82,9 @@ import com.cloud.dc.Pod; import com.cloud.dc.Vlan; import com.cloud.domain.Domain; import com.cloud.event.Event; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.network.IpAddress; import com.cloud.network.RemoteAccessVpn; @@ -103,14 +95,12 @@ import com.cloud.offering.ServiceOffering; import com.cloud.org.Cluster; import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOsCategory; -import com.cloud.storage.Snapshot; import com.cloud.storage.StoragePool; import com.cloud.storage.Volume; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserAccount; import com.cloud.uservm.UserVm; -import com.cloud.utils.exception.ExecutionException; import com.cloud.vm.InstanceGroup; import com.cloud.vm.VirtualMachine; @@ -121,30 +111,6 @@ import com.cloud.vm.VirtualMachine; public interface ManagementService { static final String Name = "management-server"; - /** - * Creates and starts a new Virtual Machine. - * - * @param cmd the command with the deployment parameters - * - userId - * - accountId - * - zoneId - * - serviceOfferingId - * - templateId: the id of the template (or ISO) to use for creating the virtual machine - * - diskOfferingId: ID of the disk offering to use when creating the root disk (if deploying from an ISO) or the data disk (if deploying from a template). If deploying from a template and a disk offering ID is not passed in, the VM will have only a root disk. - * - displayName: user-supplied name to be shown in the UI or returned in the API - * - groupName: user-supplied groupname to be shown in the UI or returned in the API - * - userData: user-supplied base64-encoded data that can be retrieved by the instance from the virtual router - * - size: size to be used for volume creation in case the disk offering is private (i.e. size=0) - * @return VirtualMachine if successfully deployed, null otherwise - * @throws InvalidParameterValueException if the parameter values are incorrect. - * @throws ExecutionException - * @throws StorageUnavailableException - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException - * @throws InsufficientCapacityException - */ - UserVm deployVirtualMachine(DeployVMCmd cmd, String password) throws ResourceAllocationException, InsufficientStorageCapacityException, ExecutionException, StorageUnavailableException, ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException; - /** * Retrieves the list of data centers with search criteria. * Currently the only search criteria is "available" zones for the account that invokes the API. By specifying @@ -450,6 +416,4 @@ public interface ManagementService { */ boolean unregisterPreallocatedLun(DeletePreallocatedLunCmd cmd) throws IllegalArgumentException; - - } diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java index 1d32258c9d2..bc73f6a4d3f 100755 --- a/api/src/com/cloud/vm/UserVmService.java +++ b/api/src/com/cloud/vm/UserVmService.java @@ -23,7 +23,6 @@ import com.cloud.api.commands.CreateTemplateCmd; import com.cloud.api.commands.CreateVMGroupCmd; import com.cloud.api.commands.DeleteVMGroupCmd; import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DeployVm2Cmd; import com.cloud.api.commands.DestroyVMCmd; import com.cloud.api.commands.DetachVolumeCmd; import com.cloud.api.commands.RebootVMCmd; @@ -133,7 +132,7 @@ public interface UserVmService { * @throws ConcurrentOperationException if there are multiple users working on the same VM. * @throws ResourceUnavailableException if the resources required the deploy the VM is not currently available. */ - UserVm startVirtualMachine(DeployVm2Cmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException; + UserVm startVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException; /** * Creates a vm group. diff --git a/server/src/com/cloud/dc/dao/VlanDaoImpl.java b/server/src/com/cloud/dc/dao/VlanDaoImpl.java index d3ff641396a..14d1419a06c 100644 --- a/server/src/com/cloud/dc/dao/VlanDaoImpl.java +++ b/server/src/com/cloud/dc/dao/VlanDaoImpl.java @@ -240,7 +240,7 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao if (vlan == null) { return null; } - String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), sourceNat); + String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), sourceNat).getAddress(); if (ipAddress == null) { return null; } @@ -270,7 +270,7 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao return null; } - String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false); + String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress(); if (ipAddress == null) { return null; } diff --git a/server/src/com/cloud/network/dao/IPAddressDao.java b/server/src/com/cloud/network/dao/IPAddressDao.java index e87e9e3558a..73b1d45327c 100644 --- a/server/src/com/cloud/network/dao/IPAddressDao.java +++ b/server/src/com/cloud/network/dao/IPAddressDao.java @@ -18,8 +18,8 @@ package com.cloud.network.dao; -import java.util.List; - +import java.util.List; + import com.cloud.network.IPAddressVO; import com.cloud.utils.db.GenericDao; @@ -32,7 +32,7 @@ public interface IPAddressDao extends GenericDao { * @param sourceNat is it for source nat? * @return public ip address */ - public String assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat); + public IPAddressVO assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat); public void unassignIpAddress(String ipAddress); diff --git a/server/src/com/cloud/network/dao/IPAddressDaoImpl.java b/server/src/com/cloud/network/dao/IPAddressDaoImpl.java index b77b58e0bc2..6de4878c7f4 100644 --- a/server/src/com/cloud/network/dao/IPAddressDaoImpl.java +++ b/server/src/com/cloud/network/dao/IPAddressDaoImpl.java @@ -31,6 +31,7 @@ import org.apache.log4j.Logger; import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress.State; import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; @@ -56,6 +57,7 @@ public class IPAddressDaoImpl extends GenericDaoBase implem AllFieldsSearch.and("ipAddress", AllFieldsSearch.entity().getAddress(), SearchCriteria.Op.EQ); AllFieldsSearch.and("vlan", AllFieldsSearch.entity().getVlanId(), Op.EQ); AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAllocatedToAccountId(), Op.EQ); + AllFieldsSearch.and("sourceNat", AllFieldsSearch.entity().isSourceNat(), SearchCriteria.Op.EQ); AllFieldsSearch.done(); VlanDbIdSearchUnallocated = createSearchBuilder(); @@ -85,6 +87,7 @@ public class IPAddressDaoImpl extends GenericDaoBase implem IPAddressVO vo = createForUpdate(); vo.setAllocatedTime(new Date()); + vo.setState(State.Allocated); return update(vo, sc) >= 1; } @@ -92,42 +95,30 @@ public class IPAddressDaoImpl extends GenericDaoBase implem @Override @DB public List assignAcccountSpecificIps(long accountId, long domainId, Long vlanDbId, boolean sourceNat) { - - SearchBuilder VlanDbIdSearch = createSearchBuilder(); - VlanDbIdSearch.and("vlanDbId", VlanDbIdSearch.entity().getVlanId(), SearchCriteria.Op.EQ); - VlanDbIdSearch.and("sourceNat", VlanDbIdSearch.entity().isSourceNat(), SearchCriteria.Op.EQ); - VlanDbIdSearch.done(); Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - SearchCriteria sc = VlanDbIdSearch.create(); - sc.setParameters("vlanDbId", vlanDbId); - sc.setParameters("sourceNat", sourceNat); + txn.start(); + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("vlan", vlanDbId); + sc.setParameters("sourceNat", sourceNat); - List ipList = this.lockRows(sc, null, true); - List ipStringList = new ArrayList(); + List ipList = lockRows(sc, null, true); + List ipStringList = new ArrayList(); - for (IPAddressVO ip : ipList) { + for (IPAddressVO ip : ipList) { - ip.setAllocatedToAccountId(accountId); - ip.setAllocatedTime(new Date()); - ip.setAllocatedInDomainId(domainId); - ip.setSourceNat(sourceNat); - ip.setState(State.Allocated); + ip.setAllocatedToAccountId(accountId); + ip.setAllocatedTime(new Date()); + ip.setAllocatedInDomainId(domainId); + ip.setSourceNat(sourceNat); + ip.setState(State.Allocated); - if (!update(ip.getAddress(), ip)) { - s_logger.debug("Unable to retrieve ip address " + ip.getAddress()); - return null; - } - ipStringList.add(ip.getAddress()); + if (!update(ip.getAddress(), ip)) { + throw new CloudRuntimeException("Unable to update a locked ip address " + ip.getAddress()); } - txn.commit(); - return ipStringList; - } catch (Exception e) { - s_logger.warn("Unable to assign IP", e); + ipStringList.add(ip.getAddress()); } - return null; - + txn.commit(); + return ipStringList; } @Override @@ -141,18 +132,22 @@ public class IPAddressDaoImpl extends GenericDaoBase implem @Override @DB - public String assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat) { + public IPAddressVO assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat) { Transaction txn = Transaction.currentTxn(); txn.start(); SearchCriteria sc = VlanDbIdSearchUnallocated.create(); sc.setParameters("vlanDbId", vlanDbId); + + Filter filter = new Filter(IPAddressVO.class, "vlanId", true, 0l, 1l); - IPAddressVO ip = this.lockOneRandomRow(sc, true); - if (ip == null) { + List ips = this.lockRows(sc, filter, true); + if (ips.size() == 0) { s_logger.info("Unable to get an ip address in " + vlanDbId); return null; } + + IPAddressVO ip = ips.get(0); ip.setAllocatedToAccountId(accountId); ip.setAllocatedTime(new Date()); @@ -165,7 +160,7 @@ public class IPAddressDaoImpl extends GenericDaoBase implem } txn.commit(); - return ip.getAddress(); + return ip; } @Override diff --git a/server/src/com/cloud/network/router/DomainRouterManagerImpl.java b/server/src/com/cloud/network/router/DomainRouterManagerImpl.java index af7458d8074..3bc81f488f3 100644 --- a/server/src/com/cloud/network/router/DomainRouterManagerImpl.java +++ b/server/src/com/cloud/network/router/DomainRouterManagerImpl.java @@ -316,7 +316,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return rtrs.get(0); } String mgmtNetmask = NetUtils.getCidrNetmask(pod.getCidrSize()); - final String guestIp = _ipAddressDao.assignIpAddress(accountIdForDHCPServer, domainIdForDHCPServer, guestVlan.getId(), false); + final String guestIp = _ipAddressDao.assignIpAddress(accountIdForDHCPServer, domainIdForDHCPServer, guestVlan.getId(), false).getAddress(); router = new DomainRouterVO(id, diff --git a/server/src/com/cloud/server/ManagementServer.java b/server/src/com/cloud/server/ManagementServer.java index fbc22baeb30..fb9591144c4 100755 --- a/server/src/com/cloud/server/ManagementServer.java +++ b/server/src/com/cloud/server/ManagementServer.java @@ -39,7 +39,6 @@ import com.cloud.network.security.NetworkGroupVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOSVO; -import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.StorageStats; import com.cloud.storage.VMTemplateVO; @@ -163,14 +162,6 @@ public interface ManagementServer extends ManagementService { */ boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach, long startEventId); - /** - * Finds a domain router by id - * @param router id - * @return a domainRouter - */ - DomainRouterVO findDomainRouterById(long domainRouterId); - - /** * Retrieves a host by id * @param hostId diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 869307d2433..0652385eadd 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -36,17 +36,14 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.Executors; @@ -78,8 +75,6 @@ import com.cloud.api.ServerApiException; import com.cloud.api.commands.CreateDomainCmd; import com.cloud.api.commands.DeleteDomainCmd; import com.cloud.api.commands.DeletePreallocatedLunCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DeployVm2Cmd; import com.cloud.api.commands.ExtractVolumeCmd; import com.cloud.api.commands.GetCloudIdentifierCmd; import com.cloud.api.commands.ListAccountsCmd; @@ -171,17 +166,11 @@ import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.CloudAuthenticationException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ManagementServerException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; @@ -197,7 +186,6 @@ import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.dao.VpnUserDao; -import com.cloud.network.security.NetworkGroupManager; import com.cloud.network.security.NetworkGroupVO; import com.cloud.network.security.dao.NetworkGroupDao; import com.cloud.offering.NetworkOffering; @@ -245,20 +233,16 @@ import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserAccountVO; import com.cloud.user.UserContext; -import com.cloud.user.UserStatisticsVO; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; -import com.cloud.user.dao.UserStatisticsDao; -import com.cloud.uservm.UserVm; import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -269,7 +253,6 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; import com.cloud.vm.ConsoleProxyVO; @@ -280,7 +263,6 @@ import com.cloud.vm.NicVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; import com.cloud.vm.UserVmManager; -import com.cloud.vm.UserVmService; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; @@ -315,7 +297,6 @@ public class ManagementServerImpl implements ManagementServer { private final UserDao _userDao; private final UserVmDao _userVmDao; private final ConfigurationDao _configDao; - private final NetworkManager _networkMgr; private final UserVmManager _vmMgr; private final ConsoleProxyManager _consoleProxyMgr; private final SecondaryStorageVmManager _secStorageVmMgr; @@ -334,22 +315,18 @@ public class ManagementServerImpl implements ManagementServer { private final StoragePoolDao _poolDao; private final StoragePoolHostDao _poolHostDao; private final StorageManager _storageMgr; - private final UserVmDao _vmDao; private final NetworkDao _networkDao; private final NicDao _nicDao; private final Adapters _userAuthenticators; private final HostPodDao _hostPodDao; - private final UserStatisticsDao _userStatsDao; private final VMInstanceDao _vmInstanceDao; private final VolumeDao _volumeDao; private final AlertManager _alertMgr; private final AsyncJobDao _jobDao; private final AsyncJobManager _asyncMgr; private final TemplateManager _tmpltMgr; - private final NetworkGroupManager _networkGroupMgr; private final int _purgeDelay; - private final boolean _directAttachNetworkExternalIpAllocator; private final PreallocatedLunDao _lunDao; private final InstanceGroupDao _vmGroupDao; private final InstanceGroupVMMapDao _groupVMMapDao; @@ -358,7 +335,6 @@ public class ManagementServerImpl implements ManagementServer { private final CertificateDao _certDao; private final RemoteAccessVpnDao _remoteAccessVpnDao; private final VpnUserDao _vpnUsersDao; - @Inject private UserVmService _userVmService; private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("AccountChecker")); @@ -373,14 +349,11 @@ public class ManagementServerImpl implements ManagementServer { private final int _routerRamSize; private final int _proxyRamSize; private final int _ssRamSize; - private int _maxVolumeSizeInGb; private boolean _useNewNetworking = false; private final Map _availableIdsMap; - private boolean _networkGroupsEnabled = false; - private boolean _isHypervisorSnapshotCapable = false; private String _hashKey = null; @@ -404,7 +377,6 @@ public class ManagementServerImpl implements ManagementServer { _accountMgr = locator.getManager(AccountManager.class); _agentMgr = locator.getManager(AgentManager.class); _configMgr = locator.getManager(ConfigurationManager.class); - _networkMgr = locator.getManager(NetworkManager.class); _vmMgr = locator.getManager(UserVmManager.class); _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class); _secStorageVmMgr = locator.getManager(SecondaryStorageVmManager.class); @@ -430,7 +402,6 @@ public class ManagementServerImpl implements ManagementServer { _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); _poolDao = locator.getDao(StoragePoolDao.class); _poolHostDao = locator.getDao(StoragePoolHostDao.class); - _vmDao = locator.getDao(UserVmDao.class); _vmGroupDao = locator.getDao(InstanceGroupDao.class); _groupVMMapDao = locator.getDao(InstanceGroupVMMapDao.class); _uploadDao = locator.getDao(UploadDao.class); @@ -438,13 +409,11 @@ public class ManagementServerImpl implements ManagementServer { _remoteAccessVpnDao = locator.getDao(RemoteAccessVpnDao.class); _vpnUsersDao = locator.getDao(VpnUserDao.class); _configs = _configDao.getConfiguration(); - _userStatsDao = locator.getDao(UserStatisticsDao.class); _vmInstanceDao = locator.getDao(VMInstanceDao.class); _volumeDao = locator.getDao(VolumeDao.class); _alertMgr = locator.getManager(AlertManager.class); _asyncMgr = locator.getManager(AsyncJobManager.class); _tmpltMgr = locator.getManager(TemplateManager.class); - _networkGroupMgr = locator.getManager(NetworkGroupManager.class); _uploadMonitor = locator.getManager(UploadMonitor.class); _userAuthenticators = locator.getAdapters(UserAuthenticator.class); @@ -469,9 +438,6 @@ public class ManagementServerImpl implements ManagementServer { _proxyRamSize = NumbersUtil.parseInt(_configs.get("consoleproxy.ram.size"), ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE); _ssRamSize = NumbersUtil.parseInt(_configs.get("secstorage.ram.size"), SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE); - _directAttachNetworkExternalIpAllocator = - Boolean.parseBoolean(_configs.get("direct.attach.network.externalIpAllocator.enabled")); - _statsCollector = StatsCollector.getInstance(_configs); _executor.scheduleAtFixedRate(new AccountCleanupTask(), cleanup, cleanup, TimeUnit.SECONDS); @@ -485,15 +451,6 @@ public class ManagementServerImpl implements ManagementServer { for (String id: availableIds) { _availableIdsMap.put(id, true); } - String enabled =_configDao.getValue("direct.attach.network.groups.enabled"); - if ("true".equalsIgnoreCase(enabled)) { - _networkGroupsEnabled = true; - } - - String maxVolumeSizeInGbString = _configDao.getValue("max.volume.size.gb"); - int maxVolumeSizeGb = NumbersUtil.parseInt(maxVolumeSizeInGbString, (2000));//2000 gb - _maxVolumeSizeInGb = maxVolumeSizeGb; - _useNewNetworking = Boolean.parseBoolean(_configs.get("use.new.networking")); } @@ -833,518 +790,6 @@ public class ManagementServerImpl implements ManagementServer { return success; } - private boolean validPassword(String password) { - for (int i = 0; i < password.length(); i++) { - if (password.charAt(i) == ' ') { - return false; - } - } - return true; - } - - private UserVm deployVirtualMachineImpl(long userId, long accountId, long dataCenterId, long serviceOfferingId, VMTemplateVO template, Long diskOfferingId, - String domain, String password, String displayName, String group, String userData, String [] networkGroups, long startEventId, long size) throws ResourceAllocationException, - InsufficientStorageCapacityException, ExecutionException, StorageUnavailableException, ConcurrentOperationException { - - EventUtils.saveStartedEvent(userId, accountId, EventTypes.EVENT_VM_CREATE, "Deploying Vm", startEventId); - - AccountVO account = _accountDao.findById(accountId); - DataCenterVO dc = _dcDao.findById(dataCenterId); - ServiceOfferingVO offering = _offeringsDao.findById(serviceOfferingId); - - // Make sure a valid template ID was specified - if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template or ISO ID."); - } - - long templateId = template.getId(); - - byte [] decodedUserData = null; - if (userData != null) { - if (userData.length() >= 2* UserVmManager.MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); - } - decodedUserData = org.apache.commons.codec.binary.Base64.decodeBase64(userData.getBytes()); - if (decodedUserData.length > UserVmManager.MAX_USER_DATA_LENGTH_BYTES){ - throw new InvalidParameterValueException("User data is too long"); - } - - } - - boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); - DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); - - // TODO: Checks such as is the user allowed to use the template and purchase the service offering id. - - if (domain == null) { - domain = "v" + Long.toHexString(accountId) + _domain; - } - - // Check that the password was passed in and is valid - if (!template.getEnablePassword()) { - password = "saved_password"; - } - - if (password == null || password.equals("") || (!validPassword(password))) { - throw new InvalidParameterValueException("A valid password for this virtual machine was not provided."); - } - List networkGroupVOs = new ArrayList(); - if (networkGroups != null) { - for (String groupName: networkGroups) { - NetworkGroupVO networkGroupVO = _networkSecurityGroupDao.findByAccountAndName(accountId, groupName); - if (networkGroupVO == null) { - throw new InvalidParameterValueException("Network Group " + groupName + " does not exist"); - } - networkGroupVOs.add(networkGroupVO); - } - } - - UserStatisticsVO stats = _userStatsDao.findBy(account.getId(), dataCenterId); - if (stats == null) { - stats = new UserStatisticsVO(account.getId(), dataCenterId); - _userStatsDao.persist(stats); - } - - Long vmId = _vmDao.getNextInSequence(Long.class, "id"); - - // check if we are within context of async-execution - AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); - if (asyncExecutor != null) { - AsyncJobVO job = asyncExecutor.getJob(); - - if (s_logger.isInfoEnabled()) { - s_logger.info("DeployVM acquired a new instance " + vmId + ", update async job-" + job.getId() + " progress status"); - } - - _asyncMgr.updateAsyncJobAttachment(job.getId(), "vm_instance", vmId); - _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, vmId); - } - - HashMap avoids = new HashMap(); - - // Pod allocator now allocate VM based on a reservation style allocation, disable retry here for now - for (int retry = 0; retry < 1; retry++) { - String externalIp = null; - UserVmVO created = null; - - ArrayList a = new ArrayList(avoids.values()); - if (_directAttachNetworkExternalIpAllocator) { - try { - created = _vmMgr.createDirectlyAttachedVMExternal(vmId, userId, account, dc, offering, template, diskOffering, displayName, userData, a, networkGroupVOs, startEventId, size); - } catch (ResourceAllocationException rae) { - throw rae; - } - } else { - if (offering.getGuestIpType() == NetworkOffering.GuestIpType.Virtual) { - try { - externalIp = _networkMgr.assignSourceNatIpAddress(account, dc, domain, offering, startEventId, template.getHypervisorType()); - } catch (ResourceAllocationException rae) { - throw rae; - } - - if (externalIp == null) { - throw new CloudRuntimeException("Unable to allocate a source nat ip address"); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Source Nat acquired: " + externalIp); - } - - try { - created = _vmMgr.createVirtualMachine(vmId, userId, account, dc, offering, template, diskOffering, displayName, userData, a, startEventId, size); - } catch (ResourceAllocationException rae) { - throw rae; - } - } else { - try { - created = _vmMgr.createDirectlyAttachedVM(vmId, userId, account, dc, offering, template, diskOffering, displayName, userData, a, networkGroupVOs, startEventId, size); - } catch (ResourceAllocationException rae) { - throw rae; - } - } - } - - //assign vm to the group - try{ - if (group != null) { - boolean addToGroup = _vmMgr.addInstanceToGroup(Long.valueOf(vmId), group); - if (!addToGroup) { - throw new CloudRuntimeException("Unable to assing Vm to the group " + group); - } - } - } catch (Exception ex) { - throw new CloudRuntimeException("Unable to assing Vm to the group " + group); - } - - - if (created == null) { - throw new CloudRuntimeException("Unable to create VM for account (" + accountId + "): " + account.getAccountName()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM created: " + created.getId() + "-" + created.getHostName()); - } - boolean executionExceptionFlag = false; - boolean storageUnavailableExceptionFlag = false; - boolean concurrentOperationExceptionFlag = false; - String executionExceptionMsg= ""; - String storageUnavailableExceptionMsg = ""; - String concurrentOperationExceptionMsg = ""; - UserVmVO started = null; - - if (isIso) - { - Pair isoPath = _storageMgr.getAbsoluteIsoPath(templateId, dataCenterId); - if (isoPath == null) { - s_logger.warn("Unable to get absolute path of the iso"); - throw new CloudRuntimeException("Unable to get absolute path of the iso"); - } - try - { - started = _vmMgr.startVirtualMachine(userId, created.getId(), password, isoPath.first(), startEventId); - } - catch (ExecutionException e) - { - executionExceptionFlag = true; - executionExceptionMsg = e.getMessage(); - } - catch (StorageUnavailableException e) - { - storageUnavailableExceptionFlag = true; - storageUnavailableExceptionMsg = e.getMessage(); - } - catch (ConcurrentOperationException e) - { - concurrentOperationExceptionFlag = true; - concurrentOperationExceptionMsg = e.getMessage(); - } - } - else - { - try - { - started = _vmMgr.startVirtualMachine(userId, created.getId(), password, null, startEventId); - } - catch (ExecutionException e) - { - executionExceptionFlag = true; - executionExceptionMsg = e.getMessage(); - } - catch (StorageUnavailableException e) - { - storageUnavailableExceptionFlag = true; - storageUnavailableExceptionMsg = e.getMessage(); - } - catch (ConcurrentOperationException e) - { - concurrentOperationExceptionFlag = true; - concurrentOperationExceptionMsg = e.getMessage(); - } - } - - if (started == null) { - List> disks = _storageMgr.isStoredOn(created); - // NOTE: We now destroy a VM if the deploy process fails at any step. We now - // have a lazy delete so there is still some time to figure out what's wrong. - _vmMgr.destroyVirtualMachine(userId, created.getId()); - - boolean retryCreate = true; - for (Pair disk : disks) { - if (disk.second().isLocal()) { - avoids.put(disk.second().getId(), disk.second()); - } else { - retryCreate = false; - } - } - - if (retryCreate) { - continue; - } else if(executionExceptionFlag){ - throw new ExecutionException(executionExceptionMsg); - } else if (storageUnavailableExceptionFlag){ - throw new StorageUnavailableException(storageUnavailableExceptionMsg); - }else if (concurrentOperationExceptionFlag){ - throw new ConcurrentOperationException(concurrentOperationExceptionMsg); - } - else{ - throw new CloudRuntimeException("Unable to start the VM " + created.getId() + "-" + created.getHostName()); - } - - } else { - if (isIso) { - started.setIsoId(templateId); - _userVmDao.update(started.getId(), started); - started = _userVmDao.findById(started.getId()); - } - - try { - _configMgr.associateIpAddressListToAccount(userId, accountId, dc.getId(),null); - } catch (InsufficientAddressCapacityException e) { - s_logger.debug("Unable to assign public IP address pool: " +e.getMessage()); - } - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM started: " + started.getId() + "-" + started.getHostName()); - } - return started; - } - - return null; - } - - @Override - public UserVm deployVirtualMachine(DeployVMCmd cmd, String password) throws ResourceAllocationException, - ExecutionException, - ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (_useNewNetworking) { - UserVm vm = _userVmService.createVirtualMachine(cmd); - if (vm == null) { - return null; - } - - DeployVm2Cmd cmd2 = new DeployVm2Cmd(); - cmd2.setEntityId(vm.getId()); - vm = _userVmService.startVirtualMachine(cmd2); - return vm; - } - Account ctxAccount = UserContext.current().getAccount(); - Long userId = UserContext.current().getUserId(); - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Long accountId = null; - long dataCenterId = cmd.getZoneId(); - long serviceOfferingId = cmd.getServiceOfferingId(); - long templateId = cmd.getTemplateId(); - Long diskOfferingId = cmd.getDiskOfferingId(); - String domain = null; // FIXME: this was hardcoded to null in DeployVMCmd in the old framework, do we need it? - String displayName = cmd.getDisplayName(); - String group = cmd.getGroup(); - String userData = cmd.getUserData(); - String[] networkGroups = null; - Long sizeObj = cmd.getSize(); - long size = (sizeObj == null) ? 0 : sizeObj; - Account userAccount = null; - - DataCenterVO dc = _dcDao.findById(dataCenterId); - if (dc == null) { - throw new InvalidParameterValueException("Unable to find zone: " + dataCenterId); - } - - if ((ctxAccount == null) || isAdmin(ctxAccount.getType())) { - if (domainId != null) { - if ((ctxAccount != null) && !_domainDao.isChildDomain(ctxAccount.getDomainId(), domainId)) { - throw new PermissionDeniedException("Failed to deploy VM, invalid domain id (" + domainId + ") given."); - } - if (accountName != null) { - userAccount = _accountDao.findActiveAccount(accountName, domainId); - if (userAccount == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - accountId = userAccount.getId(); - } - } else { - accountId = ((ctxAccount != null) ? ctxAccount.getId() : null); - } - } else { - accountId = ctxAccount.getId(); - } - - if (accountId == null) { - throw new InvalidParameterValueException("No valid account specified for deploying a virtual machine."); - } - - if(domainId == null){ - domainId = dc.getDomainId(); //get the domain id from zone - } - - if(domainId == null){ - //do nothing (public zone case) - } - else{ - if(userAccount != null){ - _configMgr.checkAccess(userAccount, dc);//user deploying his own vm - }else{ - _configMgr.checkAccess(ctxAccount, dc); - } - } - - List netGrpList = cmd.getNetworkGroupList(); - if ((netGrpList != null) && !netGrpList.isEmpty()) { - networkGroups = netGrpList.toArray(new String[netGrpList.size()]); - } - - AccountVO account = _accountDao.findById(accountId); - if (account == null) { - throw new InvalidParameterValueException("Unable to find account: " + accountId); - } - - ServiceOfferingVO offering = _offeringsDao.findById(serviceOfferingId); - if (offering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); - } - - if(offering.getDomainId() == null){ - //do nothing as offering is public - }else{ - if(userAccount != null){ - _configMgr.checkServiceOfferingAccess(userAccount, offering);//user deploying his own vm - }else{ - _configMgr.checkServiceOfferingAccess(ctxAccount, offering); - } - } - - VMTemplateVO template = _templateDao.findById(templateId); - // Make sure a valid template ID was specified - if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template or ISO ID."); - } - - boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); - - if (isIso && !template.isBootable()) { - throw new InvalidParameterValueException("Please specify a bootable ISO."); - } - - // If the template represents an ISO, a disk offering must be passed in, and will be used to create the root disk - // Else, a disk offering is optional, and if present will be used to create the data disk - DiskOfferingVO diskOffering = null; - - if (diskOfferingId != null) { - diskOffering = _diskOfferingDao.findById(diskOfferingId); - } - - if (isIso && diskOffering == null) { - throw new InvalidParameterValueException("Please specify a valid disk offering ID."); - } - - if(diskOffering != null){ - if(diskOffering.getDomainId() == null){ - //do nothing as offering is public - }else{ - if(userAccount != null){ - _configMgr.checkDiskOfferingAccess(userAccount, diskOffering);//user deploying his own vm - }else{ - _configMgr.checkDiskOfferingAccess(ctxAccount, diskOffering); - } - } - } - - if (isIso) { - /*iso template doesn;t have hypervisor type, temporarily set it's type as user specified, pass it to storage allocator */ - template.setHypervisorType(HypervisorType.getType(cmd.getHypervisor())); - } - - //if it is a custom disk offering,AND the size passed in here is <= 0; error out - if(diskOffering != null && diskOffering.isCustomized() && size <= 0){ - throw new InvalidParameterValueException("Please specify a valid disk size for VM creation; custom disk offering has no size set"); - } - - if(diskOffering != null && diskOffering.isCustomized() && size > _maxVolumeSizeInGb){ - throw new InvalidParameterValueException("Please specify a valid disk size for VM creation; custom disk offering max size is:"+_maxVolumeSizeInGb); - } - - // validate that the template is usable by the account - if (!template.isPublicTemplate()) { - Long templateOwner = template.getAccountId(); - if (!BaseCmd.isAdmin(account.getType()) && ((templateOwner == null) || (templateOwner.longValue() != accountId))) { - // since the current account is not the owner of the template, check the launch permissions table to see if the - // account can launch a VM from this template - LaunchPermissionVO permission = _launchPermissionDao.findByTemplateAndAccount(templateId, account.getId()); - if (permission == null) { - throw new PermissionDeniedException("Account " + account.getAccountName() + " does not have permission to launch instances from template " + template.getName()); - } - } - } - - - - byte [] decodedUserData = null; - if (userData != null) { - if (userData.length() >= 2* UserVmManager.MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); - } - decodedUserData = org.apache.commons.codec.binary.Base64.decodeBase64(userData.getBytes()); - if (decodedUserData.length > UserVmManager.MAX_USER_DATA_LENGTH_BYTES){ - throw new InvalidParameterValueException("User data is too long"); - } - if (decodedUserData.length < 1) { - throw new InvalidParameterValueException("User data is too short"); - } - - } - if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtual) { - _networkGroupMgr.createDefaultNetworkGroup(accountId); - } - - if (networkGroups != null) { - if (offering.getGuestIpType() == NetworkOffering.GuestIpType.Virtual) { - throw new InvalidParameterValueException("Network groups are not compatible with service offering " + offering.getName()); - } - Set nameSet = new HashSet(); //handle duplicate names -- allowed - nameSet.addAll(Arrays.asList(networkGroups)); - nameSet.add(NetworkGroupManager.DEFAULT_GROUP_NAME); - networkGroups = nameSet.toArray(new String[nameSet.size()]); - List networkGroupVOs = _networkSecurityGroupDao.findByAccountAndNames(accountId, networkGroups); - if (networkGroupVOs.size() != nameSet.size()) { - throw new InvalidParameterValueException("Some network group names do not exist"); - } - } else { //create a default group if necessary - if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtual && _networkGroupsEnabled) { - networkGroups = new String[]{NetworkGroupManager.DEFAULT_GROUP_NAME}; - } - } - - Long eventId = cmd.getStartEventId(); - try { - return deployVirtualMachineImpl(userId, accountId, dataCenterId, serviceOfferingId, template, diskOfferingId, domain, password, displayName, group, userData, networkGroups, eventId, (1L*size*1024));//this api expects size in MB - } catch (ResourceAllocationException e) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - } - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INSUFFICIENT_CAPACITY", null, eventId); - throw e; - } catch (ExecutionException e) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - } - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_HOST_LICENSE_EXPIRED", null, eventId); - throw e; - } catch (InvalidParameterValueException e) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - } - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INVALID_PARAM_ERROR", null, eventId); - throw e; - } catch (InsufficientStorageCapacityException e) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - } - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INSUFFICIENT_CAPACITY", null, eventId); - throw e; - } catch (PermissionDeniedException e) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - } - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: ACCOUNT_ERROR", null, eventId); - throw e; - } catch (ConcurrentOperationException e) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - } - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: INTERNAL_ERROR", null, eventId); - throw e; - } catch(Exception e) { - s_logger.warn("Unable to deploy VM : " + e.getMessage(), e); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: INTERNAL_ERROR", null, eventId); - throw new CloudRuntimeException("Unable to deploy VM : " + e.getMessage()); - } - } - - @Override - public DomainRouterVO findDomainRouterById(long domainRouterId) { - return _routerDao.findById(domainRouterId); - } - @Override public List listDataCenters(ListZonesByCmd cmd) { Account account = UserContext.current().getAccount(); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 3dd1dbaaa1e..003ffcdd69f 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -70,7 +70,6 @@ import com.cloud.api.commands.CreateTemplateCmd; import com.cloud.api.commands.CreateVMGroupCmd; import com.cloud.api.commands.DeleteVMGroupCmd; import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DeployVm2Cmd; import com.cloud.api.commands.DestroyVMCmd; import com.cloud.api.commands.DetachVolumeCmd; import com.cloud.api.commands.RebootVMCmd; @@ -202,7 +201,6 @@ import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.InstanceGroupVMMapDao; import com.cloud.vm.dao.UserVmDao; - @Local(value={UserVmManager.class, UserVmService.class}) public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualMachineGuru, Manager, VirtualMachineManager { private static final Logger s_logger = Logger.getLogger(UserVmManagerImpl.class); @@ -2818,7 +2816,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM { for(VlanVO vlanForAcc : vlansForAccount) { - guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForAcc.getId(), false); + guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForAcc.getId(), false).getAddress(); if(guestIp!=null) { break; //got an ip } @@ -2829,7 +2827,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM //i.e. for pod for(VlanVO vlanForPod : vlansForPod) { - guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForPod.getId(), false); + guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForPod.getId(), false).getAddress(); if(guestIp!=null) { break;//got an ip } @@ -2840,7 +2838,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM //for zone for(VlanVO vlanForZone : zoneWideVlans) { - guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForZone.getId(), false); + guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForZone.getId(), false).getAddress(); if(guestIp!=null) { break;//found an ip } @@ -3732,7 +3730,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM } @Override - public UserVm startVirtualMachine(DeployVm2Cmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { + public UserVm startVirtualMachine(DeployVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { long vmId = cmd.getEntityId(); UserVmVO vm = _vmDao.findById(vmId);