diff --git a/api/src/com/cloud/configuration/ConfigurationService.java b/api/src/com/cloud/configuration/ConfigurationService.java index e2fe2c7fa17..5e97381953f 100644 --- a/api/src/com/cloud/configuration/ConfigurationService.java +++ b/api/src/com/cloud/configuration/ConfigurationService.java @@ -45,41 +45,43 @@ import com.cloud.dc.Pod; import com.cloud.dc.Vlan; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.DiskOffering; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.Type; public interface ConfigurationService { - + /** * Updates a configuration entry with a new value - * @param cmd - the command wrapping name and value parameters + * + * @param cmd + * - the command wrapping name and value parameters * @return updated configuration object if successful - * @throws InvalidParameterValueException */ - Configuration updateConfiguration(UpdateCfgCmd cmd) throws InvalidParameterValueException; - + Configuration updateConfiguration(UpdateCfgCmd cmd); + /** * Persists a config value via the API call + * * @return newly created Config object */ Configuration addConfig(CreateCfgCmd cmd); - + /** * Create a service offering through the API - * @param cmd the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service offering + * + * @param cmd + * the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service offering * @return the newly created service offering if successful, null otherwise */ ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd); - + /** * Updates a service offering + * * @param serviceOfferingId * @param userId * @param name @@ -90,32 +92,38 @@ public interface ConfigurationService { * @return updated service offering */ ServiceOffering updateServiceOffering(UpdateServiceOfferingCmd cmd); - + /** * Deletes a service offering + * * @param userId * @param serviceOfferingId */ boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd); - + /** * Updates a disk offering - * @param cmd - the command specifying diskOfferingId, name, description, tags + * + * @param cmd + * - the command specifying diskOfferingId, name, description, tags * @return updated disk offering - * @throws + * @throws */ DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd); - + /** * Deletes a disk offering - * @param cmd - the command specifying disk offering id + * + * @param cmd + * - the command specifying disk offering id * @return true or false - * @throws + * @throws */ boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd); - + /** * Creates a new disk offering + * * @param domainId * @param name * @param description @@ -125,41 +133,49 @@ public interface ConfigurationService { * @return ID */ DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd); - + /** * Creates a new pod based on the parameters specified in the command object - * @param cmd the command object that specifies the name, zone, gateway, cidr, and ip range for the pod + * + * @param cmd + * the command object that specifies the name, zone, gateway, cidr, and ip range for the pod * @return the new pod if successful, null otherwise - * @throws - * @throws + * @throws + * @throws */ Pod createPod(CreatePodCmd cmd); /** * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. - * @param UpdatePodCmd api command + * + * @param UpdatePodCmd + * api command */ Pod editPod(UpdatePodCmd cmd); - + /** * Deletes a pod from the database. Will not allow you to delete pods that are being used anywhere in the system. - * @param cmd - the command containing podId + * + * @param cmd + * - the command containing podId * @return true or false - * @throws , + * @throws , */ boolean deletePod(DeletePodCmd cmd); - + /** * Creates a new zone + * * @param cmd * @return the zone if successful, null otherwise - * @throws - * @throws + * @throws + * @throws */ DataCenter createZone(CreateZoneCmd cmd); - + /** * Edits a zone in the database. Will not allow you to edit DNS values if there are VMs in the specified zone. + * * @param UpdateZoneCmd * @return Updated zone */ @@ -167,16 +183,20 @@ public interface ConfigurationService { /** * Deletes a zone from the database. Will not allow you to delete zones that are being used anywhere in the system. + * * @param userId * @param zoneId */ boolean deleteZone(DeleteZoneCmd cmd); - - + /** - * Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on the virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs + * Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on the + * virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs + * * @param userId - * @param vlanType - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be directly attached to UserVMs) + * @param vlanType + * - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be directly + * attached to UserVMs) * @param zoneId * @param accountId * @param podId @@ -185,35 +205,35 @@ public interface ConfigurationService { * @param gateway * @param startIP * @param endIP - * @throws + * @throws * @return The new Vlan object */ Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException; boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd); - + NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd); - + NetworkOffering updateNetworkOffering(UpdateNetworkOfferingCmd cmd); - + List searchForNetworkOfferings(ListNetworkOfferingsCmd cmd); - + boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd); - + NetworkOffering getNetworkOffering(long id); - + Integer getNetworkOfferingNetworkRate(long networkOfferingId); - + Account getVlanAccount(long vlanId); - + List listNetworkOfferings(TrafficType trafficType, boolean systemOnly); DataCenter getZone(long id); - + ServiceOffering getServiceOffering(long serviceOfferingId); - + Long getDefaultPageSize(); - + Integer getServiceOfferingNetworkRate(long serviceOfferingId); - + } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 139c75f3299..5e62ae89119 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -28,8 +28,6 @@ import com.cloud.api.commands.RestartNetworkCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Capability; @@ -37,49 +35,54 @@ import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.user.Account; -import com.cloud.vm.VirtualMachine.Type; - public interface NetworkService { - + List getVirtualNetworksOwnedByAccountInZone(String accountName, long domainId, long zoneId); - + List listNetworkOfferings(); - + IpAddress allocateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException; + /** * Associates a public IP address for a router. - * @param cmd - the command specifying ipAddress + * + * @param cmd + * - the command specifying ipAddress * @return ip address object - * @throws ResourceAllocationException, InsufficientCapacityException + * @throws ResourceAllocationException + * , InsufficientCapacityException */ - IpAddress associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException, ResourceUnavailableException; + IpAddress associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException, ResourceUnavailableException; + boolean disassociateIpAddress(DisassociateIPAddrCmd cmd); Network createNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException; - List searchForNetworks(ListNetworksCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; - boolean deleteNetwork(long networkId) throws InvalidParameterValueException, PermissionDeniedException; - + + List searchForNetworks(ListNetworksCmd cmd); + + boolean deleteNetwork(long networkId); + boolean restartNetwork(RestartNetworkCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + int getActiveNicsInNetwork(long networkId); - + Network getNetwork(long networkId); - + IpAddress getIp(long id); - + NetworkProfile convertNetworkToNetworkProfile(long networkId); - + Map> getZoneCapabilities(long zoneId); - + Map> getNetworkCapabilities(long networkId); - + boolean isNetworkAvailableInDomain(long networkId, long domainId); - + Long getDedicatedNetworkDomain(long networkId); - + Network updateNetwork(long networkId, String name, String displayText, Account caller); - + Integer getNetworkRate(long networkId, Long vmId); Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); diff --git a/api/src/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/com/cloud/network/VirtualNetworkApplianceService.java index a194b06174a..e1d137b4076 100644 --- a/api/src/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VirtualNetworkApplianceService.java @@ -20,8 +20,6 @@ package com.cloud.network; import com.cloud.api.commands.UpgradeRouterCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.router.VirtualRouter; @@ -30,17 +28,15 @@ public interface VirtualNetworkApplianceService{ * Starts domain router * @param cmd the command specifying router's id * @return DomainRouter object - * @throws InvalidParameterValueException, PermissionDeniedException */ - VirtualRouter startRouter(long routerId, boolean restartNetwork) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; + VirtualRouter startRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** * Reboots domain router * @param cmd the command specifying router's id * @return router if successful - * @throws InvalidParameterValueException, PermissionDeniedException */ - VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; + VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualRouter upgradeRouter(UpgradeRouterCmd cmd); @@ -49,10 +45,9 @@ public interface VirtualNetworkApplianceService{ * @param id of the router * @param forced just do it. caller knows best. * @return router if successful, null otherwise - * @throws ConcurrentOperationException * @throws ResourceUnavailableException - * @throws InvalidParameterValueException, PermissionDeniedException + * @throws ConcurrentOperationException */ - VirtualRouter stopRouter(long routerId, boolean forced) throws InvalidParameterValueException, PermissionDeniedException, ResourceUnavailableException, ConcurrentOperationException; + VirtualRouter stopRouter(long routerId, boolean forced) throws ResourceUnavailableException, ConcurrentOperationException; } diff --git a/api/src/com/cloud/network/security/SecurityGroupService.java b/api/src/com/cloud/network/security/SecurityGroupService.java index c913b1066ef..a25ba39c423 100644 --- a/api/src/com/cloud/network/security/SecurityGroupService.java +++ b/api/src/com/cloud/network/security/SecurityGroupService.java @@ -46,7 +46,7 @@ public interface SecurityGroupService { */ public List searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException; - public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; + public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd); } diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index a3289654807..01f3f61391f 100644 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -36,43 +36,51 @@ import com.cloud.org.Cluster; public interface ResourceService { /** * Updates a host - * @param cmd - the command specifying hostId + * + * @param cmd + * - the command specifying hostId * @return hostObject - * @throws InvalidParameterValueException */ - Host updateHost(UpdateHostCmd cmd) throws InvalidParameterValueException; + Host updateHost(UpdateHostCmd cmd); - Host cancelMaintenance(CancelMaintenanceCmd cmd) throws InvalidParameterValueException; + Host cancelMaintenance(CancelMaintenanceCmd cmd); Host reconnectHost(ReconnectHostCmd cmd) throws AgentUnavailableException; - + /** - * We will automatically create a cloud.com cluster to attach to the external cluster and return a hyper host to perform + * We will automatically create a cloud.com cluster to attach to the external cluster and return a hyper host to perform * host related operation within the cluster * * @param cmd * @return * @throws IllegalArgumentException * @throws DiscoveryException - * @throws InvalidParameterValueException */ - List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException; - boolean deleteCluster(DeleteClusterCmd cmd) throws InvalidParameterValueException; - Cluster updateCluster(Cluster cluster, String clusterType, String hypervisor, String allocationState) throws InvalidParameterValueException; - + List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException; + + boolean deleteCluster(DeleteClusterCmd cmd); + + Cluster updateCluster(Cluster cluster, String clusterType, String hypervisor, String allocationState); + List discoverHosts(AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException; + List discoverHosts(AddSecondaryStorageCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException; - Host maintain(PrepareForMaintenanceCmd cmd) throws InvalidParameterValueException; + + Host maintain(PrepareForMaintenanceCmd cmd); + /** * Deletes a host - * @param hostId TODO - * @param isForced TODO + * + * @param hostId + * TODO + * @param isForced + * TODO * * @param true if deleted, false otherwise */ - boolean deleteHost(long hostId, boolean isForced); - + boolean deleteHost(long hostId, boolean isForced); + Host getHost(long hostId); - Cluster getCluster(Long clusterId); + Cluster getCluster(Long clusterId); } diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 161cbd4ee3d..2a5696cb6d5 100644 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -85,7 +85,6 @@ import com.cloud.domain.Domain; import com.cloud.event.Event; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InternalErrorException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; @@ -110,165 +109,183 @@ import com.cloud.vm.VirtualMachine.Type; /** * Hopefull this is temporary. - * + * */ public interface ManagementService { static final String Name = "management-server"; - + /** - * 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 - * available=true all zones which the account can access. By specifying available=false the zones where the - * account has virtual machine instances will be returned. + * 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 available=true all zones which the account can access. By specifying + * available=false the zones where the account has virtual machine instances will be returned. + * * @return a list of DataCenters */ List listDataCenters(ListZonesByCmd cmd); /** * returns the a map of the names/values in the configuraton table + * * @return map of configuration name/values */ List searchForConfigurations(ListCfgsByCmd c); - - /** revisit - * Searches for users by the specified search criteria - * Can search by: "id", "username", "account", "domainId", "type" + + /** + * revisit Searches for users by the specified search criteria Can search by: "id", "username", "account", "domainId", + * "type" + * * @param cmd * @return List of UserAccounts */ List searchForUsers(ListUsersCmd cmd); - + /** - * Searches for Service Offerings by the specified search criteria - * Can search by: "name" + * Searches for Service Offerings by the specified search criteria Can search by: "name" + * * @param cmd * @return List of ServiceOfferings */ List searchForServiceOfferings(ListServiceOfferingsCmd cmd); - + /** * Searches for Clusters by the specified search criteria + * * @param c * @return */ List searchForClusters(ListClustersCmd c); - + /** - * Searches for Pods by the specified search criteria - * Can search by: pod name and/or zone name + * Searches for Pods by the specified search criteria Can search by: pod name and/or zone name + * * @param cmd * @return List of Pods */ List searchForPods(ListPodsByCmd cmd); - + /** - * Searches for servers by the specified search criteria - * Can search by: "name", "type", "state", "dataCenterId", "podId" + * Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId", "podId" + * * @param cmd * @return List of Hosts */ List searchForServers(ListHostsCmd cmd); - + /** * Creates a new template + * * @param cmd * @return updated template - * @throws InvalidParameterValueException, PermissionDeniedException */ VirtualMachineTemplate updateTemplate(UpdateIsoCmd cmd); + VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd); - + /** - * Obtains a list of events by the specified search criteria. - * Can search by: "username", "type", "level", "startDate", "endDate" + * Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level", "startDate", + * "endDate" + * * @param c * @return List of Events. */ List searchForEvents(ListEventsCmd c); - + /** - * Obtains a list of routers by the specified search criteria. - * Can search by: "userId", "name", "state", "dataCenterId", "podId", "hostId" + * Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state", "dataCenterId", + * "podId", "hostId" + * * @param cmd * @return List of DomainRouters. */ List searchForRouters(ListRoutersCmd cmd); - - /** revisit - * Obtains a list of storage volumes by the specified search criteria. - * Can search by: "userId", "vType", "instanceId", "dataCenterId", "podId", "hostId" + + /** + * revisit Obtains a list of storage volumes by the specified search criteria. Can search by: "userId", "vType", + * "instanceId", "dataCenterId", "podId", "hostId" + * * @param cmd * @return List of Volumes. */ List searchForVolumes(ListVolumesCmd cmd); /** - * Obtains a list of IP Addresses by the specified search criteria. - * Can search by: "userId", "dataCenterId", "address" - * @param cmd the command that wraps the search criteria + * Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId", "address" + * + * @param cmd + * the command that wraps the search criteria * @return List of IPAddresses */ List searchForIPAddresses(ListPublicIpAddressesCmd cmd); - + /** * Obtains a list of all guest OS. + * * @return list of GuestOS */ List listGuestOSByCriteria(ListGuestOsCmd cmd); - + /** * Obtains a list of all guest OS categories. + * * @return list of GuestOSCategories */ List listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd); - + VirtualMachine stopSystemVM(StopSystemVmCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException; + VirtualMachine startSystemVM(StartSystemVMCmd cmd); + VirtualMachine rebootSystemVM(RebootSystemVmCmd cmd); + VirtualMachine destroySystemVM(DestroySystemVmCmd cmd); - + /** - * Search for domains owned by the given domainId/domainName (those parameters are wrapped - * in a command object. + * Search for domains owned by the given domainId/domainName (those parameters are wrapped in a command object. + * * @return list of domains owned by the given user */ List searchForDomains(ListDomainsCmd c); - + List searchForDomainChildren(ListDomainChildrenCmd cmd); /** * create a new domain - * @param command - the create command defining the name to use and the id of the parent domain under which to create the new domain. + * + * @param command + * - the create command defining the name to use and the id of the parent domain under which to create the new + * domain. */ Domain createDomain(CreateDomainCmd command); /** * delete a domain with the given domainId - * @param cmd the command wrapping the delete parameters - * - domainId - * - ownerId - * - cleanup: whether or not to delete all accounts/VMs/sub-domains when deleting the domain + * + * @param cmd + * the command wrapping the delete parameters - domainId - ownerId - cleanup: whether or not to delete all + * accounts/VMs/sub-domains when deleting the domain */ boolean deleteDomain(DeleteDomainCmd cmd); /** * update an existing domain - * @param cmd - the command containing domainId and new domainName + * + * @param cmd + * - the command containing domainId and new domainName * @return Domain object if the command succeeded - * @throws InvalidParameterValueException, PermissionDeniedException */ Domain updateDomain(UpdateDomainCmd cmd); - + /** - * Searches for accounts by the specified search criteria - * Can search by: "id", "name", "domainid", "type" + * Searches for accounts by the specified search criteria Can search by: "id", "name", "domainid", "type" + * * @param cmd * @return List of Accounts */ List searchForAccounts(ListAccountsCmd cmd); - + /** * Searches for alerts + * * @param c * @return List of Alerts */ @@ -276,62 +293,82 @@ public interface ManagementService { /** * list all the capacity rows in capacity operations table + * * @param cmd * @return List of capacities */ List listCapacities(ListCapacityCmd cmd); /** - * List the permissions on a template. This will return a list of account names that have been granted permission to launch instances from the template. - * @param cmd the command wrapping the search criteria (template id) + * List the permissions on a template. This will return a list of account names that have been granted permission to launch + * instances from the template. + * + * @param cmd + * the command wrapping the search criteria (template id) * @return list of account names that have been granted permission to launch instances from the template */ List listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd); /** - * List ISOs that match the specified criteria. - * @param cmd The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId parameters. + * List ISOs that match the specified criteria. + * + * @param cmd + * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId + * parameters. * @return list of ISOs */ Set> listIsos(ListIsosCmd cmd); /** - * List templates that match the specified criteria. - * @param cmd The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId parameters. + * List templates that match the specified criteria. + * + * @param cmd + * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId + * parameters. * @return list of ISOs */ Set> listTemplates(ListTemplatesCmd cmd); /** * Search for disk offerings based on search criteria - * @param cmd the command containing the criteria to use for searching for disk offerings + * + * @param cmd + * the command containing the criteria to use for searching for disk offerings * @return a list of disk offerings that match the given criteria */ List searchForDiskOfferings(ListDiskOfferingsCmd cmd); /** * List storage pools that match the given criteria - * @param cmd the command that wraps the search criteria (zone, pod, name, IP address, path, and cluster id) + * + * @param cmd + * the command that wraps the search criteria (zone, pod, name, IP address, path, and cluster id) * @return a list of storage pools that match the given criteria */ List searchForStoragePools(ListStoragePoolsCmd cmd); /** * List system VMs by the given search criteria - * @param cmd the command that wraps the search criteria (host, name, state, type, zone, pod, and/or id) + * + * @param cmd + * the command that wraps the search criteria (host, name, state, type, zone, pod, and/or id) * @return the list of system vms that match the given criteria */ List searchForSystemVm(ListSystemVMsCmd cmd); /** * Returns back a SHA1 signed response - * @param userId -- id for the user + * + * @param userId + * -- id for the user * @return -- ArrayList of */ ArrayList getCloudIdentifierResponse(GetCloudIdentifierCmd cmd); boolean updateTemplatePermissions(UpdateTemplatePermissionsCmd cmd); + boolean updateTemplatePermissions(UpdateIsoPermissionsCmd cmd); + String[] createApiKeyAndSecretKey(RegisterCmd cmd); InstanceGroup updateVmGroup(UpdateVMGroupCmd cmd); @@ -342,16 +379,20 @@ public interface ManagementService { /** * Extracts the volume to a particular location. - * @param cmd the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume exists), id (the id of the volume) + * + * @param cmd + * the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume exists), + * id (the id of the volume) * @throws URISyntaxException * @throws InternalErrorException - * @throws PermissionDeniedException - * + * @throws PermissionDeniedException + * */ Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException; /** * return an array of available hypervisors + * * @param cmd * @return an array of available hypervisors in the cloud */ @@ -359,82 +400,100 @@ public interface ManagementService { /** * This method uploads a custom cert to the db, and patches every cpvm with it on the current ms - * @param cmd -- upload certificate cmd + * + * @param cmd + * -- upload certificate cmd * @return -- returns a string on success - * @throws ServerApiException -- even if one of the console proxy patching fails, we throw back this exception + * @throws ServerApiException + * -- even if one of the console proxy patching fails, we throw back this exception */ String uploadCertificate(UploadCustomCertificateCmd cmd); - + String getVersion(); - + /** - * Searches for vlan by the specified search criteria - * Can search by: "id", "vlan", "name", "zoneID" + * Searches for vlan by the specified search criteria Can search by: "id", "vlan", "name", "zoneID" + * * @param cmd * @return List of Vlans */ List searchForVlans(ListVlanIpRangesCmd cmd); + /** * Search for async jobs by account and/or startDate - * @param cmd the command specifying the account and start date parameters + * + * @param cmd + * the command specifying the account and start date parameters * @return the list of async jobs that match the criteria */ List searchForAsyncJobs(ListAsyncJobsCmd cmd); - + /** * Generates a random password that will be used (initially) by newly created and started virtual machines + * * @return a random password */ String generateRandomPassword(); - + public Long saveStartedEvent(Long userId, Long accountId, String type, String description, long startEventId); - + public Long saveCompletedEvent(Long userId, Long accountId, String level, String type, String description, long startEventId); /** - * Search registered key pairs for the logged in user. - * @param cmd The api command class. + * Search registered key pairs for the logged in user. + * + * @param cmd + * The api command class. * @return The list of key pairs found. */ List listSSHKeyPairs(ListSSHKeyPairsCmd cmd); /** - * Registers a key pair for a given public key. - * @param cmd The api command class. - * @return A VO with the key pair name and a finger print for the public key. + * Registers a key pair for a given public key. + * + * @param cmd + * The api command class. + * @return A VO with the key pair name and a finger print for the public key. */ SSHKeyPair registerSSHKeyPair(RegisterSSHKeyPairCmd cmd); /** - * Creates a new - * @param cmd The api command class. - * @return A VO containing the key pair name, finger print for the public key - * and the private key material of the key pair. + * Creates a new + * + * @param cmd + * The api command class. + * @return A VO containing the key pair name, finger print for the public key and the private key material of the key pair. */ SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd); /** * Deletes a key pair by name. - * @param cmd The api command class. + * + * @param cmd + * The api command class. * @return True on success. False otherwise. */ boolean deleteSSHKeyPair(DeleteSSHKeyPairCmd cmd); /** * Finds and returns an encrypted password for a VM. - * @param cmd The api command class. + * + * @param cmd + * The api command class. * @return The encrypted password. */ String getVMPassword(GetVMPasswordCmd cmd); Type findSystemVMTypeById(long instanceId); - + /** - * List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current host - * and also a list of hostIds that seem to have enough CPU and RAM capacity to host this VM. - * @param UserVm vm The VM to migrate + * List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current host and + * also a list of hostIds that seem to have enough CPU and RAM capacity to host this VM. + * + * @param UserVm + * vm The VM to migrate * @return Pair, List> List of all Hosts in VM's cluster and list of HostIds with enough capacity */ - Pair, List> listHostsForMigrationOfVM(UserVm vm, Long startIndex, Long pageSize); + Pair, List> listHostsForMigrationOfVM(UserVm vm, Long startIndex, Long pageSize); } diff --git a/api/src/com/cloud/storage/StorageService.java b/api/src/com/cloud/storage/StorageService.java index 72ecd4a2415..9bcf1139b0d 100644 --- a/api/src/com/cloud/storage/StorageService.java +++ b/api/src/com/cloud/storage/StorageService.java @@ -28,7 +28,6 @@ import com.cloud.api.commands.PreparePrimaryStorageForMaintenanceCmd; import com.cloud.api.commands.UpdateStoragePoolCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceInUseException; @@ -55,7 +54,6 @@ public interface StorageService { * @param cmd * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, name) * @return the volume object - * @throws InvalidParameterValueException * @throws PermissionDeniedException */ Volume allocVolume(CreateVolumeCmd cmd) throws ResourceAllocationException; @@ -77,9 +75,8 @@ public interface StorageService { * @param cmd * - the command specifying poolId * @return success or failure - * @throws InvalidParameterValueException */ - boolean deletePool(DeletePoolCmd cmd) throws InvalidParameterValueException; + boolean deletePool(DeletePoolCmd cmd); /** * Enable maintenance for primary storage diff --git a/api/src/com/cloud/storage/snapshot/SnapshotService.java b/api/src/com/cloud/storage/snapshot/SnapshotService.java index 2a5fe8da3a4..b5ca0eb2ab4 100644 --- a/api/src/com/cloud/storage/snapshot/SnapshotService.java +++ b/api/src/com/cloud/storage/snapshot/SnapshotService.java @@ -26,7 +26,6 @@ import com.cloud.api.commands.DeleteSnapshotPoliciesCmd; import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; import com.cloud.api.commands.ListSnapshotPoliciesCmd; import com.cloud.api.commands.ListSnapshotsCmd; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.storage.Snapshot; @@ -34,51 +33,60 @@ import com.cloud.storage.Snapshot; public interface SnapshotService { /** * Create a snapshot of a volume - * @param cmd the API command wrapping the parameters for creating the snapshot (mainly volumeId) + * + * @param cmd + * the API command wrapping the parameters for creating the snapshot (mainly volumeId) * @return the Snapshot that was created */ - Snapshot createSnapshot(CreateSnapshotCmd cmd) throws InvalidParameterValueException; + Snapshot createSnapshot(CreateSnapshotCmd cmd); /** * List all snapshots of a disk volume. Optionally lists snapshots created by specified interval - * @param cmd the command containing the search criteria (order by, limit, etc.) + * + * @param cmd + * the command containing the search criteria (order by, limit, etc.) * @return list of snapshots - * @throws InvalidParameterValueException * @throws PermissionDeniedException */ List listSnapshots(ListSnapshotsCmd cmd); /** - * Delete specified snapshot from the specified. - * If no other policies are assigned it calls destroy snapshot. - * This will be used for manual snapshots too. + * Delete specified snapshot from the specified. If no other policies are assigned it calls destroy snapshot. This will be + * used for manual snapshots too. */ - boolean deleteSnapshot(DeleteSnapshotCmd cmd); + boolean deleteSnapshot(DeleteSnapshotCmd cmd); /** * Creates a policy with specified schedule. maxSnaps specifies the number of most recent snapshots that are to be retained. - * If the number of snapshots go beyond maxSnaps the oldest snapshot is deleted - * @param cmd the command that + * If the number of snapshots go beyond maxSnaps the oldest snapshot is deleted + * + * @param cmd + * the command that * @return the newly created snapshot policy if success, null otherwise */ SnapshotPolicy createPolicy(CreateSnapshotPolicyCmd cmd); - + /** - * Get the recurring snapshots scheduled for this volume currently along with the time at which they are scheduled - * @param cmd the command wrapping the volumeId (volume for which the snapshots are required) and policyId (to show snapshots for only this policy). + * Get the recurring snapshots scheduled for this volume currently along with the time at which they are scheduled + * + * @param cmd + * the command wrapping the volumeId (volume for which the snapshots are required) and policyId (to show + * snapshots for only this policy). * @return The list of snapshot schedules. */ public List findRecurringSnapshotSchedule(ListRecurringSnapshotScheduleCmd cmd); /** * list all snapshot policies assigned to the specified volume - * @param cmd the command that specifies the volume criteria + * + * @param cmd + * the command that specifies the volume criteria * @return list of snapshot policies */ List listPoliciesforVolume(ListSnapshotPoliciesCmd cmd); - + boolean deleteSnapshotPolicies(DeleteSnapshotPoliciesCmd cmd); - + Snapshot allocSnapshot(CreateSnapshotCmd cmd) throws ResourceAllocationException; } diff --git a/api/src/com/cloud/template/TemplateService.java b/api/src/com/cloud/template/TemplateService.java index 3513989ea7c..c733ecc0f3a 100755 --- a/api/src/com/cloud/template/TemplateService.java +++ b/api/src/com/cloud/template/TemplateService.java @@ -30,48 +30,57 @@ import com.cloud.api.commands.ExtractTemplateCmd; import com.cloud.api.commands.RegisterIsoCmd; import com.cloud.api.commands.RegisterTemplateCmd; import com.cloud.exception.InternalErrorException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.StorageUnavailableException; public interface TemplateService { - + VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException; - VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws IllegalArgumentException, ResourceAllocationException; + + VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws IllegalArgumentException, ResourceAllocationException; + VirtualMachineTemplate copyIso(CopyIsoCmd cmd) throws StorageUnavailableException, ResourceAllocationException; + VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException; + boolean detachIso(DetachIsoCmd cmd); + boolean attachIso(AttachIsoCmd cmd); + /** * Deletes a template - * @param cmd - the command specifying templateId + * + * @param cmd + * - the command specifying templateId */ boolean deleteTemplate(DeleteTemplateCmd cmd); - + /** * Deletes a template - * @param cmd - the command specifying isoId + * + * @param cmd + * - the command specifying isoId * @return true if deletion is successful, false otherwise - * @throws InvalidParameterValueException, InternalErrorException, PermissionDeniedException */ boolean deleteIso(DeleteIsoCmd cmd); /** * Extracts an ISO - * @param cmd - the command specifying the mode and id of the ISO + * + * @param cmd + * - the command specifying the mode and id of the ISO * @return extractId. - * @throws InvalidParameterValueException, InternalErrorException, PermissionDeniedException */ - Long extract(ExtractIsoCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, InternalErrorException; - + Long extract(ExtractIsoCmd cmd) throws InternalErrorException; + /** * Extracts a Template - * @param cmd - the command specifying the mode and id of the template - * @return extractId. - * @throws InvalidParameterValueException, InternalErrorException, PermissionDeniedException + * + * @param cmd + * - the command specifying the mode and id of the template + * @return extractId */ - Long extract(ExtractTemplateCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, InternalErrorException; - + Long extract(ExtractTemplateCmd cmd) throws InternalErrorException; + VirtualMachineTemplate getTemplate(long templateId); } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 1cb936e0cff..b88338704d1 100644 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -35,51 +35,59 @@ import com.cloud.api.commands.UpdateUserCmd; import com.cloud.configuration.ResourceLimit; import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.utils.Pair; public interface AccountService { - + /** * Creates a new user, stores the password as is so encrypted passwords are recommended. - * @param cmd the create command that has the username, email, password, account name, domain, timezone, etc. for creating the user. + * + * @param cmd + * the create command that has the username, email, password, account name, domain, timezone, etc. for creating + * the user. * @return the user if created successfully, null otherwise */ UserAccount createAccount(CreateAccountCmd cmd); + /** * Deletes a user by userId - * @param cmd - the delete command defining the id of the user to be deleted. + * + * @param cmd + * - the delete command defining the id of the user to be deleted. * @return true if delete was successful, false otherwise */ boolean deleteUserAccount(DeleteAccountCmd cmd); /** * Disables a user by userId - * @param cmd the command wrapping the userId parameter + * + * @param cmd + * the command wrapping the userId parameter * @return UserAccount object - * @throws InvalidParameterValueException, PermissionDeniedException */ UserAccount disableUser(DisableUserCmd cmd); - + /** * Enables a user - * @param cmd - the command containing userId + * + * @param cmd + * - the command containing userId * @return UserAccount object - * @throws InvalidParameterValueException, PermissionDeniedException */ UserAccount enableUser(EnableUserCmd cmd); /** - * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses allocated/etc. + * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses allocated/etc. + * * @param userId * @return UserAccount object */ UserAccount lockUser(LockUserCmd cmd); - + /** * Update a user by userId + * * @param userId * @return UserAccount object */ @@ -87,76 +95,84 @@ public interface AccountService { /** * Disables an account by accountName and domainId - * @param disabled account if success + * + * @param disabled + * account if success * @return true if disable was successful, false otherwise - * @throws InvalidParameterValueException, PermissionDeniedException */ - Account disableAccount(DisableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, ResourceUnavailableException; + Account disableAccount(DisableAccountCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException; /** * Enables an account by accountId - * @param cmd - the enableAccount command defining the accountId to be deleted. + * + * @param cmd + * - the enableAccount command defining the accountId to be deleted. * @return account object - * @throws InvalidParameterValueException, PermissionDeniedException */ Account enableAccount(EnableAccountCmd cmd); /** - * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP addresses allocated/etc. - * @param cmd - the LockAccount command defining the accountId to be locked. + * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP addresses + * allocated/etc. + * + * @param cmd + * - the LockAccount command defining the accountId to be locked. * @return account object */ - Account lockAccount(DisableAccountCmd cmd); + Account lockAccount(DisableAccountCmd cmd); /** * Updates an account name - * @param cmd - the parameter containing accountId + * + * @param cmd + * - the parameter containing accountId * @return updated account object - * @throws InvalidParameterValueException, PermissionDeniedException */ - + Account updateAccount(UpdateAccountCmd cmd); - + /** * Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one. - * @param cmd the command that wraps the domainId, accountId, type, and max parameters + * + * @param cmd + * the command that wraps the domainId, accountId, type, and max parameters * @return the updated/created resource limit - * @throws InvalidParameterValueException */ - ResourceLimit updateResourceLimit(UpdateResourceLimitCmd cmd) throws InvalidParameterValueException; - + ResourceLimit updateResourceLimit(UpdateResourceLimitCmd cmd); + /** * Search for resource limits for the given id and/or account and/or type and/or domain. - * @param cmd the command wrapping the id, type, account, and domain + * + * @param cmd + * the command wrapping the id, type, account, and domain * @return a list of limits that match the criteria - * @throws InvalidParameterValueException - * @throws PermissionDeniedException */ - List searchForLimits(ListResourceLimitsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; - + List searchForLimits(ListResourceLimitsCmd cmd); + Account getSystemAccount(); - + User getSystemUser(); - + User createUser(CreateUserCmd cmd); - boolean deleteUser(DeleteUserCmd deleteUserCmd); - - boolean isAdmin(short accountType); - - Account finalizeOwner(Account caller, String accountName, Long domainId); - - Pair finalizeAccountDomainForList(Account caller, String accountName, Long domainId); - - Account getActiveAccount(String accountName, Long domainId); - - Account getActiveAccount(Long accountId); - - Account getAccount(Long accountId); - - User getActiveUser(long userId); - - Domain getDomain(long id); - - boolean isRootAdmin(short accountType); + + boolean deleteUser(DeleteUserCmd deleteUserCmd); + + boolean isAdmin(short accountType); + + Account finalizeOwner(Account caller, String accountName, Long domainId); + + Pair finalizeAccountDomainForList(Account caller, String accountName, Long domainId); + + Account getActiveAccount(String accountName, Long domainId); + + Account getActiveAccount(Long accountId); + + Account getAccount(Long accountId); + + User getActiveUser(long userId); + + Domain getDomain(long id); + + boolean isRootAdmin(short accountType); } diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java index da7d9e32985..340b82fb20b 100755 --- a/api/src/com/cloud/vm/UserVmService.java +++ b/api/src/com/cloud/vm/UserVmService.java @@ -38,213 +38,287 @@ import com.cloud.api.commands.UpgradeVMCmd; import com.cloud.dc.DataCenter; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ManagementServerException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; import com.cloud.exception.VirtualMachineMigrationException; +import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.offering.ServiceOffering; import com.cloud.storage.Volume; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -import com.cloud.host.Host; import com.cloud.utils.exception.ExecutionException; public interface UserVmService { /** * Destroys one virtual machine - * @param userId the id of the user performing the action - * @param vmId the id of the virtual machine. - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException + * + * @param userId + * the id of the user performing the action + * @param vmId + * the id of the virtual machine. + * @throws ConcurrentOperationException + * @throws ResourceUnavailableException */ UserVm destroyVm(DestroyVMCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException; - + /** * Destroys one virtual machine - * @param userId the id of the user performing the action - * @param vmId the id of the virtual machine. - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException + * + * @param userId + * the id of the user performing the action + * @param vmId + * the id of the virtual machine. + * @throws ConcurrentOperationException + * @throws ResourceUnavailableException */ UserVm destroyVm(long vmId) throws ResourceUnavailableException, ConcurrentOperationException; - + /** * Resets the password of a virtual machine. - * @param cmd - the command specifying vmId, password + * + * @param cmd + * - the command specifying vmId, password * @return the VM if reset worked successfully, null otherwise */ UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException; - + /** * Attaches the specified volume to the specified VM - * @param cmd - the command specifying volumeId and vmId + * + * @param cmd + * - the command specifying volumeId and vmId * @return the Volume object if attach worked successfully. - * @throws InvalidParameterValueException, PermissionDeniedException */ Volume attachVolumeToVM(AttachVolumeCmd cmd); - + /** * Detaches the specified volume from the VM it is currently attached to. - * @param cmd - the command specifying volumeId + * + * @param cmd + * - the command specifying volumeId * @return the Volume object if detach worked successfully. - * @throws InvalidParameterValueException */ Volume detachVolumeFromVM(DetachVolumeCmd cmmd); - - UserVm startVirtualMachine(StartVMCmd cmd) throws StorageUnavailableException, ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException; + + UserVm startVirtualMachine(StartVMCmd cmd) throws StorageUnavailableException, ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, + ResourceAllocationException; + UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException; + UserVm updateVirtualMachine(UpdateVMCmd cmd); + UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException; - + /** * Create a template database record in preparation for creating a private template. - * @param cmd the command object that defines the name, display text, snapshot/volume, bits, public/private, etc. - * for the private template + * + * @param cmd + * the command object that defines the name, display text, snapshot/volume, bits, public/private, etc. for the + * private template * @return the vm template object if successful, null otherwise - * @throws ResourceAllocationException - * @throws PermissionDeniedException - * @throws InvalidParameterValueException - * @throws PermissionDeniedException + * @throws ResourceAllocationException */ - VirtualMachineTemplate createPrivateTemplateRecord(CreateTemplateCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ResourceAllocationException; - + VirtualMachineTemplate createPrivateTemplateRecord(CreateTemplateCmd cmd) throws ResourceAllocationException; + /** * Creates a private template from a snapshot of a VM - * @param cmd - the command specifying snapshotId, name, description + * + * @param cmd + * - the command specifying snapshotId, name, description * @return a template if successfully created, null otherwise - * @throws InvalidParameterValueException */ VirtualMachineTemplate createPrivateTemplate(CreateTemplateCmd cmd); - + /** * Creates a Basic Zone User VM in the database and returns the VM to the caller. - * - * @param zone - availability zone for the virtual machine - * @param serviceOffering - the service offering for the virtual machine - * @param template - the template for the virtual machine - * @param securityGroupIdList - comma separated list of security groups id that going to be applied to the virtual machine - * @param accountName - an optional account for the virtual machine. Must be used with domainId - * @param domainId - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used - * @param hostName - host name for the virtual machine - * @param displayName - an optional user generated name for the virtual machine - * @param diskOfferingId - 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 indicate 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 - * @param diskSize - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId - * @param group - an optional group for the virtual machine - * @param hypervisor - the hypervisor on which to deploy the virtual machine - * @param userData - 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 - * @param sshKeyPair - name of the ssh key pair used to login to the virtual machine - * @param Host destinationHost to deploy the VM - * + * + * @param zone + * - availability zone for the virtual machine + * @param serviceOffering + * - the service offering for the virtual machine + * @param template + * - the template for the virtual machine + * @param securityGroupIdList + * - comma separated list of security groups id that going to be applied to the virtual machine + * @param accountName + * - an optional account for the virtual machine. Must be used with domainId + * @param domainId + * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used + * @param hostName + * - host name for the virtual machine + * @param displayName + * - an optional user generated name for the virtual machine + * @param diskOfferingId + * - 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 indicate 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 + * @param diskSize + * - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId + * @param group + * - an optional group for the virtual machine + * @param hypervisor + * - the hypervisor on which to deploy the virtual machine + * @param userData + * - 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 + * @param sshKeyPair + * - name of the ssh key pair used to login to the virtual machine + * @param Host + * destinationHost to deploy the VM + * * @return UserVm object if successful. * - * @throws InsufficientCapacityException if there is insufficient capacity to deploy the VM. - * @throws ConcurrentOperationException if there are multiple users working on the same VM or in the same environment. - * @throws ResourceUnavailableException if the resources required to deploy the VM is not currently available. - * @throws InsufficientResourcesException - */ - UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, - HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; - - + * @throws InsufficientCapacityException + * if there is insufficient capacity to deploy the VM. + * @throws ConcurrentOperationException + * if there are multiple users working on the same VM or in the same environment. + * @throws ResourceUnavailableException + * if the resources required to deploy the VM is not currently available. + * @throws InsufficientResourcesException + */ + UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, Account owner, String hostName, + String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + /** * Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the caller. - * - * @param zone - availability zone for the virtual machine - * @param serviceOffering - the service offering for the virtual machine - * @param template - the template for the virtual machine - * @param networkIdList - list of network ids used by virtual machine - * @param securityGroupIdList - comma separated list of security groups id that going to be applied to the virtual machine - * @param accountName - an optional account for the virtual machine. Must be used with domainId - * @param domainId - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used - * @param hostName - host name for the virtual machine - * @param displayName - an optional user generated name for the virtual machine - * @param diskOfferingId - 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 indicate 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 - * @param diskSize - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId - * @param group - an optional group for the virtual machine - * @param hypervisor - the hypervisor on which to deploy the virtual machine - * @param userData - 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 - * @param sshKeyPair - name of the ssh key pair used to login to the virtual machine - * @param Host destinationHost to deploy the VM + * + * @param zone + * - availability zone for the virtual machine + * @param serviceOffering + * - the service offering for the virtual machine + * @param template + * - the template for the virtual machine + * @param networkIdList + * - list of network ids used by virtual machine + * @param securityGroupIdList + * - comma separated list of security groups id that going to be applied to the virtual machine + * @param accountName + * - an optional account for the virtual machine. Must be used with domainId + * @param domainId + * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used + * @param hostName + * - host name for the virtual machine + * @param displayName + * - an optional user generated name for the virtual machine + * @param diskOfferingId + * - 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 indicate 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 + * @param diskSize + * - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId + * @param group + * - an optional group for the virtual machine + * @param hypervisor + * - the hypervisor on which to deploy the virtual machine + * @param userData + * - 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 + * @param sshKeyPair + * - name of the ssh key pair used to login to the virtual machine + * @param Host + * destinationHost to deploy the VM * * @return UserVm object if successful. * - * @throws InsufficientCapacityException if there is insufficient capacity to deploy the VM. - * @throws ConcurrentOperationException if there are multiple users working on the same VM or in the same environment. - * @throws ResourceUnavailableException if the resources required to deploy the VM is not currently available. - * @throws InsufficientResourcesException - */ - UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, List securityGroupIdList, - Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, - HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; - - + * @throws InsufficientCapacityException + * if there is insufficient capacity to deploy the VM. + * @throws ConcurrentOperationException + * if there are multiple users working on the same VM or in the same environment. + * @throws ResourceUnavailableException + * if the resources required to deploy the VM is not currently available. + * @throws InsufficientResourcesException + */ + UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, List securityGroupIdList, + Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + /** * Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the caller. - * - * @param zone - availability zone for the virtual machine - * @param serviceOffering - the service offering for the virtual machine - * @param template - the template for the virtual machine - * @param networkIdList - list of network ids used by virtual machine - * @param accountName - an optional account for the virtual machine. Must be used with domainId - * @param domainId - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used - * @param hostName - host name for the virtual machine - * @param displayName - an optional user generated name for the virtual machine - * @param diskOfferingId - 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 indicate 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 - * @param diskSize - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId - * @param group - an optional group for the virtual machine - * @param hypervisor - the hypervisor on which to deploy the virtual machine - * @param userData - 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 - * @param sshKeyPair - name of the ssh key pair used to login to the virtual machine - * @param Host destinationHost to deploy the VM + * + * @param zone + * - availability zone for the virtual machine + * @param serviceOffering + * - the service offering for the virtual machine + * @param template + * - the template for the virtual machine + * @param networkIdList + * - list of network ids used by virtual machine + * @param accountName + * - an optional account for the virtual machine. Must be used with domainId + * @param domainId + * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used + * @param hostName + * - host name for the virtual machine + * @param displayName + * - an optional user generated name for the virtual machine + * @param diskOfferingId + * - 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 indicate 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 + * @param diskSize + * - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId + * @param group + * - an optional group for the virtual machine + * @param hypervisor + * - the hypervisor on which to deploy the virtual machine + * @param userData + * - 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 + * @param sshKeyPair + * - name of the ssh key pair used to login to the virtual machine + * @param Host + * destinationHost to deploy the VM * * @return UserVm object if successful. * - * @throws InsufficientCapacityException if there is insufficient capacity to deploy the VM. - * @throws ConcurrentOperationException if there are multiple users working on the same VM or in the same environment. - * @throws ResourceUnavailableException if the resources required to deploy the VM is not currently available. - * @throws InsufficientResourcesException + * @throws InsufficientCapacityException + * if there is insufficient capacity to deploy the VM. + * @throws ConcurrentOperationException + * if there are multiple users working on the same VM or in the same environment. + * @throws ResourceUnavailableException + * if the resources required to deploy the VM is not currently available. + * @throws InsufficientResourcesException */ - UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, String hostName, - String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; - + UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, String hostName, + String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + /** * Starts the virtual machine created from createVirtualMachine. - * - * @param cmd Command to deploy. + * + * @param cmd + * Command to deploy. * @return UserVm object if successful. - * @throws InsufficientCapacityException if there is insufficient capacity to deploy the VM. - * @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. + * @throws InsufficientCapacityException + * if there is insufficient capacity to deploy the VM. + * @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(DeployVMCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException; - + /** * Creates a vm group. - * @param name - name of the group - * @param accountId - accountId + * + * @param name + * - name of the group + * @param accountId + * - accountId */ InstanceGroup createVmGroup(CreateVMGroupCmd cmd); @@ -252,42 +326,53 @@ public interface UserVmService { /** * upgrade the service offering of the virtual machine - * @param cmd - the command specifying vmId and new serviceOfferingId + * + * @param cmd + * - the command specifying vmId and new serviceOfferingId * @return the vm - * @throws InvalidParameterValueException */ UserVm upgradeVirtualMachine(UpgradeVMCmd cmd); - + UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException; - + UserVm startVirtualMachine(long vmId) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; void deletePrivateTemplateRecord(Long templateId); - + /** - * Obtains a list of virtual machines by the specified search criteria. - * Can search by: "userId", "name", "state", "dataCenterId", "podId", "hostId" - * @param cmd the API command that wraps the search criteria + * Obtains a list of virtual machines by the specified search criteria. Can search by: "userId", "name", "state", + * "dataCenterId", "podId", "hostId" + * + * @param cmd + * the API command that wraps the search criteria * @return List of UserVMs. */ List searchForUserVMs(ListVMsCmd cmd); - + HypervisorType getHypervisorTypeOfUserVM(long vmid); - - UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, - StorageUnavailableException, ResourceAllocationException; + + UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, + ResourceAllocationException; + UserVm getUserVm(long vmId); - + /** - * Migrate the given VM to the destination host provided. The API returns the migrated VM - * if migration succeeds. Only Root Admin can migrate a VM. - * @param UserVm vm The VM to migrate - * @param Host destinationHost to migrate the VM + * Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds. Only Root + * Admin can migrate a VM. + * + * @param UserVm + * vm The VM to migrate + * @param Host + * destinationHost to migrate the VM * @return UserVm migrated VM - * @throws ManagementServerException in case we get error finding the VM or host or access errors or other internal errors. - * @throws ConcurrentOperationException if there are multiple users working on the same VM. - * @throws ResourceUnavailableException if the destination host to migrate the VM is not currently available. - * @throws VirtualMachineMigrationException if the VM to be migrated is not in Running state + * @throws ManagementServerException + * in case we get error finding the VM or host or access errors or other internal errors. + * @throws ConcurrentOperationException + * if there are multiple users working on the same VM. + * @throws ResourceUnavailableException + * if the destination host to migrate the VM is not currently available. + * @throws VirtualMachineMigrationException + * if the VM to be migrated is not in Running state */ UserVm migrateVirtualMachine(UserVm vm, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException; } diff --git a/server/src/com/cloud/agent/manager/AgentManagerImpl.java b/server/src/com/cloud/agent/manager/AgentManagerImpl.java index e9b3654c86a..a387ce3d66b 100755 --- a/server/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/server/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -558,7 +558,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS } @Override - public List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { + public List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException { Long dcId = cmd.getZoneId(); Long podId = cmd.getPodId(); String clusterName = cmd.getClusterName(); @@ -935,7 +935,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS @Override @DB - public boolean deleteCluster(DeleteClusterCmd cmd) throws InvalidParameterValueException { + public boolean deleteCluster(DeleteClusterCmd cmd) { Transaction txn = Transaction.currentTxn(); try { txn.start(); @@ -970,7 +970,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS @Override @DB - public Cluster updateCluster(Cluster clusterToUpdate, String clusterType, String hypervisor, String allocationState) throws InvalidParameterValueException { + public Cluster updateCluster(Cluster clusterToUpdate, String clusterType, String hypervisor, String allocationState) { ClusterVO cluster = (ClusterVO) clusterToUpdate; // Verify cluster information and update the cluster if needed @@ -2012,7 +2012,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS } @Override - public Host cancelMaintenance(CancelMaintenanceCmd cmd) throws InvalidParameterValueException { + public Host cancelMaintenance(CancelMaintenanceCmd cmd) { Long hostId = cmd.getId(); // verify input parameters @@ -2113,7 +2113,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS } @Override - public Host maintain(PrepareForMaintenanceCmd cmd) throws InvalidParameterValueException { + public Host maintain(PrepareForMaintenanceCmd cmd) { Long hostId = cmd.getId(); HostVO host = _hostDao.findById(hostId); @@ -2455,7 +2455,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS } @Override - public Host updateHost(UpdateHostCmd cmd) throws InvalidParameterValueException { + public Host updateHost(UpdateHostCmd cmd) { Long hostId = cmd.getId(); Long guestOSCategoryId = cmd.getOsCategoryId(); diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index efaa35f6a52..47ed232fedf 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -504,7 +504,7 @@ public class ApiDBUtils { return _zoneDao.listAll(); } - public static boolean volumeIsOnSharedStorage(long volumeId) throws InvalidParameterValueException { + public static boolean volumeIsOnSharedStorage(long volumeId) { // Check that the volume is valid VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 83efc16dc66..1a60d0918b1 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -503,10 +503,10 @@ public class ApiResponseHelper implements ResponseGenerator { hostResponse.setZoneName(ApiDBUtils.findZoneById(host.getDataCenterId()).getName()); if (host.getPodId() != null) { - HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); - if(pod != null){ - hostResponse.setPodName(pod.getName()); - } + HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); + if (pod != null) { + hostResponse.setPodName(pod.getName()); + } } DecimalFormat decimalFormat = new DecimalFormat("#.##"); @@ -590,8 +590,8 @@ public class ApiResponseHelper implements ResponseGenerator { if (podId != null) { HostPodVO pod = ApiDBUtils.findPodById(podId); vlanResponse.setPodId(podId); - if(pod != null){ - vlanResponse.setPodName(pod.getName()); + if (pod != null) { + vlanResponse.setPodName(pod.getName()); } } @@ -891,10 +891,10 @@ public class ApiResponseHelper implements ResponseGenerator { } if (pool.getPodId() != null) { poolResponse.setPodId(pool.getPodId()); - HostPodVO pod = ApiDBUtils.findPodById(pool.getPodId()); - if(pod != null){ - poolResponse.setPodName(pod.getName()); - } + HostPodVO pod = ApiDBUtils.findPodById(pool.getPodId()); + if (pod != null) { + poolResponse.setPodName(pod.getName()); + } } if (pool.getCreated() != null) { poolResponse.setCreated(pool.getCreated()); @@ -934,9 +934,9 @@ public class ApiResponseHelper implements ResponseGenerator { clusterResponse.setClusterType(cluster.getClusterType().toString()); clusterResponse.setAllocationState(cluster.getAllocationState().toString()); HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); - if(pod != null){ - clusterResponse.setPodName(pod.getName()); - } + if (pod != null) { + clusterResponse.setPodName(pod.getName()); + } DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); clusterResponse.setZoneName(zone.getName()); clusterResponse.setObjectName("cluster"); @@ -1511,7 +1511,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (templateSize > 0) { templateResponse.setSize(templateSize); } - + templateResponse.setChecksum(template.getChecksum()); templateResponse.setObjectName("template"); @@ -1572,7 +1572,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setZoneId(zone.getId()); templateResponse.setZoneName(zone.getName()); templateResponse.setHypervisor(template.getHypervisorType().toString()); - templateResponse.setObjectName("template"); + templateResponse.setObjectName("template"); templateResponse.setChecksum(template.getChecksum()); responses.add(templateResponse); @@ -2199,10 +2199,10 @@ public class ApiResponseHelper implements ResponseGenerator { if (summedCapacity.getPodId() != null) { capacityResponse.setPodId(summedCapacity.getPodId()); if (summedCapacity.getPodId() > 0) { - HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); - if(pod != null){ - capacityResponse.setPodName(pod.getName()); - } + HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); + if (pod != null) { + capacityResponse.setPodName(pod.getName()); + } } else { capacityResponse.setPodName("All"); } @@ -2248,7 +2248,7 @@ public class ApiResponseHelper implements ResponseGenerator { } @Override - public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) throws InvalidParameterValueException { + public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) { AsyncJobResult result = ApiDBUtils._asyncMgr.queryAsyncJobResult(cmd); AsyncJobResponse response = new AsyncJobResponse(); response.setId(result.getJobId()); diff --git a/server/src/com/cloud/async/AsyncJobManager.java b/server/src/com/cloud/async/AsyncJobManager.java index 6a1c293a4ba..3251456fe9b 100644 --- a/server/src/com/cloud/async/AsyncJobManager.java +++ b/server/src/com/cloud/async/AsyncJobManager.java @@ -21,8 +21,6 @@ package com.cloud.async; import java.util.List; import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.utils.component.Manager; public interface AsyncJobManager extends Manager { @@ -50,5 +48,5 @@ public interface AsyncJobManager extends Manager { * @param cmd the command that specifies the job id * @return an async-call result object */ - public AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd) throws InvalidParameterValueException, PermissionDeniedException; + public AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd); } diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java index 75406340a07..f7260c4c373 100644 --- a/server/src/com/cloud/async/AsyncJobManagerImpl.java +++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java @@ -50,7 +50,6 @@ import com.cloud.cluster.StackMaid; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; @@ -273,7 +272,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } @Override - public AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd) { AsyncJobVO job = _jobDao.findById(cmd.getId()); if (job == null) { throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId()); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index e91878f9390..988457ae684 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -316,7 +316,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public Configuration updateConfiguration(UpdateCfgCmd cmd) throws InvalidParameterValueException { + public Configuration updateConfiguration(UpdateCfgCmd cmd) { Long userId = UserContext.current().getCallerUserId(); String name = cmd.getCfgName(); String value = cmd.getValue(); @@ -338,7 +338,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private String validateConfigurationValue(String name, String value) throws InvalidParameterValueException { + private String validateConfigurationValue(String name, String value) { if (value == null) { return null; } @@ -506,8 +506,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private void checkPodAttributes(long podId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationStateStr, boolean checkForDuplicates) - throws InvalidParameterValueException { + private void checkPodAttributes(long podId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationStateStr, boolean checkForDuplicates) { if (checkForDuplicates) { // Check if the pod already exists if (validPod(podName, zoneId)) { @@ -952,8 +951,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } - private void checkZoneParameters(String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, boolean checkForDuplicates, Long domainId, String allocationStateStr) - throws InvalidParameterValueException { + private void checkZoneParameters(String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, boolean checkForDuplicates, Long domainId, String allocationStateStr) { if (checkForDuplicates) { // Check if a zone with the specified name already exists if (validZone(zoneName)) { @@ -998,7 +996,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private void checkIpRange(String startIp, String endIp, String cidrAddress, long cidrSize) throws InvalidParameterValueException { + private void checkIpRange(String startIp, String endIp, String cidrAddress, long cidrSize) { if (!NetUtils.isValidIp(startIp)) { throw new InvalidParameterValueException("The start address of the IP range is not a valid IP address."); } @@ -1537,7 +1535,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_DISK_OFFERING_CREATE, eventDescription = "creating disk offering") - public DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized) throws InvalidParameterValueException { + public DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized) { long diskSize = 0;// special case for custom disk offerings if (numGibibytes != null && (numGibibytes <= 0)) { throw new InvalidParameterValueException("Please specify a disk size of at least 1 Gb."); @@ -1566,7 +1564,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd) throws InvalidParameterValueException { + public DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd) { String name = cmd.getOfferingName(); String description = cmd.getDisplayText(); Long numGibibytes = cmd.getDiskSize(); @@ -1585,7 +1583,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_DISK_OFFERING_EDIT, eventDescription = "updating disk offering") - public DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd) throws InvalidParameterValueException { + public DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd) { Long diskOfferingId = cmd.getId(); String name = cmd.getDiskOfferingName(); String displayText = cmd.getDisplayText(); @@ -1645,7 +1643,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_DISK_OFFERING_DELETE, eventDescription = "deleting disk offering") - public boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd) throws InvalidParameterValueException { + public boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd) { Long diskOfferingId = cmd.getId(); DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId); @@ -1664,7 +1662,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_SERVICE_OFFERING_DELETE, eventDescription = "deleting service offering") - public boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd) throws InvalidParameterValueException { + public boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd) { Long offeringId = cmd.getId(); Long userId = UserContext.current().getCallerUserId(); @@ -1690,7 +1688,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public String changePrivateIPRange(boolean add, long podId, String startIP, String endIP) throws InvalidParameterValueException { + public String changePrivateIPRange(boolean add, long podId, String startIP, String endIP) { checkPrivateIpRangeErrors(podId, startIP, endIP); long zoneId = _podDao.findById(podId).getDataCenterId(); @@ -2086,7 +2084,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId) throws InvalidParameterValueException { + public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId) { VlanVO vlan = _vlanDao.findById(vlanDbId); if (vlan == null) { throw new InvalidParameterValueException("Please specify a valid IP range id."); @@ -2285,7 +2283,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private void checkPublicIpRangeErrors(long zoneId, String vlanId, String vlanGateway, String vlanNetmask, String startIP, String endIP) throws InvalidParameterValueException { + private void checkPublicIpRangeErrors(long zoneId, String vlanId, String vlanGateway, String vlanNetmask, String startIP, String endIP) { // Check that the start and end IPs are valid if (!NetUtils.isValidIp(startIP)) { throw new InvalidParameterValueException("Please specify a valid start IP"); @@ -2317,7 +2315,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private void checkPrivateIpRangeErrors(Long podId, String startIP, String endIP) throws InvalidParameterValueException { + private void checkPrivateIpRangeErrors(Long podId, String startIP, String endIP) { HostPodVO pod = _podDao.findById(podId); if (pod == null) { throw new InvalidParameterValueException("Please specify a valid pod."); @@ -2373,7 +2371,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return pod.getCidrSize(); } - private void checkPodCidrSubnets(long dcId, HashMap> currentPodCidrSubnets) throws InvalidParameterValueException { + private void checkPodCidrSubnets(long dcId, HashMap> currentPodCidrSubnets) { // For each pod, return an error if any of the following is true: // 1. The pod's CIDR subnet conflicts with the guest network subnet // 2. The pod's CIDR subnet conflicts with the CIDR subnet of any other pod @@ -2494,7 +2492,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private String[] getLinkLocalIPRange() throws InvalidParameterValueException { + private String[] getLinkLocalIPRange() { String ipNums = _configDao.getValue("linkLocalIp.nums"); int nums = Integer.parseInt(ipNums); if (nums > 16 || nums <= 0) { @@ -2529,7 +2527,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DELETE, eventDescription = "deleting vlan ip range", async = false) - public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) throws InvalidParameterValueException { + public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) { Long vlanDbId = cmd.getId(); Long userId = UserContext.current().getCallerUserId(); @@ -2598,7 +2596,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd) throws InvalidParameterValueException { + public NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd) { Long userId = UserContext.current().getCallerUserId(); String name = cmd.getNetworkOfferingName(); String displayText = cmd.getDisplayText(); @@ -2763,7 +2761,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd) throws InvalidParameterValueException { + public boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd) { Long offeringId = cmd.getId(); // Verify network offering id @@ -2843,7 +2841,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } // Note: This method will be used for entity name validations in the coming releases (place holder for now) - private void validateEntityName(String str) throws InvalidParameterValueException { + private void validateEntityName(String str) { String forbidden = "~!@#$%^&*()+="; char[] searchChars = forbidden.toCharArray(); if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) { diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index a0d6def5104..1c9f4af8a6f 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -645,7 +645,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } @Override - public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) { Account caller = UserContext.current().getCaller(); Long ipId = cmd.getPublicIpId(); Long zoneId = cmd.getZoneId(); @@ -654,7 +654,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, Pair accountDomainPair = _accountMgr.finalizeAccountDomainForList(caller, cmd.getAccountName(), cmd.getDomainId()); String accountName = accountDomainPair.first(); Long domainId = accountDomainPair.second(); - + if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { Domain domain = _accountMgr.getDomain(caller.getDomainId()); path = domain.getPath(); diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 19a87603d6f..a3e9145aac8 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -323,7 +323,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian @Override @DB - public VirtualRouter upgradeRouter(UpgradeRouterCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public VirtualRouter upgradeRouter(UpgradeRouterCmd cmd) { Long routerId = cmd.getId(); Long serviceOfferingId = cmd.getServiceOfferingId(); Account account = UserContext.current().getCaller(); @@ -495,8 +495,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } @Override - public VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { + public VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { Account caller = UserContext.current().getCaller(); // verify parameters diff --git a/server/src/com/cloud/network/rules/RulesManager.java b/server/src/com/cloud/network/rules/RulesManager.java index f8829a8b6e2..eaba1bc1e0b 100644 --- a/server/src/com/cloud/network/rules/RulesManager.java +++ b/server/src/com/cloud/network/rules/RulesManager.java @@ -19,9 +19,7 @@ package com.cloud.network.rules; import java.util.List; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.user.Account; @@ -60,8 +58,8 @@ public interface RulesManager extends RulesService { */ void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException; - void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException; - void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException; + void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller); + void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller); boolean revokeAllRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException; diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index e4a68f24e6c..d5dd92d50c9 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -39,7 +39,6 @@ import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress; @@ -140,7 +139,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } @Override - public void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException { + public void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) { if (ipAddress == null || ipAddress.getAllocatedTime() == null || ipAddress.getAllocatedToAccountId() == null) { throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified."); } @@ -169,7 +168,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } @Override - public void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException { + public void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller) { if (userVm == null || rule == null) { return; } diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index aef5b7f2e32..84113071afe 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -454,7 +454,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG } @Override @DB @SuppressWarnings("rawtypes") - public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ + public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd){ Long groupId = cmd.getSecurityGroupId(); String protocol = cmd.getProtocol(); Integer startPort = cmd.getStartPort(); diff --git a/server/src/com/cloud/server/ConfigurationServer.java b/server/src/com/cloud/server/ConfigurationServer.java index 69292346ee0..46bce165a62 100644 --- a/server/src/com/cloud/server/ConfigurationServer.java +++ b/server/src/com/cloud/server/ConfigurationServer.java @@ -19,7 +19,6 @@ package com.cloud.server; import com.cloud.exception.InternalErrorException; -import com.cloud.exception.InvalidParameterValueException; /** * ConfigurationServer is the public interface to talk to the Configuration Server. @@ -32,5 +31,5 @@ public interface ConfigurationServer { * Persists default values for the configuration table, pods/zones, and VLANs * @return */ - public void persistDefaultValues() throws InvalidParameterValueException, InternalErrorException; + public void persistDefaultValues() throws InternalErrorException; } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 6c57d4fcb32..9e797946482 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -114,7 +114,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } @Override @DB - public void persistDefaultValues() throws InvalidParameterValueException, InternalErrorException { + public void persistDefaultValues() throws InternalErrorException { // Create system user and admin user saveUser(); @@ -558,7 +558,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } @DB - protected HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException { + protected HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp) throws InternalErrorException { String[] cidrPair = cidr.split("\\/"); String cidrAddress = cidrPair[0]; int cidrSize = Integer.parseInt(cidrPair[1]); @@ -618,7 +618,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { return pod; } - private DiskOfferingVO createDiskOffering(Long domainId, String name, String description, int numGibibytes, String tags) throws InvalidParameterValueException { + private DiskOfferingVO createDiskOffering(Long domainId, String name, String description, int numGibibytes, String tags) { long diskSize = numGibibytes * 1024; tags = cleanupTags(tags); diff --git a/server/src/com/cloud/server/ManagementServer.java b/server/src/com/cloud/server/ManagementServer.java index 4fd92ada8e0..4c1f452188b 100755 --- a/server/src/com/cloud/server/ManagementServer.java +++ b/server/src/com/cloud/server/ManagementServer.java @@ -31,7 +31,6 @@ import com.cloud.dc.VlanVO; import com.cloud.domain.DomainVO; import com.cloud.event.EventVO; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.HostVO; @@ -58,11 +57,9 @@ import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; - /** - * ManagementServer is the interface to talk to the Managment Server. - * This will be the line drawn between the UI and MS. If we need to build - * a wire protocol, it will be built on top of this java interface. + * ManagementServer is the interface to talk to the Managment Server. This will be the line drawn between the UI and MS. If we + * need to build a wire protocol, it will be built on top of this java interface. */ public interface ManagementServer extends ManagementService { @@ -85,35 +82,41 @@ public interface ManagementServer extends ManagementService { /** * Authenticates a user when s/he logs in. - * @param username required username for authentication - * @param password password to use for authentication, can be null for single sign-on case - * @param domainId id of domain where user with username resides - * @param requestParameters the request parameters of the login request, which should contain timestamp of when the request signature is made, and the signature itself in the single sign-on case + * + * @param username + * required username for authentication + * @param password + * password to use for authentication, can be null for single sign-on case + * @param domainId + * id of domain where user with username resides + * @param requestParameters + * the request parameters of the login request, which should contain timestamp of when the request signature is + * made, and the signature itself in the single sign-on case * @return a user object, null if the user failed to authenticate */ UserAccount authenticateUser(String username, String password, Long domainId, Map requestParameters); - - String updateAdminPassword(long userId, String oldPassword, String newPassword); /** * Locate a user by their apiKey - * @param apiKey that was created for a particular user + * + * @param apiKey + * that was created for a particular user * @return the user/account pair if one exact match was found, null otherwise */ Pair findUserByApiKey(String apiKey); /** * Get an account by the accountId + * * @param accountId * @return the account, or null if not found */ Account getAccount(long accountId); /** - * Gets Volume statistics. The array returned will contain VolumeStats in the same order - * as the array of volumes requested. + * Gets Volume statistics. The array returned will contain VolumeStats in the same order as the array of volumes requested. * * @param volId * @return array of VolumeStats @@ -122,6 +125,7 @@ public interface ManagementServer extends ManagementService { /** * If the specified VLAN is associated with the pod, returns the pod ID. Else, returns null. + * * @param vlanDbId * @return pod ID, or null */ @@ -129,16 +133,21 @@ public interface ManagementServer extends ManagementService { /** * Return a list of IP addresses + * * @param accountId - * @param allocatedOnly - if true, will only list IPs that are allocated to the specified account - * @param zoneId - if specified, will list IPs in this zone - * @param vlanDbId - if specified, will list IPs in this VLAN + * @param allocatedOnly + * - if true, will only list IPs that are allocated to the specified account + * @param zoneId + * - if specified, will list IPs in this zone + * @param vlanDbId + * - if specified, will list IPs in this VLAN * @return list of IP addresses */ List listPublicIpAddressesBy(Long accountId, boolean allocatedOnly, Long zoneId, Long vlanDbId); - + /** * Return a list of private IP addresses that have been allocated to the given pod and zone + * * @param podId * @param zoneId * @return list of private IP addresses @@ -147,60 +156,71 @@ public interface ManagementServer extends ManagementService { /** * Attaches an ISO to the virtual CDROM device of the specified VM. Will fail if the VM already has an ISO mounted. + * * @param vmId * @param userId * @param isoId - * @param attach whether to attach or detach the iso from the instance + * @param attach + * whether to attach or detach the iso from the instance * @return */ boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach); /** * Retrieves a host by id + * * @param hostId * @return Host */ HostVO getHostBy(long hostId); - + /** * Retrieves all Events between the start and end date specified * - * @param userId unique id of the user, pass in -1 to retrieve events for all users - * @param accountId unique id of the account (which could be shared by many users), pass in -1 to retrieve events for all accounts - * @param domainId the id of the domain in which to search for users (useful when -1 is passed in for userId) - * @param type the type of the event. - * @param level INFO, WARN, or ERROR - * @param startDate inclusive. - * @param endDate inclusive. If date specified is greater than the current time, the - * system will use the current time. + * @param userId + * unique id of the user, pass in -1 to retrieve events for all users + * @param accountId + * unique id of the account (which could be shared by many users), pass in -1 to retrieve events for all accounts + * @param domainId + * the id of the domain in which to search for users (useful when -1 is passed in for userId) + * @param type + * the type of the event. + * @param level + * INFO, WARN, or ERROR + * @param startDate + * inclusive. + * @param endDate + * inclusive. If date specified is greater than the current time, the system will use the current time. * @return List of events */ List getEvents(long userId, long accountId, Long domainId, String type, String level, Date startDate, Date endDate); - + /** * returns the instance id of this management server. + * * @return id of the management server */ long getId(); - + /** - * Searches for Zones by the specified search criteria - * Can search by: zone name + * Searches for Zones by the specified search criteria Can search by: zone name + * * @param c * @return List of Zones */ List searchForZones(Criteria c); - + /** * Searches for servers that are either Down or in Alert state + * * @param c * @return List of Hosts */ List searchForAlertServers(Criteria c); - + /** - * Search for templates by the specified search criteria - * Can search by: "name", "ready", "isPublic" + * Search for templates by the specified search criteria Can search by: "name", "ready", "isPublic" + * * @param c * @return List of VMTemplates */ @@ -208,6 +228,7 @@ public interface ManagementServer extends ManagementService { /** * Obtains pods that match the data center ID + * * @param dataCenterId * @return List of Pods */ @@ -215,22 +236,23 @@ public interface ManagementServer extends ManagementService { /** * Change a pod's private IP range + * * @param op * @param podId * @param startIP * @param endIP * @return Message to display to user - * @throws InvalidParameterValueException if unable to add private ip range */ String changePrivateIPRange(boolean add, Long podId, String startIP, String endIP); - + /** * Finds a user by their user ID. + * * @param ownerId * @return User */ User findUserById(Long userId); - + /** * Gets user by id. * @@ -239,16 +261,18 @@ public interface ManagementServer extends ManagementService { * @return */ User getUser(long userId, boolean active); - + /** * Obtains a list of virtual machines that are similar to the VM with the specified name. + * * @param vmInstanceName * @return List of VMInstances */ List findVMInstancesLike(String vmInstanceName); - + /** * Finds a virtual machine instance with the specified Volume ID. + * * @param volumeId * @return VMInstance */ @@ -256,6 +280,7 @@ public interface ManagementServer extends ManagementService { /** * Finds a guest virtual machine instance with the specified ID. + * * @param userVmId * @return UserVmVO */ @@ -263,201 +288,238 @@ public interface ManagementServer extends ManagementService { /** * Finds a service offering with the specified ID. + * * @param offeringId * @return ServiceOffering */ ServiceOfferingVO findServiceOfferingById(long offeringId); - + /** * Obtains a list of all service offerings. + * * @return List of ServiceOfferings */ List listAllServiceOfferings(); - + /** * Obtains a list of all active hosts. + * * @return List of Hosts. */ List listAllActiveHosts(); - + /** * Finds a data center with the specified ID. + * * @param dataCenterId * @return DataCenter */ DataCenterVO findDataCenterById(long dataCenterId); - + /** * Finds a template by the specified ID. + * * @param templateId * @return A VMTemplate */ VMTemplateVO findTemplateById(long templateId); - + List listPendingEvents(int entryTime, int duration); - + /** * Obtains a list of routers by the specified host ID. + * * @param hostId * @return List of DomainRouters. */ List listRoutersByHostId(long hostId); - + /** * Obtains a list of all active routers. + * * @return List of DomainRouters */ List listAllActiveRouters(); - + List searchForConsoleProxy(Criteria c); - + /** * Finds a pod by the specified ID. + * * @param podId * @return HostPod */ HostPodVO findHostPodById(long podId); - + /** * Finds a secondary storage host in the specified zone + * * @param zoneId * @return Host */ HostVO findSecondaryStorageHosT(long zoneId); - + /** - * Obtains a list of billing records by the specified search criteria. - * Can search by: "userId", "startDate", "endDate" + * Obtains a list of billing records by the specified search criteria. Can search by: "userId", "startDate", "endDate" + * * @param c - * @return List of Billings. - List searchForUsage(Criteria c); + * @return List of Billings. List searchForUsage(Criteria c); */ - + /** * Obtains a list of all templates. + * * @return list of VMTemplates */ List listAllTemplates(); - + /** * Logs out a user + * * @param userId */ void logoutUser(Long userId); - ConsoleProxyInfo getConsoleProxy(long dataCenterId, long userVmId); - ConsoleProxyVO startConsoleProxy(long instanceId); - ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException; - ConsoleProxyVO rebootConsoleProxy(long instanceId); - String getConsoleAccessUrlRoot(long vmId); - ConsoleProxyVO findConsoleProxyById(long instanceId); - VMInstanceVO findSystemVMById(long instanceId); - VirtualMachine startSystemVm(long vmId); + ConsoleProxyInfo getConsoleProxy(long dataCenterId, long userVmId); - /** - * Returns a configuration value with the specified name - * @param name - * @return configuration value - */ - String getConfigurationValue(String name); - - /** - * Returns the vnc port of the vm. - * - * @param VirtualMachine vm - * @return the vnc port if found; -1 if unable to find. - */ - Pair getVncPort(VirtualMachine vm); + ConsoleProxyVO startConsoleProxy(long instanceId); + + ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException; + + ConsoleProxyVO rebootConsoleProxy(long instanceId); + + String getConsoleAccessUrlRoot(long vmId); + + ConsoleProxyVO findConsoleProxyById(long instanceId); + + VMInstanceVO findSystemVMById(long instanceId); + + VirtualMachine startSystemVm(long vmId); + + /** + * Returns a configuration value with the specified name + * + * @param name + * @return configuration value + */ + String getConfigurationValue(String name); + + /** + * Returns the vnc port of the vm. + * + * @param VirtualMachine + * vm + * @return the vnc port if found; -1 if unable to find. + */ + Pair getVncPort(VirtualMachine vm); /** * find the domain Id associated with the given account - * @param accountId the id of the account to use to look up the domain + * + * @param accountId + * the id of the account to use to look up the domain */ Long findDomainIdByAccountId(Long accountId); /** * find the domain by its path - * @param domainPath the path to use to lookup a domain + * + * @param domainPath + * the path to use to lookup a domain * @return domainVO the domain with the matching path, or null if no domain with the given path exists */ DomainVO findDomainByPath(String domainPath); /** * Finds accounts with account identifiers similar to the parameter + * * @param accountName * @return list of Accounts */ List findAccountsLike(String accountName); - + /** * Finds accounts with account identifier + * * @param accountName * @return an account that is active (not deleted) */ Account findActiveAccountByName(String accountName); - + /** * Finds accounts with account identifier - * @param accountName, domainId + * + * @param accountName + * , domainId * @return an account that is active (not deleted) */ - + Account findActiveAccount(String accountName, Long domainId); - + /** * Finds accounts with account identifier + * * @param accountName * @param domainId * @return an account that may or may not have been deleted */ Account findAccountByName(String accountName, Long domainId); - + /** * Finds an account by the ID. + * * @param accountId * @return Account */ Account findAccountById(Long accountId); - + /** * Deletes a Limit - * @param limitId - the database ID of the Limit + * + * @param limitId + * - the database ID of the Limit * @return true if successful, false if not */ boolean deleteLimit(Long limitId); - + /** * Finds limit by id - * @param limitId - the database ID of the Limit + * + * @param limitId + * - the database ID of the Limit * @return LimitVO object */ ResourceLimitVO findLimitById(long limitId); - + /** * Lists ISOs that are available for the specified account ID. + * * @param accountId * @param accountType * @return a list of ISOs (VMTemplateVO objects) */ List listIsos(Criteria c); - + public long getMemoryUsagebyHost(Long hostId); - + /** * Finds a diskOffering by the specified ID. + * * @param diskOfferingId * @return A DiskOffering */ DiskOfferingVO findDiskOfferingById(long diskOffering); /** - * Finds the obj associated with the private disk offering + * Finds the obj associated with the private disk offering + * * @return -- vo obj for private disk offering */ List findPrivateDiskOffering(); /** * List private templates for which the given account/domain has been granted permission to launch instances + * * @param accountId * @return */ @@ -465,57 +527,67 @@ public interface ManagementServer extends ManagementService { /** * - * @param jobId async-call job id + * @param jobId + * async-call job id * @return async-call result object */ AsyncJobResult queryAsyncJobResult(long jobId); - AsyncJobVO findAsyncJobById(long jobId); String[] getApiConfig(); - StoragePoolVO findPoolById(Long id); - List searchForStoragePools(Criteria c); - /** - * Return whether a domain is a child domain of a given domain. - * @param parentId - * @param childId - * @return True if the domainIds are equal, or if the second domain is a child of the first domain. False otherwise. - */ + StoragePoolVO findPoolById(Long id); + + List searchForStoragePools(Criteria c); + + /** + * Return whether a domain is a child domain of a given domain. + * + * @param parentId + * @param childId + * @return True if the domainIds are equal, or if the second domain is a child of the first domain. False otherwise. + */ boolean isChildDomain(Long parentId, Long childId); - List searchForSecondaryStorageVm(Criteria c); + List searchForSecondaryStorageVm(Criteria c); SecurityGroupVO findNetworkGroupByName(Long accountId, String groupName); /** * Find a network group by id - * @param networkGroupId id of group to lookup + * + * @param networkGroupId + * id of group to lookup * @return the network group if found, null otherwise */ SecurityGroupVO findNetworkGroupById(long networkGroupId); - List searchForStoragePoolDetails(long poolId, String value); - - boolean checkLocalStorageConfigVal(); + List searchForStoragePoolDetails(long poolId, String value); - VolumeVO findVolumeByInstanceAndDeviceId(long instanceId, long deviceId); + boolean checkLocalStorageConfigVal(); + + VolumeVO findVolumeByInstanceAndDeviceId(long instanceId, long deviceId); InstanceGroupVO getGroupForVm(long vmId); - List searchForZoneWideVlans(long dcId, String vlanType,String vlanId); + List searchForZoneWideVlans(long dcId, String vlanType, String vlanId); - /* - * Fetches the version of cloud stack + /* + * Fetches the version of cloud stack */ @Override String getVersion(); GuestOSVO getGuestOs(Long guestOsId); + VolumeVO getRootVolume(Long instanceId); + long getPsMaintenanceCount(long podId); + boolean isPoolUp(long instanceId); + boolean checkIfMaintenable(long hostId); + String getHashKey(); } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index c2dfdd6bd80..cee74092028 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -73,7 +73,6 @@ import com.cloud.alert.AlertManager; import com.cloud.alert.AlertVO; import com.cloud.alert.dao.AlertDao; import com.cloud.api.ApiDBUtils; -import com.cloud.api.BaseCmd; import com.cloud.api.commands.CreateDomainCmd; import com.cloud.api.commands.CreateSSHKeyPairCmd; import com.cloud.api.commands.DeleteDomainCmd; @@ -193,7 +192,6 @@ import com.cloud.network.dao.NetworkDao; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.dao.SecurityGroupDao; -import com.cloud.offering.ServiceOffering; import com.cloud.server.auth.UserAuthenticator; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; @@ -281,13 +279,13 @@ import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; -public class ManagementServerImpl implements ManagementServer { +public class ManagementServerImpl implements ManagementServer { public static final Logger s_logger = Logger.getLogger(ManagementServerImpl.class.getName()); private final AccountManager _accountMgr; private final AgentManager _agentMgr; private final ConfigurationManager _configMgr; - private final SecurityGroupDao _networkSecurityGroupDao; + private final SecurityGroupDao _networkSecurityGroupDao; private final IPAddressDao _publicIpAddressDao; private final DataCenterIpAddressDao _privateIpAddressDao; private final DomainRouterDao _routerDao; @@ -341,7 +339,6 @@ public class ManagementServerImpl implements ManagementServer { private final CertificateDao _certDao; private final SSHKeyPairDao _sshKeyPairDao; - private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); private final StatsCollector _statsCollector; @@ -351,11 +348,11 @@ public class ManagementServerImpl implements ManagementServer { private final int _routerRamSize; private final int _proxyRamSize; private final int _ssRamSize; - + private final Map _availableIdsMap; - private String _hashKey = null; - + private String _hashKey = null; + protected ManagementServerImpl() { ComponentLocator locator = ComponentLocator.getLocator(Name); _configDao = locator.getDao(ConfigurationDao.class); @@ -379,7 +376,7 @@ public class ManagementServerImpl implements ManagementServer { _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class); _secStorageVmMgr = locator.getManager(SecondaryStorageVmManager.class); _storageMgr = locator.getManager(StorageManager.class); - _networkSecurityGroupDao = locator.getDao(SecurityGroupDao.class); + _networkSecurityGroupDao = locator.getDao(SecurityGroupDao.class); _publicIpAddressDao = locator.getDao(IPAddressDao.class); _privateIpAddressDao = locator.getDao(DataCenterIpAddressDao.class); _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); @@ -413,7 +410,7 @@ public class ManagementServerImpl implements ManagementServer { _sshKeyPairDao = locator.getDao(SSHKeyPairDao.class); _itMgr = locator.getManager(VirtualMachineManager.class); _networkMgr = locator.getManager(NetworkManager.class); - + _userAuthenticators = locator.getAdapters(UserAuthenticator.class); if (_userAuthenticators == null || !_userAuthenticators.isSet()) { s_logger.error("Unable to find an user authenticator."); @@ -424,24 +421,24 @@ public class ManagementServerImpl implements ManagementServer { // Parse the max number of UserVMs and public IPs from server-setup.xml, // and set them in the right places - _routerRamSize = NumbersUtil.parseInt(_configs.get("router.ram.size"),VirtualNetworkApplianceManager.DEFAULT_ROUTER_VM_RAMSIZE); + _routerRamSize = NumbersUtil.parseInt(_configs.get("router.ram.size"), VirtualNetworkApplianceManager.DEFAULT_ROUTER_VM_RAMSIZE); _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); _statsCollector = StatsCollector.getInstance(_configs); _purgeDelay = NumbersUtil.parseInt(_configs.get("event.purge.delay"), 0); - if(_purgeDelay != 0){ + if (_purgeDelay != 0) { _eventExecutor.scheduleAtFixedRate(new EventPurgeTask(), cleanup, cleanup, TimeUnit.SECONDS); } - + String[] availableIds = TimeZone.getAvailableIDs(); _availableIdsMap = new HashMap(availableIds.length); - for (String id: availableIds) { + for (String id : availableIds) { _availableIdsMap.put(id, true); } } - + protected Map getConfigs() { return _configs; } @@ -539,38 +536,38 @@ public class ManagementServerImpl implements ManagementServer { if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to log in user: " + username + " in domain " + domainId); } - + // We only use the first adapter even if multiple have been configured Enumeration en = _userAuthenticators.enumeration(); UserAuthenticator authenticator = en.nextElement(); boolean authenticated = authenticator.authenticate(username, password, domainId); if (authenticated) { - UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId); - if (userAccount == null) { - s_logger.warn("Unable to find an authenticated user with username " + username + " in domain " + domainId); - return null; - } + UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId); + if (userAccount == null) { + s_logger.warn("Unable to find an authenticated user with username " + username + " in domain " + domainId); + return null; + } - DomainVO domain = _domainDao.findById(domainId); - String domainName = null; - if(domain != null) { - domainName = domain.getName(); - } - - if (!userAccount.getState().equalsIgnoreCase(Account.State.enabled.toString()) || !userAccount.getAccountState().equalsIgnoreCase(Account.State.enabled.toString())) { - if (s_logger.isInfoEnabled()) { - s_logger.info("User " + username + " in domain " + domainName + " is disabled/locked (or account is disabled/locked)"); - } - throw new CloudAuthenticationException("User " + username + " in domain " + domainName + " is disabled/locked (or account is disabled/locked)"); - //return null; - } - return userAccount; + DomainVO domain = _domainDao.findById(domainId); + String domainName = null; + if (domain != null) { + domainName = domain.getName(); + } + + if (!userAccount.getState().equalsIgnoreCase(Account.State.enabled.toString()) || !userAccount.getAccountState().equalsIgnoreCase(Account.State.enabled.toString())) { + if (s_logger.isInfoEnabled()) { + s_logger.info("User " + username + " in domain " + domainName + " is disabled/locked (or account is disabled/locked)"); + } + throw new CloudAuthenticationException("User " + username + " in domain " + domainName + " is disabled/locked (or account is disabled/locked)"); + // return null; + } + return userAccount; } else { - if (s_logger.isDebugEnabled()) { + if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to authenticate user with username " + username + " in domain " + domainId); } - return null; + return null; } } @@ -595,22 +592,22 @@ public class ManagementServerImpl implements ManagementServer { return account; } - + @Override public String[] createApiKeyAndSecretKey(RegisterCmd cmd) { - Long userId = cmd.getId(); - User user = _userDao.findById(userId); + Long userId = cmd.getId(); + User user = _userDao.findById(userId); - if (user == null) { - throw new InvalidParameterValueException("unable to find user for id : " + userId); - } + if (user == null) { + throw new InvalidParameterValueException("unable to find user for id : " + userId); + } - // generate both an api key and a secret key, update the user table with the keys, return the keys to the user - String[] keys = new String[2]; - keys[0] = createApiKey(userId); - keys[1] = createSecretKey(userId); + // generate both an api key and a secret key, update the user table with the keys, return the keys to the user + String[] keys = new String[2]; + keys[0] = createApiKey(userId); + keys[1] = createSecretKey(userId); - return keys; + return keys; } private String createApiKey(Long userId) { @@ -702,13 +699,13 @@ public class ManagementServerImpl implements ManagementServer { @Override public String generateRandomPassword() { - return PasswordGenerator.generateRandomPassword(6); + return PasswordGenerator.generateRandomPassword(6); } @Override public boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach) { - UserVmVO vm = _userVmDao.findById(vmId); - VMTemplateVO iso = _templateDao.findById(isoId); + UserVmVO vm = _userVmDao.findById(vmId); + VMTemplateVO iso = _templateDao.findById(isoId); boolean success = _vmMgr.attachISOToVM(vmId, isoId, attach); if (success) { @@ -723,79 +720,76 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List listDataCenters(ListZonesByCmd cmd) { - Account account = UserContext.current().getCaller(); + public List listDataCenters(ListZonesByCmd cmd) { + Account account = UserContext.current().getCaller(); List dcs = null; - Long domainId = cmd.getDomainId(); - Long id = cmd.getId(); - boolean removeDisabledZones = false; - if(domainId != null){ - //for domainId != null - //right now, we made the decision to only list zones associated with this domain - dcs = _dcDao.findZonesByDomainId(domainId); //private zones - } - else if((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)){ - dcs = _dcDao.listAll(); //all zones - }else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL){ - //it was decided to return all zones for the user's domain, and everything above till root - //list all zones belonging to this domain, and all of its parents - //check the parent, if not null, add zones for that parent to list - dcs = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true){ - dcs.addAll(_dcDao.findZonesByDomainId(domainRecord.getId())); - if(domainRecord.getParent() != null) { + Long domainId = cmd.getDomainId(); + Long id = cmd.getId(); + boolean removeDisabledZones = false; + if (domainId != null) { + // for domainId != null + // right now, we made the decision to only list zones associated with this domain + dcs = _dcDao.findZonesByDomainId(domainId); // private zones + } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { + dcs = _dcDao.listAll(); // all zones + } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) { + // it was decided to return all zones for the user's domain, and everything above till root + // list all zones belonging to this domain, and all of its parents + // check the parent, if not null, add zones for that parent to list + dcs = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + dcs.addAll(_dcDao.findZonesByDomainId(domainRecord.getId())); + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; } - } - } - //add all public zones too - dcs.addAll(_dcDao.listPublicZones()); - removeDisabledZones = true; - }else if(account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN){ - //it was decided to return all zones for the domain admin, and everything above till root - dcs = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - //this covers path till root - if(domainRecord != null) - { - DomainVO localRecord = domainRecord; - while(true){ - dcs.addAll(_dcDao.findZonesByDomainId(localRecord.getId())); - if(localRecord.getParent() != null) { + } + } + // add all public zones too + dcs.addAll(_dcDao.listPublicZones()); + removeDisabledZones = true; + } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // it was decided to return all zones for the domain admin, and everything above till root + dcs = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + // this covers path till root + if (domainRecord != null) { + DomainVO localRecord = domainRecord; + while (true) { + dcs.addAll(_dcDao.findZonesByDomainId(localRecord.getId())); + if (localRecord.getParent() != null) { localRecord = _domainDao.findById(localRecord.getParent()); } else { break; } - } - } - //this covers till leaf - if(domainRecord != null){ - //find all children for this domain based on a like search by path - List allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId()); - List allChildDomainIds = new ArrayList(); - //create list of domainIds for search - for(DomainVO domain : allChildDomains){ - allChildDomainIds.add(domain.getId()); - } - //now make a search for zones based on this - if(allChildDomainIds.size() > 0){ - List childZones = _dcDao.findChildZones((allChildDomainIds.toArray())); - dcs.addAll(childZones); - } - } - //add all public zones too - dcs.addAll(_dcDao.listPublicZones()); - removeDisabledZones = true; - } - - if(removeDisabledZones){ - dcs.removeAll(_dcDao.listDisabledZones()); - } + } + } + // this covers till leaf + if (domainRecord != null) { + // find all children for this domain based on a like search by path + List allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId()); + List allChildDomainIds = new ArrayList(); + // create list of domainIds for search + for (DomainVO domain : allChildDomains) { + allChildDomainIds.add(domain.getId()); + } + // now make a search for zones based on this + if (allChildDomainIds.size() > 0) { + List childZones = _dcDao.findChildZones((allChildDomainIds.toArray())); + dcs.addAll(childZones); + } + } + // add all public zones too + dcs.addAll(_dcDao.listPublicZones()); + removeDisabledZones = true; + } + + if (removeDisabledZones) { + dcs.removeAll(_dcDao.listDisabledZones()); + } Boolean available = cmd.isAvailable(); if (account != null) { @@ -816,7 +810,7 @@ public class ManagementServerImpl implements ManagementServer { } } } - + if (id != null) { List singleZone = new ArrayList(); for (DataCenterVO zone : dcs) { @@ -825,7 +819,7 @@ public class ManagementServerImpl implements ManagementServer { } } return singleZone; - } + } return dcs; } @@ -839,7 +833,7 @@ public class ManagementServerImpl implements ManagementServer { return MacAddress.getMacAddress().toLong(); } - protected void checkPortParameters(String publicPort, String privatePort, String privateIp, String proto) throws InvalidParameterValueException { + protected void checkPortParameters(String publicPort, String privatePort, String privateIp, String proto) { if (!NetUtils.isValidPort(publicPort)) { throw new InvalidParameterValueException("publicPort is an invalid value"); @@ -848,17 +842,16 @@ public class ManagementServerImpl implements ManagementServer { throw new InvalidParameterValueException("privatePort is an invalid value"); } -// s_logger.debug("Checking if " + privateIp + " is a valid private IP address. Guest IP address is: " + _configs.get("guest.ip.network")); -// -// if (!NetUtils.isValidPrivateIp(privateIp, _configs.get("guest.ip.network"))) { -// throw new InvalidParameterValueException("Invalid private ip address"); -// } + // s_logger.debug("Checking if " + privateIp + " is a valid private IP address. Guest IP address is: " + + // _configs.get("guest.ip.network")); + // + // if (!NetUtils.isValidPrivateIp(privateIp, _configs.get("guest.ip.network"))) { + // throw new InvalidParameterValueException("Invalid private ip address"); + // } if (!NetUtils.isValidProto(proto)) { throw new InvalidParameterValueException("Invalid protocol"); } } - - @Override public List getEvents(long userId, long accountId, Long domainId, String type, String level, Date startDate, Date endDate) { @@ -914,7 +907,7 @@ public class ManagementServerImpl implements ManagementServer { // default domainId to the admin's domain domainId = ((account == null) ? DomainVO.ROOT_DOMAIN : account.getDomainId()); } - + Filter searchFilter = new Filter(UserAccountVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); Long id = cmd.getId(); @@ -927,16 +920,16 @@ public class ManagementServerImpl implements ManagementServer { SearchBuilder sb = _userAccountDao.createSearchBuilder(); sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE); if (id != null && id == 1) { - //system user should NOT be searchable + // system user should NOT be searchable List emptyList = new ArrayList(); return emptyList; } else if (id != null) { sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - } else { - //this condition is used to exclude system user from the search results + } else { + // this condition is used to exclude system user from the search results sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ); - } - + } + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); @@ -970,7 +963,7 @@ public class ManagementServerImpl implements ManagementServer { if (id != null) { sc.setParameters("id", id); } else { - //Don't return system user, search builder with NEQ + // Don't return system user, search builder with NEQ sc.setParameters("id", 1); } @@ -994,44 +987,44 @@ public class ManagementServerImpl implements ManagementServer { return _userAccountDao.search(sc, searchFilter); } - - //This method is used for permissions check for both disk and service offerings - private boolean isPermissible(Long accountDomainId, Long offeringDomainId){ - - if(accountDomainId == offeringDomainId) - { + + // This method is used for permissions check for both disk and service offerings + private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { + + if (accountDomainId == offeringDomainId) { return true; // account and service offering in same domain } - - DomainVO domainRecord = _domainDao.findById(accountDomainId); - - if(domainRecord != null){ - while(true){ - if(domainRecord.getId() == offeringDomainId) { + + DomainVO domainRecord = _domainDao.findById(accountDomainId); + + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == offeringDomainId) { return true; } - - //try and move on to the next domain - if(domainRecord.getParent() != null) { + + // try and move on to the next domain + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; } - } - } - - return false; + } + } + + return false; } @Override public List searchForServiceOfferings(ListServiceOfferingsCmd cmd) { - //Note - //The list method for offerings is being modified in accordance with discussion with Will/Kevin - //For now, we will be listing the following based on the usertype - //1. For root, we will list all offerings - //2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way till root - Filter searchFilter = new Filter(ServiceOfferingVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + // Note + // The list method for offerings is being modified in accordance with discussion with Will/Kevin + // For now, we will be listing the following based on the usertype + // 1. For root, we will list all offerings + // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way till + // root + Filter searchFilter = new Filter(ServiceOfferingVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _offeringsDao.createSearchCriteria(); Account account = UserContext.current().getCaller(); @@ -1040,29 +1033,29 @@ public class ManagementServerImpl implements ManagementServer { Object keyword = cmd.getKeyword(); Long vmId = cmd.getVirtualMachineId(); Long domainId = cmd.getDomainId(); - - //Keeping this logic consistent with domain specific zones - //if a domainId is provided, we just return the so associated with this domain - if(domainId != null){ - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN){ - return _offeringsDao.findServiceOfferingByDomainId(domainId);//no perm check - }else{ - //check if the user's domain == so's domain || user's domain is a child of so's domain - if(isPermissible(account.getDomainId(), domainId)){ - //perm check succeeded - return _offeringsDao.findServiceOfferingByDomainId(domainId); - }else{ - throw new PermissionDeniedException("The account:"+account.getAccountName()+" does not fall in the same domain hierarchy as the service offering"); - } - } + + // Keeping this logic consistent with domain specific zones + // if a domainId is provided, we just return the so associated with this domain + if (domainId != null) { + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + return _offeringsDao.findServiceOfferingByDomainId(domainId);// no perm check + } else { + // check if the user's domain == so's domain || user's domain is a child of so's domain + if (isPermissible(account.getDomainId(), domainId)) { + // perm check succeeded + return _offeringsDao.findServiceOfferingByDomainId(domainId); + } else { + throw new PermissionDeniedException("The account:" + account.getAccountName() + " does not fall in the same domain hierarchy as the service offering"); + } + } } - - //For non-root users - if((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN){ - return searchServiceOfferingsInternal(account, name, id, vmId, keyword, searchFilter); + + // For non-root users + if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + return searchServiceOfferingsInternal(account, name, id, vmId, keyword, searchFilter); } - - //for root users, the existing flow + + // for root users, the existing flow if (keyword != null) { SearchCriteria ssc = _offeringsDao.createSearchCriteria(); ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1082,9 +1075,9 @@ public class ManagementServerImpl implements ManagementServer { ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - + // Only return offerings with the same Guest IP type and storage pool preference - //sc.addAnd("guestIpType", SearchCriteria.Op.EQ, offering.getGuestIpType()); + // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, offering.getGuestIpType()); sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); } @@ -1098,91 +1091,91 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("systemUse", SearchCriteria.Op.EQ, false); return _offeringsDao.search(sc, searchFilter); - + } - private List searchServiceOfferingsInternal(Account account, Object name, Object id, Long vmId, Object keyword, Filter searchFilter){ + private List searchServiceOfferingsInternal(Account account, Object name, Object id, Long vmId, Object keyword, Filter searchFilter) { - //it was decided to return all offerings for the user's domain, and everything above till root (for normal user or domain admin) - //list all offerings belonging to this domain, and all of its parents - //check the parent, if not null, add offerings for that parent to list - List sol = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - boolean includePublicOfferings = true; - if(domainRecord != null) - { - while(true){ - if(id != null) { - ServiceOfferingVO so = _offeringsDao.findById((Long)id); - if(so != null) { + // it was decided to return all offerings for the user's domain, and everything above till root (for normal user or + // domain admin) + // list all offerings belonging to this domain, and all of its parents + // check the parent, if not null, add offerings for that parent to list + List sol = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + boolean includePublicOfferings = true; + if (domainRecord != null) { + while (true) { + if (id != null) { + ServiceOfferingVO so = _offeringsDao.findById((Long) id); + if (so != null) { sol.add(so); } - return sol; - } - - SearchCriteria sc = _offeringsDao.createSearchCriteria(); - - if (keyword != null) { - includePublicOfferings = false; - SearchCriteria ssc = _offeringsDao.createSearchCriteria(); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + return sol; + } - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } else if (vmId != null) { - UserVmVO vmInstance = _userVmDao.findById(vmId); - if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); - } - if ((account != null) && !isAdmin(account.getType())) { - if (account.getId() != vmInstance.getAccountId()) { - throw new PermissionDeniedException("unable to find a virtual machine with id " + vmId + " for this account"); - } - } + SearchCriteria sc = _offeringsDao.createSearchCriteria(); - ServiceOfferingVO offering = _offeringsDao.findById(vmInstance.getServiceOfferingId()); - sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - - sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); - } + if (keyword != null) { + includePublicOfferings = false; + SearchCriteria ssc = _offeringsDao.createSearchCriteria(); + ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); -// if (id != null) { -// includePublicOfferings = false; -// sc.addAnd("id", SearchCriteria.Op.EQ, id); -// } + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } else if (vmId != null) { + UserVmVO vmInstance = _userVmDao.findById(vmId); + if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { + throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + } + if ((account != null) && !isAdmin(account.getType())) { + if (account.getId() != vmInstance.getAccountId()) { + throw new PermissionDeniedException("unable to find a virtual machine with id " + vmId + " for this account"); + } + } - if (name != null) { - includePublicOfferings = false; - sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); - } - sc.addAnd("systemUse", SearchCriteria.Op.EQ, false); + ServiceOfferingVO offering = _offeringsDao.findById(vmInstance.getServiceOfferingId()); + sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - //for this domain - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); - - //search and add for this domain - sol.addAll(_offeringsDao.search(sc, searchFilter)); - - //try and move on to the next domain - if(domainRecord.getParent() != null) { + sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); + } + + // if (id != null) { + // includePublicOfferings = false; + // sc.addAnd("id", SearchCriteria.Op.EQ, id); + // } + + if (name != null) { + includePublicOfferings = false; + sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); + } + sc.addAnd("systemUse", SearchCriteria.Op.EQ, false); + + // for this domain + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); + + // search and add for this domain + sol.addAll(_offeringsDao.search(sc, searchFilter)); + + // try and move on to the next domain + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); + } else { + break;// now we got all the offerings for this user/dom adm } - else { - break;//now we got all the offerings for this user/dom adm - } - } - }else{ - s_logger.error("Could not find the domainId for account:"+account.getAccountName()); - throw new CloudAuthenticationException("Could not find the domainId for account:"+account.getAccountName()); - } - - //add all the public offerings to the sol list before returning - if(includePublicOfferings) { + } + } else { + s_logger.error("Could not find the domainId for account:" + account.getAccountName()); + throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName()); + } + + // add all the public offerings to the sol list before returning + if (includePublicOfferings) { sol.addAll(_offeringsDao.findPublicServiceOfferings()); } - return sol; + return sol; } + @Override public List searchForClusters(ListClustersCmd cmd) { Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -1195,7 +1188,7 @@ public class ManagementServerImpl implements ManagementServer { Object hypervisorType = cmd.getHypervisorType(); Object clusterType = cmd.getClusterType(); Object allocationState = cmd.getAllocationState(); - + zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); if (id != null) { @@ -1205,25 +1198,25 @@ public class ManagementServerImpl implements ManagementServer { if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - + if (podId != null) { - sc.addAnd("podId", SearchCriteria.Op.EQ, podId); + sc.addAnd("podId", SearchCriteria.Op.EQ, podId); } - + if (zoneId != null) { - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } - - if(hypervisorType != null) { - sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); + + if (hypervisorType != null) { + sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); } - - if(clusterType != null) { - sc.addAnd("clusterType", SearchCriteria.Op.EQ, clusterType); + + if (clusterType != null) { + sc.addAnd("clusterType", SearchCriteria.Op.EQ, clusterType); } - - if(allocationState != null){ - sc.addAnd("allocationState", SearchCriteria.Op.EQ, allocationState); + + if (allocationState != null) { + sc.addAnd("allocationState", SearchCriteria.Op.EQ, allocationState); } return _clusterDao.search(sc, searchFilter); @@ -1231,11 +1224,11 @@ public class ManagementServerImpl implements ManagementServer { @Override public List searchForServers(ListHostsCmd cmd) { - - Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); + + Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); Object name = cmd.getHostName(); Object type = cmd.getType(); - Object state = cmd.getState(); + Object state = cmd.getState(); Object pod = cmd.getPodId(); Object cluster = cmd.getClusterId(); Object id = cmd.getId(); @@ -1244,80 +1237,81 @@ public class ManagementServerImpl implements ManagementServer { return searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, allocationState); } - + @Override public Pair, List> listHostsForMigrationOfVM(UserVm vm, Long startIndex, Long pageSize) { - //access check - only root admin can migrate VM - Account caller = UserContext.current().getCaller(); - if(caller.getType() != Account.ACCOUNT_TYPE_ADMIN){ - if(s_logger.isDebugEnabled()){ - s_logger.debug("Caller is not a root admin, permission denied to migrate the VM"); - } - throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!"); - } - //business logic - if(vm.getState() != State.Running){ + // access check - only root admin can migrate VM + Account caller = UserContext.current().getCaller(); + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Caller is not a root admin, permission denied to migrate the VM"); + } + throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!"); + } + // business logic + if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is not Running, unable to migrate the vm " + vm); } throw new InvalidParameterValueException("VM is not Running, unable to migrate the vm " + vm); } - - if(!vm.getHypervisorType().equals(HypervisorType.XenServer)){ - if(s_logger.isDebugEnabled()){ - s_logger.debug(vm + " is not XenServer, cannot migrate this VM."); - } + + if (!vm.getHypervisorType().equals(HypervisorType.XenServer)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug(vm + " is not XenServer, cannot migrate this VM."); + } throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer only"); - } - ServiceOfferingVO svcOffering = _offeringsDao.findById(vm.getServiceOfferingId()); - if(svcOffering.getUseLocalStorage()){ - if(s_logger.isDebugEnabled()){ - s_logger.debug(vm + " is using Local Storage, cannot migrate this VM."); - } + } + ServiceOfferingVO svcOffering = _offeringsDao.findById(vm.getServiceOfferingId()); + if (svcOffering.getUseLocalStorage()) { + if (s_logger.isDebugEnabled()) { + s_logger.debug(vm + " is using Local Storage, cannot migrate this VM."); + } throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); - } - long srcHostId = vm.getHostId(); - Host srcHost = _hostDao.findById(srcHostId); - if(srcHost == null){ - if(s_logger.isDebugEnabled()){ - s_logger.debug("Unable to find the host with id: "+srcHostId+" of this VM:" + vm); - } - throw new InvalidParameterValueException("Unable to find the host with id: "+srcHostId+" of this VM:" + vm); - } - Long cluster = srcHost.getClusterId(); - Type hostType = srcHost.getType(); - if(s_logger.isDebugEnabled()){ - s_logger.debug("Searching for all hosts in cluster: " +cluster+ " for migrating VM "+ vm); - } - - List allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null); - //filter out the current host - allHostsInCluster.remove(srcHost); + } + long srcHostId = vm.getHostId(); + Host srcHost = _hostDao.findById(srcHostId); + if (srcHost == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unable to find the host with id: " + srcHostId + " of this VM:" + vm); + } + throw new InvalidParameterValueException("Unable to find the host with id: " + srcHostId + " of this VM:" + vm); + } + Long cluster = srcHost.getClusterId(); + Type hostType = srcHost.getType(); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Searching for all hosts in cluster: " + cluster + " for migrating VM " + vm); + } - if(s_logger.isDebugEnabled()){ - s_logger.debug("Other Hosts in this cluster: "+allHostsInCluster); - } - - int requiredCpu = svcOffering.getCpu() * svcOffering.getSpeed(); - long requiredRam = svcOffering.getRamSize() * 1024L * 1024L; + List allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null); + // filter out the current host + allHostsInCluster.remove(srcHost); - if(s_logger.isDebugEnabled()){ - s_logger.debug("Searching for hosts in cluster: " +cluster+ " having required CPU: " +requiredCpu+ " and RAM:"+ requiredRam); - } + if (s_logger.isDebugEnabled()) { + s_logger.debug("Other Hosts in this cluster: " + allHostsInCluster); + } - List hostsWithCapacity = _capacityDao.listHostsWithEnoughCapacity(requiredCpu, requiredRam, cluster, hostType.name()); + int requiredCpu = svcOffering.getCpu() * svcOffering.getSpeed(); + long requiredRam = svcOffering.getRamSize() * 1024L * 1024L; - if(s_logger.isDebugEnabled()){ - s_logger.debug("Hosts having capacity: "+hostsWithCapacity ); - } - - return new Pair, List>(allHostsInCluster, hostsWithCapacity); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Searching for hosts in cluster: " + cluster + " having required CPU: " + requiredCpu + " and RAM:" + requiredRam); + } + + List hostsWithCapacity = _capacityDao.listHostsWithEnoughCapacity(requiredCpu, requiredRam, cluster, hostType.name()); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Hosts having capacity: " + hostsWithCapacity); + } + + return new Pair, List>(allHostsInCluster, hostsWithCapacity); } - private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword, Object allocationState) { + private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword, + Object allocationState) { Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize); SearchCriteria sc = _hostDao.createSearchCriteria(); - + if (keyword != null) { SearchCriteria ssc = _hostDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1349,11 +1343,11 @@ public class ManagementServerImpl implements ManagementServer { if (cluster != null) { sc.addAnd("clusterId", SearchCriteria.Op.EQ, cluster); } - - if(allocationState != null){ - sc.addAnd("hostAllocationState", SearchCriteria.Op.EQ, allocationState); + + if (allocationState != null) { + sc.addAnd("hostAllocationState", SearchCriteria.Op.EQ, allocationState); } - + return _hostDao.search(sc, searchFilter); } @@ -1367,7 +1361,7 @@ public class ManagementServerImpl implements ManagementServer { Long zoneId = cmd.getZoneId(); Object keyword = cmd.getKeyword(); Object allocationState = cmd.getAllocationState(); - + zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); if (keyword != null) { @@ -1389,10 +1383,10 @@ public class ManagementServerImpl implements ManagementServer { if (zoneId != null) { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } - + if (allocationState != null) { sc.addAnd("allocationState", SearchCriteria.Op.EQ, allocationState); - } + } return _hostPodDao.search(sc, searchFilter); } @@ -1421,7 +1415,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForVlans(ListVlanIpRangesCmd cmd) throws InvalidParameterValueException { + public List searchForVlans(ListVlanIpRangesCmd cmd) { // If an account name and domain ID are specified, look up the account String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); @@ -1429,7 +1423,7 @@ public class ManagementServerImpl implements ManagementServer { Long networkId = cmd.getNetworkId(); Boolean forVirtual = cmd.getForVirtualNetwork(); String vlanType = null; - + if (accountName != null && domainId != null) { Account account = _accountDao.findActiveAccount(accountName, domainId); if (account == null) { @@ -1437,14 +1431,14 @@ public class ManagementServerImpl implements ManagementServer { } else { accountId = account.getId(); } - } - + } + if (forVirtual != null) { - if (forVirtual) { - vlanType = VlanType.VirtualNetwork.toString(); - } else { - vlanType = VlanType.DirectAttached.toString(); - } + if (forVirtual) { + vlanType = VlanType.VirtualNetwork.toString(); + } else { + vlanType = VlanType.DirectAttached.toString(); + } } Filter searchFilter = new Filter(VlanVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -1462,19 +1456,19 @@ public class ManagementServerImpl implements ManagementServer { sb.and("vlan", sb.entity().getVlanTag(), SearchCriteria.Op.EQ); sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); sb.and("vlanType", sb.entity().getVlanType(), SearchCriteria.Op.EQ); - + if (accountId != null) { - SearchBuilder accountVlanMapSearch = _accountVlanMapDao.createSearchBuilder(); - accountVlanMapSearch.and("accountId", accountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER); + SearchBuilder accountVlanMapSearch = _accountVlanMapDao.createSearchBuilder(); + accountVlanMapSearch.and("accountId", accountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER); } - + if (podId != null) { - SearchBuilder podVlanMapSearch = _podVlanMapDao.createSearchBuilder(); - podVlanMapSearch.and("podId", podVlanMapSearch.entity().getPodId(), SearchCriteria.Op.EQ); - sb.join("podVlanMapSearch", podVlanMapSearch, sb.entity().getId(), podVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER); + SearchBuilder podVlanMapSearch = _podVlanMapDao.createSearchBuilder(); + podVlanMapSearch.and("podId", podVlanMapSearch.entity().getPodId(), SearchCriteria.Op.EQ); + sb.join("podVlanMapSearch", podVlanMapSearch, sb.entity().getId(), podVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER); } - + SearchCriteria sc = sb.create(); if (keyword != null) { SearchCriteria ssc = _vlanDao.createSearchCriteria(); @@ -1482,47 +1476,47 @@ public class ManagementServerImpl implements ManagementServer { ssc.addOr("ipRange", SearchCriteria.Op.LIKE, "%" + keyword + "%"); sc.addAnd("vlanId", SearchCriteria.Op.SC, ssc); } else { - if (id != null) { - sc.setParameters("id", id); - } - - if (vlan != null) { - sc.setParameters("vlan", vlan); - } - - if (dataCenterId != null) { - sc.setParameters("dataCenterId", dataCenterId); - } - - if (networkId != null) { - sc.setParameters("networkId", networkId); - } - - if (accountId != null) { - sc.setJoinParameters("accountVlanMapSearch", "accountId", accountId); - } - - if (podId != null) { - sc.setJoinParameters("podVlanMapSearch", "podId", podId); - } - if (vlanType != null) { - sc.setParameters("vlanType", vlanType); - } + if (id != null) { + sc.setParameters("id", id); + } + + if (vlan != null) { + sc.setParameters("vlan", vlan); + } + + if (dataCenterId != null) { + sc.setParameters("dataCenterId", dataCenterId); + } + + if (networkId != null) { + sc.setParameters("networkId", networkId); + } + + if (accountId != null) { + sc.setJoinParameters("accountVlanMapSearch", "accountId", accountId); + } + + if (podId != null) { + sc.setJoinParameters("podVlanMapSearch", "podId", podId); + } + if (vlanType != null) { + sc.setParameters("vlanType", vlanType); + } } return _vlanDao.search(sc, searchFilter); } - + @Override public Long getPodIdForVlan(long vlanDbId) { - List podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(vlanDbId); - if (podVlanMaps.isEmpty()) { - return null; - } else { - return podVlanMaps.get(0).getPodId(); - } + List podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(vlanDbId); + if (podVlanMaps.isEmpty()) { + return null; + } else { + return podVlanMaps.get(0).getPodId(); + } } - + @Override public List searchForConfigurations(ListCfgsByCmd cmd) { Filter searchFilter = new Filter(ConfigurationVO.class, "name", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -1540,7 +1534,7 @@ public class ManagementServerImpl implements ManagementServer { ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("category", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("value", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - + sc.addAnd("name", SearchCriteria.Op.SC, ssc); } @@ -1588,9 +1582,9 @@ public class ManagementServerImpl implements ManagementServer { sb.and("publicTemplate", sb.entity().isPublicTemplate(), SearchCriteria.Op.EQ); sb.and("format", sb.entity().getFormat(), SearchCriteria.Op.NEQ); sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ); - + SearchCriteria sc = sb.create(); - + if (keyword != null) { SearchCriteria ssc = _templateDao.createSearchCriteria(); ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1634,13 +1628,12 @@ public class ManagementServerImpl implements ManagementServer { accountId = account.getId(); } - //It is account specific if account is admin type and domainId and accountName are not null - boolean isAccountSpecific = (account == null || isAdmin(account.getType())) - && (accountName != null) - && (domainId != null); - + // It is account specific if account is admin type and domainId and accountName are not null + boolean isAccountSpecific = (account == null || isAdmin(account.getType())) && (accountName != null) && (domainId != null); + HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), accountId, cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, isAccountSpecific, true); + return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), accountId, cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, + isAccountSpecific, true); } @Override @@ -1656,57 +1649,54 @@ public class ManagementServerImpl implements ManagementServer { accountId = account.getId(); } - //It is account specific if account is admin type and domainId and accountName are not null - boolean isAccountSpecific = (account == null || isAdmin(account.getType())) - && (accountName != null) - && (domainId != null); + // It is account specific if account is admin type and domainId and accountName are not null + boolean isAccountSpecific = (account == null || isAdmin(account.getType())) && (accountName != null) && (domainId != null); boolean showDomr = (templateFilter != TemplateFilter.selfexecutable); HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - - return listTemplates(cmd.getId(), cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, accountId, cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, isAccountSpecific, showDomr); + + return listTemplates(cmd.getId(), cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, accountId, cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, + isAccountSpecific, showDomr); } - private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long accountId, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean isAccountSpecific, boolean showDomr) throws InvalidParameterValueException { + private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long accountId, Long pageSize, + Long startIndex, Long zoneId, HypervisorType hyperType, boolean isAccountSpecific, boolean showDomr) { VMTemplateVO template = null; - if (templateId != null) { - template = _templateDao.findById(templateId); - if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template ID."); - }// If ISO requested then it should be ISO. - if (isIso && template.getFormat() != ImageFormat.ISO){ - s_logger.error("Template Id " + templateId + " is not an ISO"); - throw new InvalidParameterValueException("Template Id " + templateId + " is not an ISO"); - }// If ISO not requested then it shouldn't be an ISO. - if (!isIso && template.getFormat() == ImageFormat.ISO){ - s_logger.error("Incorrect format of the template id " + templateId); - throw new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the template id " + templateId); - } + if (templateId != null) { + template = _templateDao.findById(templateId); + if (template == null) { + throw new InvalidParameterValueException("Please specify a valid template ID."); + }// If ISO requested then it should be ISO. + if (isIso && template.getFormat() != ImageFormat.ISO) { + s_logger.error("Template Id " + templateId + " is not an ISO"); + throw new InvalidParameterValueException("Template Id " + templateId + " is not an ISO"); + }// If ISO not requested then it shouldn't be an ISO. + if (!isIso && template.getFormat() == ImageFormat.ISO) { + s_logger.error("Incorrect format of the template id " + templateId); + throw new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the template id " + templateId); + } } - - // Show only those that are downloaded. - boolean onlyReady = (templateFilter == TemplateFilter.featured) || - (templateFilter == TemplateFilter.selfexecutable) || - (templateFilter == TemplateFilter.sharedexecutable) || - (templateFilter == TemplateFilter.executable && isAccountSpecific) || - (templateFilter == TemplateFilter.community); - - Account account = null; - DomainVO domain = null; + + // Show only those that are downloaded. + boolean onlyReady = (templateFilter == TemplateFilter.featured) || (templateFilter == TemplateFilter.selfexecutable) || (templateFilter == TemplateFilter.sharedexecutable) + || (templateFilter == TemplateFilter.executable && isAccountSpecific) || (templateFilter == TemplateFilter.community); + + Account account = null; + DomainVO domain = null; if (accountId != null) { - account = _accountDao.findById(accountId); - domain = _domainDao.findById(account.getDomainId()); + account = _accountDao.findById(accountId); + domain = _domainDao.findById(account.getDomainId()); } else { - domain = _domainDao.findById(DomainVO.ROOT_DOMAIN); + domain = _domainDao.findById(DomainVO.ROOT_DOMAIN); } - - Set> templateZonePairSet = new HashSet>(); - + + Set> templateZonePairSet = new HashSet>(); + if (template == null) { - templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, bootable, account, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr); - } else { - templateZonePairSet.add(new Pair(template.getId(), zoneId)); - } - + templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, bootable, account, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr); + } else { + templateZonePairSet.add(new Pair(template.getId(), zoneId)); + } + return templateZonePairSet; } @@ -1719,9 +1709,9 @@ public class ManagementServerImpl implements ManagementServer { public List listPods(long dataCenterId) { return _hostPodDao.listByDataCenterId(dataCenterId); } - + @Override - public String changePrivateIPRange(boolean add, Long podId, String startIP, String endIP) throws InvalidParameterValueException { + public String changePrivateIPRange(boolean add, Long podId, String startIP, String endIP) { return _configMgr.changePrivateIPRange(add, podId, startIP, endIP); } @@ -1768,17 +1758,17 @@ public class ManagementServerImpl implements ManagementServer { Long accountId = cmd.getId(); String accountName = null; Boolean isRecursive = cmd.isRecursive(); - - if(isRecursive == null) { + + if (isRecursive == null) { isRecursive = false; } - - if(accountId != null && accountId == 1){ - //system account should NOT be searchable - List emptyList = new ArrayList(); - return emptyList; + + if (accountId != null && accountId == 1) { + // system account should NOT be searchable + List emptyList = new ArrayList(); + return emptyList; } - + if ((account == null) || isAdmin(account.getType())) { accountName = cmd.getSearchName(); // admin's can specify a name to search for if (domainId == null) { @@ -1820,14 +1810,14 @@ public class ManagementServerImpl implements ManagementServer { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.EQ); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - + } + SearchCriteria sc = sb.create(); if (keyword != null) { SearchCriteria ssc = _accountDao.createSearchCriteria(); ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - + sc.addAnd("accountName", SearchCriteria.Op.SC, ssc); } @@ -1841,15 +1831,15 @@ public class ManagementServerImpl implements ManagementServer { DomainVO domain = _domainDao.findById(domainId); // I want to join on user_vm.domain_id = domain.id where domain.path like 'foo%' - if(isRecursive) { + if (isRecursive) { sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); } else { sc.setJoinParameters("domainSearch", "path", domain.getPath()); } - + sc.setParameters("nid", 1L); } else { - sc.setParameters("nid", 1L); + sc.setParameters("nid", 1L); } if (type != null) { @@ -1896,7 +1886,7 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria ssc = _templateDao.createSearchCriteria(); ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - + sc.addAnd("name", SearchCriteria.Op.SC, ssc); } @@ -1951,95 +1941,95 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public VMTemplateVO updateTemplate(UpdateIsoCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public VMTemplateVO updateTemplate(UpdateIsoCmd cmd) { return updateTemplateOrIso(cmd); } @Override - public VMTemplateVO updateTemplate(UpdateTemplateCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public VMTemplateVO updateTemplate(UpdateTemplateCmd cmd) { return updateTemplateOrIso(cmd); } - private VMTemplateVO updateTemplateOrIso(UpdateTemplateOrIsoCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { - Long id = cmd.getId(); - String name = cmd.getTemplateName(); - String displayText = cmd.getDisplayText(); - String format = cmd.getFormat(); - Long guestOSId = cmd.getOsTypeId(); - Boolean passwordEnabled = cmd.isPasswordEnabled(); - Boolean bootable = cmd.isBootable(); - Account account= UserContext.current().getCaller(); - - //verify that template exists - VMTemplateVO template = findTemplateById(id); - if (template == null) { - throw new InvalidParameterValueException("unable to find template/iso with id " + id); - } - - //Don't allow to modify system template - if (id == Long.valueOf(1)) { - throw new InvalidParameterValueException("Unable to update template/iso with id " + id); - } - - //do a permission check - _accountMgr.checkAccess(account, template); + private VMTemplateVO updateTemplateOrIso(UpdateTemplateOrIsoCmd cmd) { + Long id = cmd.getId(); + String name = cmd.getTemplateName(); + String displayText = cmd.getDisplayText(); + String format = cmd.getFormat(); + Long guestOSId = cmd.getOsTypeId(); + Boolean passwordEnabled = cmd.isPasswordEnabled(); + Boolean bootable = cmd.isBootable(); + Account account = UserContext.current().getCaller(); + + // verify that template exists + VMTemplateVO template = findTemplateById(id); + if (template == null) { + throw new InvalidParameterValueException("unable to find template/iso with id " + id); + } + + // Don't allow to modify system template + if (id == Long.valueOf(1)) { + throw new InvalidParameterValueException("Unable to update template/iso with id " + id); + } + + // do a permission check + _accountMgr.checkAccess(account, template); + + boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null); + if (!updateNeeded) { + return template; + } + + template = _templateDao.createForUpdate(id); + + if (name != null) { + template.setName(name); + } + + if (displayText != null) { + template.setDisplayText(displayText); + } + + ImageFormat imageFormat = null; + if (format != null) { + try { + imageFormat = ImageFormat.valueOf(format.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + } + + template.setFormat(imageFormat); + } + + if (guestOSId != null) { + GuestOSVO guestOS = _guestOSDao.findById(guestOSId); + + if (guestOS == null) { + throw new InvalidParameterValueException("Please specify a valid guest OS ID."); + } else { + template.setGuestOSId(guestOSId); + } + } + + if (passwordEnabled != null) { + template.setEnablePassword(passwordEnabled); + } + + if (bootable != null) { + template.setBootable(bootable); + } - boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null); - if (!updateNeeded) { - return template; - } - - template = _templateDao.createForUpdate(id); - - if (name != null) { - template.setName(name); - } - - if (displayText != null) { - template.setDisplayText(displayText); - } - - ImageFormat imageFormat = null; - if (format != null) { - try { - imageFormat = ImageFormat.valueOf(format.toUpperCase()); - } catch (IllegalArgumentException e) { - throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values())); - } - - template.setFormat(imageFormat); - } - - if (guestOSId != null) { - GuestOSVO guestOS = _guestOSDao.findById(guestOSId); - - if (guestOS == null) { - throw new InvalidParameterValueException("Please specify a valid guest OS ID."); - } else { - template.setGuestOSId(guestOSId); - } - } - - if (passwordEnabled != null) { - template.setEnablePassword(passwordEnabled); - } - - if (bootable != null) { - template.setBootable(bootable); - } - _templateDao.update(id, template); return _templateDao.findById(id); } - + @Override public VMTemplateVO findTemplateById(long templateId) { return _templateDao.findById(templateId); } @Override - public List searchForEvents(ListEventsCmd cmd){ + public List searchForEvents(ListEventsCmd cmd) { Account account = UserContext.current().getCaller(); Long accountId = null; boolean isAdmin = false; @@ -2081,7 +2071,7 @@ public class ManagementServerImpl implements ManagementServer { Integer duration = cmd.getDuration(); if ((entryTime != null) && (duration != null)) { - if (entryTime <= duration){ + if (entryTime <= duration) { throw new InvalidParameterValueException("Entry time must be greater than duration"); } return listPendingEvents(entryTime, duration); @@ -2118,11 +2108,11 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("level", SearchCriteria.Op.SC, ssc); } - + if (level != null) { sc.setParameters("levelEQ", level); } - + if (accountId != null) { sc.setParameters("accountId", accountId); } else if (domainId != null) { @@ -2138,7 +2128,7 @@ public class ManagementServerImpl implements ManagementServer { if (type != null) { sc.setParameters("type", type); } - + if (startDate != null && endDate != null) { startDate = massageDate(startDate, 0, 0, 0); endDate = massageDate(endDate, 23, 59, 59); @@ -2165,7 +2155,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForRouters(ListRoutersCmd cmd){ + public List searchForRouters(ListRoutersCmd cmd) { Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Long accountId = null; @@ -2214,15 +2204,15 @@ public class ManagementServerImpl implements ManagementServer { domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + if (networkId != null) { SearchBuilder nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - + SearchBuilder networkSearch = _networkDao.createSearchBuilder(); networkSearch.and("networkId", networkSearch.entity().getId(), SearchCriteria.Op.EQ); nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); - + sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } @@ -2239,9 +2229,9 @@ public class ManagementServerImpl implements ManagementServer { if (name != null) { sc.setParameters("name", "%" + name + "%"); } - - if(id != null) { - sc.setParameters("id", id); + + if (id != null) { + sc.setParameters("id", id); } if (accountId != null) { @@ -2263,7 +2253,7 @@ public class ManagementServerImpl implements ManagementServer { if (hostId != null) { sc.setParameters("hostId", hostId); } - + if (networkId != null) { sc.setJoinParameters("nicSearch", "networkId", networkId); } @@ -2291,8 +2281,8 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - - if(id != null) { + + if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } @@ -2316,18 +2306,18 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForVolumes(ListVolumesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List searchForVolumes(ListVolumesCmd cmd) { Account account = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Long accountId = null; boolean isAdmin = false; Boolean isRecursive = cmd.isRecursive(); - - if(isRecursive == null) { + + if (isRecursive == null) { isRecursive = false; } - + if ((account == null) || isAdmin(account.getType())) { isAdmin = true; if (domainId != null) { @@ -2360,8 +2350,8 @@ public class ManagementServerImpl implements ManagementServer { Object zone = null; Object pod = null; - //Object host = null; TODO - if (isAdmin) { + // Object host = null; TODO + if (isAdmin) { zone = cmd.getZoneId(); pod = cmd.getPodId(); // host = cmd.getHostId(); TODO @@ -2383,7 +2373,7 @@ public class ManagementServerImpl implements ManagementServer { // Only return volumes that are not destroyed sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); - + SearchBuilder diskOfferingSearch = _diskOfferingDao.createSearchBuilder(); diskOfferingSearch.and("systemUse", diskOfferingSearch.entity().isSystemUse(), SearchCriteria.Op.NEQ); sb.join("diskOfferingSearch", diskOfferingSearch, sb.entity().getDiskOfferingId(), diskOfferingSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); @@ -2393,17 +2383,17 @@ public class ManagementServerImpl implements ManagementServer { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } else if((accountId == null) && (domainId != null) && !isRecursive) { + } else if ((accountId == null) && (domainId != null) && !isRecursive) { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.EQ); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - //display user vm volumes only + } + + // display user vm volumes only SearchBuilder vmSearch = _vmInstanceDao.createSearchBuilder(); vmSearch.and("type", vmSearch.entity().getType(), SearchCriteria.Op.NIN); sb.join("vmSearch", vmSearch, sb.entity().getInstanceId(), vmSearch.entity().getId(), JoinBuilder.JoinType.INNER); - + // now set the SC criteria... SearchCriteria sc = sb.create(); if (keyword != null) { @@ -2413,7 +2403,7 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - + if (name != null) { sc.setParameters("name", "%" + name + "%"); } @@ -2427,7 +2417,7 @@ public class ManagementServerImpl implements ManagementServer { sc.setJoinParameters("diskOfferingSearch", "systemUse", 1); } else if (domainId != null) { DomainVO domain = _domainDao.findById(domainId); - if(isRecursive) { + if (isRecursive) { sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); } else { sc.setJoinParameters("domainSearch", "path", domain.getPath()); @@ -2445,10 +2435,10 @@ public class ManagementServerImpl implements ManagementServer { if (pod != null) { sc.setParameters("podId", pod); } - + // Don't return DomR and ConsoleProxy volumes sc.setJoinParameters("vmSearch", "type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.DomainRouter); - + // Only return volumes that are not destroyed sc.setParameters("state", Volume.State.Destroy); @@ -2457,32 +2447,31 @@ public class ManagementServerImpl implements ManagementServer { @Override public VolumeVO findVolumeByInstanceAndDeviceId(long instanceId, long deviceId) { - VolumeVO volume = _volumeDao.findByInstanceAndDeviceId(instanceId, deviceId).get(0); - if (volume != null && volume.getState() != Volume.State.Destroy && volume.getRemoved() == null) { - return volume; - } else { - return null; - } + VolumeVO volume = _volumeDao.findByInstanceAndDeviceId(instanceId, deviceId).get(0); + if (volume != null && volume.getState() != Volume.State.Destroy && volume.getRemoved() == null) { + return volume; + } else { + return null; + } } @Override public HostPodVO findHostPodById(long podId) { return _hostPodDao.findById(podId); } - + @Override public HostVO findSecondaryStorageHosT(long zoneId) { - return _storageMgr.getSecondaryStorageHost(zoneId); + return _storageMgr.getSecondaryStorageHost(zoneId); } @Override - public List searchForIPAddresses(ListPublicIpAddressesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List searchForIPAddresses(ListPublicIpAddressesCmd cmd) { Account account = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Object keyword = cmd.getKeyword(); Long accountId = null; - if ((account == null) || isAdmin(account.getType())) { // validate domainId before proceeding @@ -2498,16 +2487,16 @@ public class ManagementServerImpl implements ManagementServer { } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } - } + } } else { domainId = ((account == null) ? DomainVO.ROOT_DOMAIN : account.getDomainId()); } } else { accountId = account.getId(); } - + if (accountId == null && keyword != null) { - Account userAccount = _accountDao.findActiveAccount((String)keyword, domainId); + Account userAccount = _accountDao.findActiveAccount((String) keyword, domainId); if (userAccount != null) { accountId = userAccount.getId(); } @@ -2523,7 +2512,7 @@ public class ManagementServerImpl implements ManagementServer { Object zone = cmd.getZoneId(); Object address = cmd.getIpAddress(); Object vlan = cmd.getVlanId(); - Object forVirtualNetwork = cmd.isForVirtualNetwork(); + Object forVirtualNetwork = cmd.isForVirtualNetwork(); Object ipId = cmd.getId(); SearchBuilder sb = _publicIpAddressDao.createSearchBuilder(); @@ -2539,14 +2528,14 @@ public class ManagementServerImpl implements ManagementServer { domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + if (keyword != null && address == null) { sb.and("addressLIKE", sb.entity().getAddress(), SearchCriteria.Op.LIKE); } - - SearchBuilder vlanSearch = _vlanDao.createSearchBuilder(); - vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ); - sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER); + + SearchBuilder vlanSearch = _vlanDao.createSearchBuilder(); + vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ); + sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER); if ((isAllocated != null) && (isAllocated == true)) { sb.and("allocated", sb.entity().getAllocatedTime(), SearchCriteria.Op.NNULL); @@ -2559,26 +2548,26 @@ public class ManagementServerImpl implements ManagementServer { DomainVO domain = _domainDao.findById(domainId); sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); } - + VlanType vlanType = null; if (forVirtualNetwork != null) { vlanType = (Boolean) forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; } else { vlanType = VlanType.VirtualNetwork; } - + sc.setJoinParameters("vlanSearch", "vlanType", vlanType); if (zone != null) { sc.setParameters("dataCenterId", zone); } - + if (ipId != null) { sc.setParameters("id", ipId); } if (address == null && keyword != null) { - sc.setParameters("addressLIKE", "%" + keyword + "%"); + sc.setParameters("addressLIKE", "%" + keyword + "%"); } if (address != null) { @@ -2606,7 +2595,8 @@ public class ManagementServerImpl implements ManagementServer { String singleSignOnTolerance = getConfigurationValue("security.singlesignon.tolerance.millis"); if (singleSignOnTolerance == null) { - // the SSO tolerance is gone (how much time before/after system time we'll allow the login request to be valid), don't authenticate + // the SSO tolerance is gone (how much time before/after system time we'll allow the login request to be valid), + // don't authenticate return null; } @@ -2620,7 +2610,7 @@ public class ManagementServerImpl implements ManagementServer { List parameterNames = new ArrayList(); for (Object paramNameObj : requestParameters.keySet()) { - parameterNames.add((String)paramNameObj); // put the name in a list that we'll sort later + parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); @@ -2628,7 +2618,7 @@ public class ManagementServerImpl implements ManagementServer { try { for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] - String paramValue = ((String[])requestParameters.get(paramName))[0]; + String paramValue = ((String[]) requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; @@ -2636,7 +2626,8 @@ public class ManagementServerImpl implements ManagementServer { if ("timestamp".equalsIgnoreCase(paramName)) { String timestampStr = paramValue; try { - // If the timestamp is in a valid range according to our tolerance, verify the request signature, otherwise return null to indicate authentication failure + // If the timestamp is in a valid range according to our tolerance, verify the request + // signature, otherwise return null to indicate authentication failure timestamp = Long.parseLong(timestampStr); long currentTime = System.currentTimeMillis(); if (Math.abs(currentTime - timestamp) > tolerance) { @@ -2689,13 +2680,13 @@ public class ManagementServerImpl implements ManagementServer { } if (user != null) { - if (s_logger.isDebugEnabled()) { + if (s_logger.isDebugEnabled()) { s_logger.debug("User: " + username + " in domain " + domainId + " has successfully logged in"); } - EventUtils.saveEvent(user.getId(), user.getAccountId(), EventTypes.EVENT_USER_LOGIN, "user has logged in"); + EventUtils.saveEvent(user.getId(), user.getAccountId(), EventTypes.EVENT_USER_LOGIN, "user has logged in"); return user; } else { - if (s_logger.isDebugEnabled()) { + if (s_logger.isDebugEnabled()) { s_logger.debug("User: " + username + " in domain " + domainId + " has failed to log in"); } return null; @@ -2707,10 +2698,9 @@ public class ManagementServerImpl implements ManagementServer { UserAccount userAcct = _userAccountDao.findById(userId); if (userAcct != null) { EventUtils.saveEvent(userId, userAcct.getAccountId(), EventTypes.EVENT_USER_LOGOUT, "user has logged out"); - } // else log some kind of error event? This likely means the user doesn't exist, or has been deleted... + } // else log some kind of error event? This likely means the user doesn't exist, or has been deleted... } - @Override public List listAllTemplates() { return _templateDao.listAllIncludingRemoved(); @@ -2729,7 +2719,7 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria sc = sb.create(); if (id != null) { - sc.setParameters("id",id); + sc.setParameters("id", id); } if (osCategoryId != null) { @@ -2750,15 +2740,15 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria sc = sb.create(); if (id != null) { - sc.setParameters("id",id); + sc.setParameters("id", id); } - return _guestOSCategoryDao.search(sc, searchFilter); + return _guestOSCategoryDao.search(sc, searchFilter); } - + @Override public String getConfigurationValue(String name) { - return _configDao.getValue(name); + return _configDao.getValue(name); } @Override @@ -2766,14 +2756,16 @@ public class ManagementServerImpl implements ManagementServer { return _consoleProxyMgr.assignProxy(dataCenterId, userVmId); } - @Override @ActionEvent (eventType=EventTypes.EVENT_PROXY_START, eventDescription="starting console proxy Vm", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_PROXY_START, eventDescription = "starting console proxy Vm", async = true) public ConsoleProxyVO startConsoleProxy(long instanceId) { return _consoleProxyMgr.startProxy(instanceId); } - @Override @ActionEvent (eventType=EventTypes.EVENT_PROXY_STOP, eventDescription="stopping console proxy Vm", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true) public ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { - + User caller = _userDao.findById(UserContext.current().getCallerUserId()); if (_itMgr.advanceStop(systemVm, isForced, caller, UserContext.current().getCaller())) { @@ -2782,17 +2774,18 @@ public class ManagementServerImpl implements ManagementServer { return null; } - @Override @ActionEvent (eventType=EventTypes.EVENT_PROXY_REBOOT, eventDescription="rebooting console proxy Vm", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_PROXY_REBOOT, eventDescription = "rebooting console proxy Vm", async = true) public ConsoleProxyVO rebootConsoleProxy(long instanceId) { _consoleProxyMgr.rebootProxy(instanceId); return _consoleProxyDao.findById(instanceId); } - - @ActionEvent (eventType=EventTypes.EVENT_PROXY_DESTROY, eventDescription="destroying console proxy Vm", async=true) + + @ActionEvent(eventType = EventTypes.EVENT_PROXY_DESTROY, eventDescription = "destroying console proxy Vm", async = true) public ConsoleProxyVO destroyConsoleProxy(long instanceId) { - ConsoleProxyVO proxy = _consoleProxyDao.findById(instanceId); - - if(_consoleProxyMgr.destroyProxy(instanceId)) { + ConsoleProxyVO proxy = _consoleProxyDao.findById(instanceId); + + if (_consoleProxyMgr.destroyProxy(instanceId)) { return proxy; } return null; @@ -2813,19 +2806,19 @@ public class ManagementServerImpl implements ManagementServer { @Override public Pair getVncPort(VirtualMachine vm) { if (vm.getHostId() == null) { - s_logger.warn("VM " + vm.getName() + " does not have host, return -1 for its VNC port"); + s_logger.warn("VM " + vm.getName() + " does not have host, return -1 for its VNC port"); return new Pair(null, -1); } - - if(s_logger.isTraceEnabled()) { + + if (s_logger.isTraceEnabled()) { s_logger.trace("Trying to retrieve VNC port from agent about VM " + vm.getName()); } - + GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new GetVncPortCommand(vm.getId(), vm.getInstanceName())); - if(answer != null && answer.getResult()) { + if (answer != null && answer.getResult()) { return new Pair(answer.getAddress(), answer.getPort()); } - + return new Pair(null, -1); } @@ -2839,7 +2832,7 @@ public class ManagementServerImpl implements ManagementServer { Long domainId = cmd.getId(); Account account = UserContext.current().getCaller(); String path = null; - + if (account != null && (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) { DomainVO domain = _domainDao.findById(account.getDomainId()); if (domain != null) { @@ -2877,12 +2870,12 @@ public class ManagementServerImpl implements ManagementServer { if (domainId != null) { sc.setParameters("id", domainId); } - + if (path != null) { - sc.setParameters("path", "%" +path+"%"); + sc.setParameters("path", "%" + path + "%"); } - return _domainDao.search(sc, searchFilter); + return _domainDao.search(sc, searchFilter); } @Override @@ -2893,7 +2886,7 @@ public class ManagementServerImpl implements ManagementServer { Boolean isRecursive = cmd.isRecursive(); Object keyword = cmd.getKeyword(); String path = null; - + if (isRecursive == null) { isRecursive = false; } @@ -2908,22 +2901,20 @@ public class ManagementServerImpl implements ManagementServer { domainId = account.getDomainId(); } } - + DomainVO domain = _domainDao.findById(domainId); if (domain != null && isRecursive) { path = domain.getPath(); domainId = null; } - List domainList = searchForDomainChildren(searchFilter, domainId, domainName, - keyword, path); - - return domainList; - } + List domainList = searchForDomainChildren(searchFilter, domainId, domainName, keyword, path); - private List searchForDomainChildren(Filter searchFilter, - Long domainId, String domainName, Object keyword, String path) { - SearchCriteria sc = _domainDao.createSearchCriteria(); + return domainList; + } + + private List searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path) { + SearchCriteria sc = _domainDao.createSearchCriteria(); if (keyword != null) { SearchCriteria ssc = _domainDao.createSearchCriteria(); @@ -2939,22 +2930,23 @@ public class ManagementServerImpl implements ManagementServer { if (domainName != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + domainName + "%"); } - + if (path != null) { sc.addAnd("path", SearchCriteria.Op.NEQ, path); sc.addAnd("path", SearchCriteria.Op.LIKE, path + "%"); - + } return _domainDao.search(sc, searchFilter); - } + } - @Override @ActionEvent (eventType=EventTypes.EVENT_DOMAIN_CREATE, eventDescription="creating Domain") - public DomainVO createDomain(CreateDomainCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + @Override + @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain") + public DomainVO createDomain(CreateDomainCmd cmd) { String name = cmd.getDomainName(); Long parentId = cmd.getParentDomainId(); Long ownerId = UserContext.current().getCaller().getId(); Account account = UserContext.current().getCaller(); - + if (ownerId == null) { ownerId = Long.valueOf(1); } @@ -2989,12 +2981,13 @@ public class ManagementServerImpl implements ManagementServer { } } - @Override @ActionEvent (eventType=EventTypes.EVENT_DOMAIN_DELETE, eventDescription="deleting Domain", async=true) - public boolean deleteDomain(DeleteDomainCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + @Override + @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_DELETE, eventDescription = "deleting Domain", async = true) + public boolean deleteDomain(DeleteDomainCmd cmd) { Account account = UserContext.current().getCaller(); Long domainId = cmd.getId(); Boolean cleanup = cmd.getCleanup(); - + if ((domainId == DomainVO.ROOT_DOMAIN) || ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId))) { throw new PermissionDeniedException("Unable to delete domain " + domainId + ", permission denied."); } @@ -3011,7 +3004,8 @@ public class ManagementServerImpl implements ManagementServer { } } else { if (!_domainDao.remove(domainId)) { - s_logger.error("Delete failed on domain " + domain.getName() + " (id: " + domainId + "); please make sure all users and sub domains have been removed from the domain before deleting"); + s_logger.error("Delete failed on domain " + domain.getName() + " (id: " + domainId + + "); please make sure all users and sub domains have been removed from the domain before deleting"); return false; } else { domain.setState(Domain.State.Inactive); @@ -3032,39 +3026,39 @@ public class ManagementServerImpl implements ManagementServer { } private void cleanupDomainOfferings(Long domainId) { - //delete the service and disk offerings associated with this domain + // delete the service and disk offerings associated with this domain List diskOfferingsForThisDomain = _diskOfferingDao.listByDomainId(domainId); - for(DiskOfferingVO diskOffering : diskOfferingsForThisDomain) { + for (DiskOfferingVO diskOffering : diskOfferingsForThisDomain) { _diskOfferingDao.remove(diskOffering.getId()); } - + List serviceOfferingsForThisDomain = _offeringsDao.findServiceOfferingByDomainId(domainId); - for(ServiceOfferingVO serviceOffering : serviceOfferingsForThisDomain) { + for (ServiceOfferingVO serviceOffering : serviceOfferingsForThisDomain) { _offeringsDao.remove(serviceOffering.getId()); } } - - private boolean cleanupDomain(Long domainId, Long ownerId) throws ConcurrentOperationException, ResourceUnavailableException{ + + private boolean cleanupDomain(Long domainId, Long ownerId) throws ConcurrentOperationException, ResourceUnavailableException { boolean success = true; { DomainVO domainHandle = _domainDao.findById(domainId); domainHandle.setState(Domain.State.Inactive); _domainDao.update(domainId, domainHandle); - + SearchCriteria sc = _domainDao.createSearchCriteria(); sc.addAnd("parent", SearchCriteria.Op.EQ, domainId); List domains = _domainDao.search(sc, null); SearchCriteria sc1 = _domainDao.createSearchCriteria(); - sc1.addAnd("path", SearchCriteria.Op.LIKE, "%"+domainHandle.getPath()+"%"); + sc1.addAnd("path", SearchCriteria.Op.LIKE, "%" + domainHandle.getPath() + "%"); List domainsToBeInactivated = _domainDao.search(sc1, null); - - //update all subdomains to inactive so no accounts/users can be created - for(DomainVO domain : domainsToBeInactivated) { + + // update all subdomains to inactive so no accounts/users can be created + for (DomainVO domain : domainsToBeInactivated) { domain.setState(Domain.State.Inactive); _domainDao.update(domain.getId(), domain); } - + // cleanup sub-domains first for (DomainVO domain : domains) { success = (success && cleanupDomain(domain.getId(), domain.getAccountId())); @@ -3086,45 +3080,46 @@ public class ManagementServerImpl implements ManagementServer { } } } - + // delete the domain itself boolean deleteDomainSuccess = _domainDao.remove(domainId); return success && deleteDomainSuccess; } - @Override @ActionEvent (eventType=EventTypes.EVENT_DOMAIN_UPDATE, eventDescription="updating Domain") - public DomainVO updateDomain(UpdateDomainCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ - Long domainId = cmd.getId(); - String domainName = cmd.getDomainName(); - - //check if domain exists in the system - DomainVO domain = _domainDao.findById(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain " + domainId); - } else if (domain.getParent() == null) { - //check if domain is ROOT domain - and deny to edit it - throw new InvalidParameterValueException("ROOT domain can not be edited"); - } + @Override + @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain") + public DomainVO updateDomain(UpdateDomainCmd cmd) { + Long domainId = cmd.getId(); + String domainName = cmd.getDomainName(); - // check permissions - Account account = UserContext.current().getCaller(); - if ((account != null) && !isChildDomain(account.getDomainId(), domain.getId())) { + // check if domain exists in the system + DomainVO domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Unable to find domain " + domainId); + } else if (domain.getParent() == null) { + // check if domain is ROOT domain - and deny to edit it + throw new InvalidParameterValueException("ROOT domain can not be edited"); + } + + // check permissions + Account account = UserContext.current().getCaller(); + if ((account != null) && !isChildDomain(account.getDomainId(), domain.getId())) { throw new PermissionDeniedException("Unable to update domain " + domainId + ", permission denied"); - } + } + + if (domainName == null || domainName.equals(domain.getName())) { + return _domainDao.findById(domainId); + } - if (domainName == null || domainName.equals(domain.getName())) { - return _domainDao.findById(domainId); - } - SearchCriteria sc = _domainDao.createSearchCriteria(); sc.addAnd("name", SearchCriteria.Op.EQ, domainName); List domains = _domainDao.search(sc, null); if ((domains == null) || domains.isEmpty()) { - //whilst updating a domain name, update its path and update all its children's path + // whilst updating a domain name, update its path and update all its children's path domain = _domainDao.findById(domainId); - String updatedDomainPath = getUpdatedDomainPath(domain.getPath(),domainName); - updateDomainChildren(domain,updatedDomainPath); + String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName); + updateDomainChildren(domain, updatedDomainPath); _domainDao.update(domainId, domainName, updatedDomainPath); return _domainDao.findById(domainId); } else { @@ -3133,25 +3128,25 @@ public class ManagementServerImpl implements ManagementServer { throw new CloudRuntimeException("Failed to update domain " + domainId); } } - - private String getUpdatedDomainPath(String oldPath, String newName){ - String[] tokenizedPath = oldPath.split("/"); - tokenizedPath[tokenizedPath.length-1] = newName; - StringBuilder finalPath = new StringBuilder(); - for(String token : tokenizedPath){ - finalPath.append(token); - finalPath.append("/"); - } - return finalPath.toString(); + + private String getUpdatedDomainPath(String oldPath, String newName) { + String[] tokenizedPath = oldPath.split("/"); + tokenizedPath[tokenizedPath.length - 1] = newName; + StringBuilder finalPath = new StringBuilder(); + for (String token : tokenizedPath) { + finalPath.append(token); + finalPath.append("/"); + } + return finalPath.toString(); } - - private void updateDomainChildren(DomainVO domain, String updatedDomainPrefix){ - List domainChildren = _domainDao.findAllChildren(domain.getPath(), domain.getId()); - //for each child, update the path - for(DomainVO dom : domainChildren){ - dom.setPath(dom.getPath().replaceFirst(domain.getPath(), updatedDomainPrefix)); - _domainDao.update(dom.getId(), dom); - } + + private void updateDomainChildren(DomainVO domain, String updatedDomainPrefix) { + List domainChildren = _domainDao.findAllChildren(domain.getPath(), domain.getId()); + // for each child, update the path + for (DomainVO dom : domainChildren) { + dom.setPath(dom.getPath().replaceFirst(domain.getPath(), updatedDomainPrefix)); + _domainDao.update(dom.getId(), dom); + } } @Override @@ -3184,16 +3179,16 @@ public class ManagementServerImpl implements ManagementServer { Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), null); if (id != null) { - sc.addAnd("id", SearchCriteria.Op.EQ, id); + sc.addAnd("id", SearchCriteria.Op.EQ, id); } - if (zoneId != null){ - sc.addAnd("data_center_id", SearchCriteria.Op.EQ, zoneId); + if (zoneId != null) { + sc.addAnd("data_center_id", SearchCriteria.Op.EQ, zoneId); } - + if (keyword != null) { SearchCriteria ssc = _alertDao.createSearchCriteria(); ssc.addOr("subject", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - + sc.addAnd("subject", SearchCriteria.Op.SC, ssc); } @@ -3215,7 +3210,7 @@ public class ManagementServerImpl implements ManagementServer { Long zoneId = cmd.getZoneId(); Long podId = cmd.getPodId(); Long hostId = cmd.getHostId(); - + zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); if (type != null) { @@ -3234,23 +3229,24 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId); } capacities = _capacityDao.search(sc, searchFilter); - + // op_host_Capacity contains only allocated stats and the real time stats are stored "in memory". - if (type == null || type == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE){ - capacities.addAll(_storageMgr.getSecondaryStorageUsedStats(hostId, podId, zoneId)); - }if (type == null || type == Capacity.CAPACITY_TYPE_STORAGE){ - capacities.addAll(_storageMgr.getStoragePoolUsedStats(hostId, podId, zoneId)); + if (type == null || type == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE) { + capacities.addAll(_storageMgr.getSecondaryStorageUsedStats(hostId, podId, zoneId)); } - + if (type == null || type == Capacity.CAPACITY_TYPE_STORAGE) { + capacities.addAll(_storageMgr.getStoragePoolUsedStats(hostId, podId, zoneId)); + } + return capacities; } - + @Override public long getMemoryUsagebyHost(Long hostId) { - + CapacityVO capacity = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_MEMORY); - return capacity == null ? 0 : capacity.getReservedCapacity() + capacity.getUsedCapacity(); - + return capacity == null ? 0 : capacity.getReservedCapacity() + capacity.getUsedCapacity(); + } @Override @@ -3262,24 +3258,23 @@ public class ManagementServerImpl implements ManagementServer { public List findPrivateDiskOffering() { return _diskOfferingDao.findPrivateDiskOffering(); } - - protected boolean templateIsCorrectType(VMTemplateVO template) { - return true; - } - - public static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } - @Override @DB - public boolean updateTemplatePermissions(UpdateTemplatePermissionsCmd cmd) { + protected boolean templateIsCorrectType(VMTemplateVO template) { + return true; + } + + public static boolean isAdmin(short accountType) { + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + } + + @Override + @DB + public boolean updateTemplatePermissions(UpdateTemplatePermissionsCmd cmd) { return updateTemplateOrIsoPermissions(cmd); } - @Override @DB + @Override + @DB public boolean updateTemplatePermissions(UpdateIsoPermissionsCmd cmd) { return updateTemplateOrIsoPermissions(cmd); } @@ -3287,8 +3282,8 @@ public class ManagementServerImpl implements ManagementServer { @DB protected boolean updateTemplateOrIsoPermissions(UpdateTemplateOrIsoPermissionsCmd cmd) { Transaction txn = Transaction.currentTxn(); - - //Input validation + + // Input validation Long id = cmd.getId(); Account account = UserContext.current().getCaller(); List accountNames = cmd.getAccountNames(); @@ -3299,86 +3294,82 @@ public class ManagementServerImpl implements ManagementServer { String mediaType = ""; VMTemplateVO template = _templateDao.findById(id); - + if (template == null || !templateIsCorrectType(template)) { throw new InvalidParameterValueException("unable to find " + mediaType + " with id " + id); } - if(cmd instanceof UpdateTemplatePermissionsCmd) - { - mediaType = "template"; - if(template.getFormat().equals(ImageFormat.ISO)) - { - throw new InvalidParameterValueException("Please provide a valid template"); - } + if (cmd instanceof UpdateTemplatePermissionsCmd) { + mediaType = "template"; + if (template.getFormat().equals(ImageFormat.ISO)) { + throw new InvalidParameterValueException("Please provide a valid template"); + } } - if(cmd instanceof UpdateIsoPermissionsCmd) - { - mediaType = "iso"; - if(!template.getFormat().equals(ImageFormat.ISO)) - { - throw new InvalidParameterValueException("Please provide a valid iso"); - } + if (cmd instanceof UpdateIsoPermissionsCmd) { + mediaType = "iso"; + if (!template.getFormat().equals(ImageFormat.ISO)) { + throw new InvalidParameterValueException("Please provide a valid iso"); + } } - + _accountMgr.checkAccess(account, template); // If command is executed via 8096 port, set userId to the id of System account (1) if (userId == null) { userId = Long.valueOf(User.UID_SYSTEM); } - + // If the template is removed throw an error. - if (template.getRemoved() != null){ - s_logger.error("unable to update permissions for " + mediaType + " with id " + id + " as it is removed "); - throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id + " as it is removed "); + if (template.getRemoved() != null) { + s_logger.error("unable to update permissions for " + mediaType + " with id " + id + " as it is removed "); + throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id + " as it is removed "); } - + if (id == Long.valueOf(1)) { throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id); } - + boolean isAdmin = ((account == null) || isAdmin(account.getType())); - boolean allowPublicUserTemplates = Boolean.parseBoolean(getConfigurationValue("allow.public.user.templates")); + boolean allowPublicUserTemplates = Boolean.parseBoolean(getConfigurationValue("allow.public.user.templates")); if (!isAdmin && !allowPublicUserTemplates && isPublic != null && isPublic) { - throw new InvalidParameterValueException("Only private " + mediaType + "s can be created."); + throw new InvalidParameterValueException("Only private " + mediaType + "s can be created."); } -// // package up the accountNames as a list -// List accountNameList = new ArrayList(); - if (accountNames != null) - { - if ((operation == null) || (!operation.equalsIgnoreCase("add") && !operation.equalsIgnoreCase("remove") && !operation.equalsIgnoreCase("reset"))) - { - throw new InvalidParameterValueException("Invalid operation on accounts, the operation must be either 'add' or 'remove' in order to modify launch permissions." + - " Given operation is: '" + operation + "'"); + // // package up the accountNames as a list + // List accountNameList = new ArrayList(); + if (accountNames != null) { + if ((operation == null) || (!operation.equalsIgnoreCase("add") && !operation.equalsIgnoreCase("remove") && !operation.equalsIgnoreCase("reset"))) { + throw new InvalidParameterValueException("Invalid operation on accounts, the operation must be either 'add' or 'remove' in order to modify launch permissions." + + " Given operation is: '" + operation + "'"); } -// StringTokenizer st = new StringTokenizer(accountNames, ","); -// while (st.hasMoreTokens()) { -// accountNameList.add(st.nextToken()); -// } + // StringTokenizer st = new StringTokenizer(accountNames, ","); + // while (st.hasMoreTokens()) { + // accountNameList.add(st.nextToken()); + // } } Long accountId = template.getAccountId(); if (accountId == null) { - // if there is no owner of the template then it's probably already a public template (or domain private template) so publishing to individual users is irrelevant + // if there is no owner of the template then it's probably already a public template (or domain private template) so + // publishing to individual users is irrelevant throw new InvalidParameterValueException("Update template permissions is an invalid operation on template " + template.getName()); } VMTemplateVO updatedTemplate = _templateDao.createForUpdate(); - + if (isPublic != null) { updatedTemplate.setPublicTemplate(isPublic.booleanValue()); } - + if (isFeatured != null) { - updatedTemplate.setFeatured(isFeatured.booleanValue()); + updatedTemplate.setFeatured(isFeatured.booleanValue()); } - + _templateDao.update(template.getId(), updatedTemplate); Long domainId; - domainId = (null == account) ? DomainVO.ROOT_DOMAIN : account.getDomainId(); // Account == null for 8096 and so its safe for domainid = ROOT + domainId = (null == account) ? DomainVO.ROOT_DOMAIN : account.getDomainId(); // Account == null for 8096 and so its safe + // for domainid = ROOT if ("add".equalsIgnoreCase(operation)) { txn.start(); for (String accountName : accountNames) { @@ -3421,7 +3412,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd) { Account account = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String acctName = cmd.getAccountName(); @@ -3458,18 +3449,18 @@ public class ManagementServerImpl implements ManagementServer { } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { DomainVO accountDomain = _domainDao.findById(account.getDomainId()); Account templateAccount = _accountDao.findById(template.getAccountId()); - DomainVO templateDomain = _domainDao.findById(templateAccount.getDomainId()); + DomainVO templateDomain = _domainDao.findById(templateAccount.getDomainId()); if (!templateDomain.getPath().contains(accountDomain.getPath())) { throw new PermissionDeniedException("unable to list permissions for " + cmd.getMediaType() + " with id " + id); } - } + } } if (id == Long.valueOf(1)) { throw new PermissionDeniedException("unable to list permissions for " + cmd.getMediaType() + " with id " + id); } - List accountNames = new ArrayList(); + List accountNames = new ArrayList(); List permissions = _launchPermissionDao.findByTemplate(id); if ((permissions != null) && !permissions.isEmpty()) { for (LaunchPermissionVO permission : permissions) { @@ -3480,121 +3471,119 @@ public class ManagementServerImpl implements ManagementServer { return accountNames; } - private List searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter){ - //it was decided to return all offerings for the user's domain, and everything above till root (for normal user or domain admin) - //list all offerings belonging to this domain, and all of its parents - //check the parent, if not null, add offerings for that parent to list - List dol = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - boolean includePublicOfferings = true; - if(domainRecord != null) - { - while(true){ - SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); + private List searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter) { + // it was decided to return all offerings for the user's domain, and everything above till root (for normal user or + // domain admin) + // list all offerings belonging to this domain, and all of its parents + // check the parent, if not null, add offerings for that parent to list + List dol = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + boolean includePublicOfferings = true; + if (domainRecord != null) { + while (true) { + SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - SearchCriteria sc = sb.create(); - if (keyword != null) { - includePublicOfferings = false; - SearchCriteria ssc = _diskOfferingDao.createSearchCriteria(); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + SearchCriteria sc = sb.create(); + if (keyword != null) { + includePublicOfferings = false; + SearchCriteria ssc = _diskOfferingDao.createSearchCriteria(); + ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } - if (name != null) { - includePublicOfferings = false; - sc.setParameters("name", "%" + name + "%"); - } + if (name != null) { + includePublicOfferings = false; + sc.setParameters("name", "%" + name + "%"); + } - if (id != null) { - includePublicOfferings = false; - sc.setParameters("id", id); - } + if (id != null) { + includePublicOfferings = false; + sc.setParameters("id", id); + } - //for this domain - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); - - //search and add for this domain - dol.addAll(_diskOfferingDao.search(sc, searchFilter)); - - //try and move on to the next domain - if(domainRecord.getParent() != null) { + // for this domain + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); + + // search and add for this domain + dol.addAll(_diskOfferingDao.search(sc, searchFilter)); + + // try and move on to the next domain + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); + } else { + break;// now we got all the offerings for this user/dom adm } - else { - break;//now we got all the offerings for this user/dom adm - } - } - }else{ - s_logger.error("Could not find the domainId for account:"+account.getAccountName()); - throw new CloudAuthenticationException("Could not find the domainId for account:"+account.getAccountName()); - } - - //add all the public offerings to the sol list before returning - if(includePublicOfferings) { + } + } else { + s_logger.error("Could not find the domainId for account:" + account.getAccountName()); + throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName()); + } + + // add all the public offerings to the sol list before returning + if (includePublicOfferings) { dol.addAll(_diskOfferingDao.findPublicDiskOfferings()); } - - return dol; - + + return dol; + } - + @Override public List searchForDiskOfferings(ListDiskOfferingsCmd cmd) { - //Note - //The list method for offerings is being modified in accordance with discussion with Will/Kevin - //For now, we will be listing the following based on the usertype - //1. For root, we will list all offerings - //2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way till root - + // Note + // The list method for offerings is being modified in accordance with discussion with Will/Kevin + // For now, we will be listing the following based on the usertype + // 1. For root, we will list all offerings + // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way till + // root + Filter searchFilter = new Filter(DiskOfferingVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); // SearchBuilder and SearchCriteria are now flexible so that the search builder can be built with all possible - // search terms and only those with criteria can be set. The proper SQL should be generated as a result. + // search terms and only those with criteria can be set. The proper SQL should be generated as a result. Account account = UserContext.current().getCaller(); Object name = cmd.getDiskOfferingName(); Object id = cmd.getId(); Object keyword = cmd.getKeyword(); Long domainId = cmd.getDomainId(); - //Keeping this logic consistent with domain specific zones - //if a domainId is provided, we just return the disk offering associated with this domain - if(domainId != null){ - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN){ - return _diskOfferingDao.listByDomainId(domainId);//no perm check - }else{ - //check if the user's domain == do's domain || user's domain is a child of so's domain - if(isPermissible(account.getDomainId(), domainId)){ - //perm check succeeded - return _diskOfferingDao.listByDomainId(domainId); - }else{ - throw new PermissionDeniedException("The account:"+account.getAccountName()+" does not fall in the same domain hierarchy as the disk offering"); - } - } + // Keeping this logic consistent with domain specific zones + // if a domainId is provided, we just return the disk offering associated with this domain + if (domainId != null) { + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + return _diskOfferingDao.listByDomainId(domainId);// no perm check + } else { + // check if the user's domain == do's domain || user's domain is a child of so's domain + if (isPermissible(account.getDomainId(), domainId)) { + // perm check succeeded + return _diskOfferingDao.listByDomainId(domainId); + } else { + throw new PermissionDeniedException("The account:" + account.getAccountName() + " does not fall in the same domain hierarchy as the disk offering"); + } + } } - - //For non-root users - if((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN){ - return searchDiskOfferingsInternal(account, name, id, keyword, searchFilter); + + // For non-root users + if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + return searchDiskOfferingsInternal(account, name, id, keyword, searchFilter); } - - //For root users, preserving existing flow + + // For root users, preserving existing flow sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - // FIXME: disk offerings should search back up the hierarchy for available disk offerings... + // FIXME: disk offerings should search back up the hierarchy for available disk offerings... /* - sb.addAnd("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - if (domainId != null) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.addAnd("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId()); - } - */ + * sb.addAnd("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); if (domainId != null) { + * SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.addAnd("path", + * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, + * sb.entity().getDomainId(), domainSearch.entity().getId()); } + */ SearchCriteria sc = sb.create(); if (keyword != null) { @@ -3613,26 +3602,20 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("id", id); } - // FIXME: disk offerings should search back up the hierarchy for available disk offerings... + // FIXME: disk offerings should search back up the hierarchy for available disk offerings... /* - if (domainId != null) { - sc.setParameters("domainId", domainId); - // - //DomainVO domain = _domainDao.findById((Long)domainId); - // - // I want to join on user_vm.domain_id = domain.id where domain.path like 'foo%' - //sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - // - } - */ + * if (domainId != null) { sc.setParameters("domainId", domainId); // //DomainVO domain = + * _domainDao.findById((Long)domainId); // // I want to join on user_vm.domain_id = domain.id where domain.path like + * 'foo%' //sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); // } + */ return _diskOfferingDao.search(sc, searchFilter); } -// @Override -// public AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd) throws PermissionDeniedException { -// return queryAsyncJobResult(cmd.getId()); -// } + // @Override + // public AsyncJobResult queryAsyncJobResult(QueryAsyncJobResultCmd cmd) throws PermissionDeniedException { + // return queryAsyncJobResult(cmd.getId()); + // } @Override public AsyncJobResult queryAsyncJobResult(long jobId) throws PermissionDeniedException { @@ -3648,38 +3631,36 @@ public class ManagementServerImpl implements ManagementServer { // treat any requests from API server as trusted requests if (!UserContext.current().isApiServer() && job.getAccountId() != UserContext.current().getCaller().getId()) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Mismatched account id in job and user context, perform further securty check. job id: " - + jobId + ", job owner account: " + job.getAccountId() + ", accound id in current context: " + UserContext.current().getCaller().getId()); + s_logger.debug("Mismatched account id in job and user context, perform further securty check. job id: " + jobId + ", job owner account: " + job.getAccountId() + + ", accound id in current context: " + UserContext.current().getCaller().getId()); } - - Account account = UserContext.current().getCaller(); - if (account != null) { - if (isAdmin(account.getType())) { - Account jobAccount = _accountDao.findById(job.getAccountId()); - if (jobAccount == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("queryAsyncJobResult error: Permission denied, account no long exist for account id in context, job id: " + jobId - + ", accountId " + job.getAccountId()); - } - throw new PermissionDeniedException("Permission denied, invalid job ownership, job id: " + jobId); - } - if (!_domainDao.isChildDomain(account.getDomainId(), jobAccount.getDomainId())) { + Account account = UserContext.current().getCaller(); + if (account != null) { + if (isAdmin(account.getType())) { + Account jobAccount = _accountDao.findById(job.getAccountId()); + if (jobAccount == null) { if (s_logger.isDebugEnabled()) { - s_logger.debug("queryAsyncJobResult error: Permission denied, invalid ownership for job " + jobId + ", job account owner: " - + job.getAccountId() + " in domain: " + jobAccount.getDomainId() + ", account id in context: " + account.getId() + - " in domain: " + account.getDomainId()); + s_logger.debug("queryAsyncJobResult error: Permission denied, account no long exist for account id in context, job id: " + jobId + ", accountId " + job.getAccountId()); } throw new PermissionDeniedException("Permission denied, invalid job ownership, job id: " + jobId); - } - } else { - if (s_logger.isDebugEnabled()) { - s_logger.debug("queryAsyncJobResult error: Permission denied, invalid ownership for job " + jobId + ", job account owner: " - + job.getAccountId() + ", account id in context: " + account.getId()); - } + } + + if (!_domainDao.isChildDomain(account.getDomainId(), jobAccount.getDomainId())) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("queryAsyncJobResult error: Permission denied, invalid ownership for job " + jobId + ", job account owner: " + job.getAccountId() + " in domain: " + + jobAccount.getDomainId() + ", account id in context: " + account.getId() + " in domain: " + account.getDomainId()); + } + throw new PermissionDeniedException("Permission denied, invalid job ownership, job id: " + jobId); + } + } else { + if (s_logger.isDebugEnabled()) { + s_logger.debug("queryAsyncJobResult error: Permission denied, invalid ownership for job " + jobId + ", job account owner: " + job.getAccountId() + ", account id in context: " + + account.getId()); + } throw new PermissionDeniedException("Permission denied, invalid job ownership, job id: " + jobId); - } - } + } + } } return _asyncMgr.queryAsyncJobResult(jobId); @@ -3689,7 +3670,7 @@ public class ManagementServerImpl implements ManagementServer { public AsyncJobVO findAsyncJobById(long jobId) { return _asyncMgr.getAsyncJob(jobId); } - + @Override public String[] getApiConfig() { return new String[] { "commands.properties" }; @@ -3712,8 +3693,8 @@ public class ManagementServerImpl implements ManagementServer { Transaction txn = null; try { - txn = Transaction.open(Transaction.CLOUD_DB); - + txn = Transaction.open(Transaction.CLOUD_DB); + List accounts = _accountDao.findCleanups(); s_logger.info("Found " + accounts.size() + " accounts to cleanup"); for (AccountVO account : accounts) { @@ -3727,10 +3708,10 @@ public class ManagementServerImpl implements ManagementServer { } catch (Exception e) { s_logger.error("Exception ", e); } finally { - if(txn != null) { + if (txn != null) { txn.close(); } - + lock.unlock(); } } catch (Exception e) { @@ -3738,7 +3719,7 @@ public class ManagementServerImpl implements ManagementServer { } } } - + protected class EventPurgeTask implements Runnable { @Override public void run() { @@ -3756,10 +3737,10 @@ public class ManagementServerImpl implements ManagementServer { final Calendar purgeCal = Calendar.getInstance(); purgeCal.add(Calendar.DAY_OF_YEAR, -_purgeDelay); Date purgeTime = purgeCal.getTime(); - s_logger.debug("Deleting events older than: "+purgeTime.toString()); + s_logger.debug("Deleting events older than: " + purgeTime.toString()); List oldEvents = _eventDao.listOlderEvents(purgeTime); - s_logger.debug("Found "+oldEvents.size()+" events to be purged"); - for (EventVO event : oldEvents){ + s_logger.debug("Found " + oldEvents.size() + " events to be purged"); + for (EventVO event : oldEvents) { _eventDao.expunge(event.getId()); } } catch (Exception e) { @@ -3780,8 +3761,8 @@ public class ManagementServerImpl implements ManagementServer { @Override public List searchForStoragePools(ListStoragePoolsCmd cmd) { - - Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); + + Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); c.addCriteria(Criteria.ID, cmd.getId()); c.addCriteria(Criteria.NAME, cmd.getStoragePoolName()); @@ -3819,9 +3800,9 @@ public class ManagementServerImpl implements ManagementServer { } if (id != null) { - sc.addAnd("id", SearchCriteria.Op.EQ, id); + sc.addAnd("id", SearchCriteria.Op.EQ, id); } - + if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } @@ -3835,28 +3816,25 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zone); } if (pod != null) { - sc.addAnd("podId", SearchCriteria.Op.EQ, pod); + sc.addAnd("podId", SearchCriteria.Op.EQ, pod); } if (address != null) { - sc.addAnd("hostAddress", SearchCriteria.Op.EQ, address); + sc.addAnd("hostAddress", SearchCriteria.Op.EQ, address); } if (cluster != null) { - sc.addAnd("clusterId", SearchCriteria.Op.EQ, cluster); + sc.addAnd("clusterId", SearchCriteria.Op.EQ, cluster); } return _poolDao.search(sc, searchFilter); } - - @Override - public List searchForStoragePoolDetails(long poolId, String value) - { - return _poolDao.searchForStoragePoolDetails(poolId, value); + public List searchForStoragePoolDetails(long poolId, String value) { + return _poolDao.searchForStoragePoolDetails(poolId, value); } - + @Override - public List searchForAsyncJobs(ListAsyncJobsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List searchForAsyncJobs(ListAsyncJobsCmd cmd) { Filter searchFilter = new Filter(AsyncJobVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _jobDao.createSearchBuilder(); @@ -3876,7 +3854,7 @@ public class ManagementServerImpl implements ManagementServer { } else if (domainId != null) { if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { throw new PermissionDeniedException("Failed to list async jobs for domain " + domainId + "; permission denied."); - } + } // we can do a domain match for the admin case SearchBuilder domainSearch = _domainDao.createSearchBuilder(); @@ -3894,7 +3872,6 @@ public class ManagementServerImpl implements ManagementServer { Object keyword = cmd.getKeyword(); Object startDate = cmd.getStartDate(); - SearchCriteria sc = _jobDao.createSearchCriteria(); if (keyword != null) { sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -3919,14 +3896,14 @@ public class ManagementServerImpl implements ManagementServer { return _domainDao.isChildDomain(parentId, childId); } - @ActionEvent (eventType=EventTypes.EVENT_SSVM_START, eventDescription="starting secondary storage Vm", async=true) + @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true) public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { return _secStorageVmMgr.startSecStorageVm(instanceId); } - @ActionEvent (eventType=EventTypes.EVENT_SSVM_STOP, eventDescription="stopping secondary storage Vm", async=true) + @ActionEvent(eventType = EventTypes.EVENT_SSVM_STOP, eventDescription = "stopping secondary storage Vm", async = true) public SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { - + User caller = _userDao.findById(UserContext.current().getCallerUserId()); if (_itMgr.advanceStop(systemVm, isForced, caller, UserContext.current().getCaller())) { @@ -3935,22 +3912,22 @@ public class ManagementServerImpl implements ManagementServer { return null; } - @ActionEvent (eventType=EventTypes.EVENT_SSVM_REBOOT, eventDescription="rebooting secondary storage Vm", async=true) + @ActionEvent(eventType = EventTypes.EVENT_SSVM_REBOOT, eventDescription = "rebooting secondary storage Vm", async = true) public SecondaryStorageVmVO rebootSecondaryStorageVm(long instanceId) { _secStorageVmMgr.rebootSecStorageVm(instanceId); return _secStorageVmDao.findById(instanceId); } - @ActionEvent (eventType=EventTypes.EVENT_SSVM_DESTROY, eventDescription="destroying secondary storage Vm", async=true) + @ActionEvent(eventType = EventTypes.EVENT_SSVM_DESTROY, eventDescription = "destroying secondary storage Vm", async = true) public SecondaryStorageVmVO destroySecondaryStorageVm(long instanceId) { - SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(instanceId); - if(_secStorageVmMgr.destroySecStorageVm(instanceId)) { + SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(instanceId); + if (_secStorageVmMgr.destroySecStorageVm(instanceId)) { return secStorageVm; } return null; } - @Override + @Override public List searchForSecondaryStorageVm(Criteria c) { Filter searchFilter = new Filter(SecondaryStorageVmVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); SearchCriteria sc = _secStorageVmDao.createSearchCriteria(); @@ -3970,8 +3947,8 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - - if(id != null) { + + if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } @@ -3994,8 +3971,9 @@ public class ManagementServerImpl implements ManagementServer { return _secStorageVmDao.search(sc, searchFilter); } - @Override @SuppressWarnings({"unchecked", "rawtypes"}) - public List searchForSystemVm(ListSystemVMsCmd cmd) { + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public List searchForSystemVm(ListSystemVMsCmd cmd) { Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); @@ -4010,53 +3988,53 @@ public class ManagementServerImpl implements ManagementServer { String type = cmd.getSystemVmType(); List systemVMs = new ArrayList(); - if (type == null) { //search for all vm types + if (type == null) { // search for all vm types systemVMs.addAll(searchForConsoleProxy(c)); systemVMs.addAll(searchForSecondaryStorageVm(c)); - } else if((type != null) && (type.equalsIgnoreCase("secondarystoragevm"))) { // search for ssvm + } else if ((type != null) && (type.equalsIgnoreCase("secondarystoragevm"))) { // search for ssvm systemVMs.addAll(searchForSecondaryStorageVm(c)); - } else if((type != null) && (type.equalsIgnoreCase("consoleproxy"))) { // search for consoleproxy + } else if ((type != null) && (type.equalsIgnoreCase("consoleproxy"))) { // search for consoleproxy systemVMs.addAll(searchForConsoleProxy(c)); } return systemVMs; - } + } - @Override - public VMInstanceVO findSystemVMById(long instanceId) { - VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); - if(systemVm == null) { + @Override + public VMInstanceVO findSystemVMById(long instanceId) { + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); + if (systemVm == null) { return null; } - - if(systemVm.getType() == VirtualMachine.Type.ConsoleProxy) { + + if (systemVm.getType() == VirtualMachine.Type.ConsoleProxy) { return _consoleProxyDao.findById(instanceId); } - return _secStorageVmDao.findById(instanceId); - } - - @Override - public VirtualMachine.Type findSystemVMTypeById(long instanceId) { - VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); - if(systemVm == null) { - throw new InvalidParameterValueException("Unable to find a system vm: " + instanceId); - } - return systemVm.getType(); - } + return _secStorageVmDao.findById(instanceId); + } - @Override - public VirtualMachine startSystemVM(StartSystemVMCmd cmd) { - return startSystemVm(cmd.getId()); - } + @Override + public VirtualMachine.Type findSystemVMTypeById(long instanceId) { + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); + if (systemVm == null) { + throw new InvalidParameterValueException("Unable to find a system vm: " + instanceId); + } + return systemVm.getType(); + } + + @Override + public VirtualMachine startSystemVM(StartSystemVMCmd cmd) { + return startSystemVm(cmd.getId()); + } @Override public VirtualMachine startSystemVm(long vmId) { - + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { throw new InvalidParameterValueException("unable to find a system vm with id " + vmId); } - + if (systemVm.getType() == VirtualMachine.Type.ConsoleProxy) { return startConsoleProxy(vmId); } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) { @@ -4065,119 +4043,116 @@ public class ManagementServerImpl implements ManagementServer { throw new InvalidParameterValueException("Unable to find a system vm: " + vmId); } } - - @Override - public VMInstanceVO stopSystemVM(StopSystemVmCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException { - Long id = cmd.getId(); - - // verify parameters - VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); + + @Override + public VMInstanceVO stopSystemVM(StopSystemVmCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException { + Long id = cmd.getId(); + + // verify parameters + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - throw new InvalidParameterValueException("unable to find a system vm with id " + id); + throw new InvalidParameterValueException("unable to find a system vm with id " + id); } - + try { if (systemVm.getType() == VirtualMachine.Type.ConsoleProxy) { return stopConsoleProxy(systemVm, cmd.isForced()); } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) { return stopSecondaryStorageVm(systemVm, cmd.isForced()); - } + } return null; } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Unable to stop " + systemVm, e); } - } - - @Override - public VMInstanceVO rebootSystemVM(RebootSystemVmCmd cmd) { - VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); - - if (systemVm == null) { - throw new InvalidParameterValueException("unable to find a system vm with id " + cmd.getId()); - } - - if (systemVm.getType().equals(VirtualMachine.Type.ConsoleProxy)){ - return rebootConsoleProxy(cmd.getId()); - } else { - return rebootSecondaryStorageVm(cmd.getId()); - } - } + } @Override - public VMInstanceVO destroySystemVM(DestroySystemVmCmd cmd) { + public VMInstanceVO rebootSystemVM(RebootSystemVmCmd cmd) { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); - + if (systemVm == null) { throw new InvalidParameterValueException("unable to find a system vm with id " + cmd.getId()); } - - if (systemVm.getType().equals(VirtualMachine.Type.ConsoleProxy)){ + + if (systemVm.getType().equals(VirtualMachine.Type.ConsoleProxy)) { + return rebootConsoleProxy(cmd.getId()); + } else { + return rebootSecondaryStorageVm(cmd.getId()); + } + } + + @Override + public VMInstanceVO destroySystemVM(DestroySystemVmCmd cmd) { + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); + + if (systemVm == null) { + throw new InvalidParameterValueException("unable to find a system vm with id " + cmd.getId()); + } + + if (systemVm.getType().equals(VirtualMachine.Type.ConsoleProxy)) { return destroyConsoleProxy(cmd.getId()); } else { return destroySecondaryStorageVm(cmd.getId()); } } - - private String signRequest(String request, String key) { - try - { - s_logger.info("Request: "+request); - s_logger.info("Key: "+key); - - if(key != null && request != null) - { - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), - "HmacSHA1"); - mac.init(keySpec); - mac.update(request.getBytes()); - byte[] encryptedBytes = mac.doFinal(); - return new String ((Base64.encodeBase64(encryptedBytes))); - } - } catch (Exception ex) { - s_logger.error("unable to sign request", ex); - } - return null; - } + + private String signRequest(String request, String key) { + try { + s_logger.info("Request: " + request); + s_logger.info("Key: " + key); + + if (key != null && request != null) { + Mac mac = Mac.getInstance("HmacSHA1"); + SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); + mac.init(keySpec); + mac.update(request.getBytes()); + byte[] encryptedBytes = mac.doFinal(); + return new String((Base64.encodeBase64(encryptedBytes))); + } + } catch (Exception ex) { + s_logger.error("unable to sign request", ex); + } + return null; + } @Override - public ArrayList getCloudIdentifierResponse(GetCloudIdentifierCmd cmd) throws InvalidParameterValueException{ - Long userId = cmd.getUserId(); - - //verify that user exists + public ArrayList getCloudIdentifierResponse(GetCloudIdentifierCmd cmd) { + Long userId = cmd.getUserId(); + + // verify that user exists User user = findUserById(userId); if ((user == null) || (user.getRemoved() != null)) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - String cloudIdentifier = _configDao.getValue("cloud.identifier"); - if (cloudIdentifier == null) { - cloudIdentifier = ""; - } + String cloudIdentifier = _configDao.getValue("cloud.identifier"); + if (cloudIdentifier == null) { + cloudIdentifier = ""; + } - String signature = ""; - try { - //get the user obj to get his secret key - user = getUser(userId); - String secretKey = user.getSecretKey(); - String input = cloudIdentifier; - signature = signRequest(input, secretKey); - } catch (Exception e) { - s_logger.warn("Exception whilst creating a signature:"+e); - } - - ArrayList cloudParams = new ArrayList(); - cloudParams.add(cloudIdentifier); - cloudParams.add(signature); + String signature = ""; + try { + // get the user obj to get his secret key + user = getUser(userId); + String secretKey = user.getSecretKey(); + String input = cloudIdentifier; + signature = signRequest(input, secretKey); + } catch (Exception e) { + s_logger.warn("Exception whilst creating a signature:" + e); + } + + ArrayList cloudParams = new ArrayList(); + cloudParams.add(cloudIdentifier); + cloudParams.add(signature); return cloudParams; } - @Override - public SecurityGroupVO findNetworkGroupByName(Long accountId, String groupName) { - SecurityGroupVO groupVO = _networkSecurityGroupDao.findByAccountAndName(accountId, groupName); - return groupVO; - } + @Override + public SecurityGroupVO findNetworkGroupByName(Long accountId, String groupName) { + SecurityGroupVO groupVO = _networkSecurityGroupDao.findByAccountAndName(accountId, groupName); + return groupVO; + } @Override public SecurityGroupVO findNetworkGroupById(long networkGroupId) { @@ -4195,9 +4170,9 @@ public class ManagementServerImpl implements ManagementServer { Date maxTime = calMax.getTime(); List startedEvents = _eventDao.listStartedEvents(minTime, maxTime); List pendingEvents = new ArrayList(); - for (EventVO event : startedEvents){ + for (EventVO event : startedEvents) { EventVO completedEvent = _eventDao.findCompletedEvent(event.getId()); - if(completedEvent == null){ + if (completedEvent == null) { pendingEvents.add(event); } } @@ -4205,97 +4180,93 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public boolean checkLocalStorageConfigVal() - { - String value = _configs.get("use.local.storage"); - - if(value!=null && value.equalsIgnoreCase("true")) { + public boolean checkLocalStorageConfigVal() { + String value = _configs.get("use.local.storage"); + + if (value != null && value.equalsIgnoreCase("true")) { return true; } else { return false; } - } + } - @Override - public boolean checkIfMaintenable(long hostId) { + @Override + public boolean checkIfMaintenable(long hostId) { - //get the poolhostref record - List poolHostRecordSet = _poolHostDao.listByHostId(hostId); - - if(poolHostRecordSet!=null) - { - //the above list has only 1 record - StoragePoolHostVO poolHostRecord = poolHostRecordSet.get(0); - - //get the poolId and get hosts associated in that pool - List hostsInPool = _poolHostDao.listByPoolId(poolHostRecord.getPoolId()); - - if(hostsInPool!=null && hostsInPool.size()>1) - { - return true; //since there are other hosts to take over as master in this pool - } - } - return false; - } + // get the poolhostref record + List poolHostRecordSet = _poolHostDao.listByHostId(hostId); + + if (poolHostRecordSet != null) { + // the above list has only 1 record + StoragePoolHostVO poolHostRecord = poolHostRecordSet.get(0); + + // get the poolId and get hosts associated in that pool + List hostsInPool = _poolHostDao.listByPoolId(poolHostRecord.getPoolId()); + + if (hostsInPool != null && hostsInPool.size() > 1) { + return true; // since there are other hosts to take over as master in this pool + } + } + return false; + } @Override public Map listCapabilities(ListCapabilitiesCmd cmd) { Map capabilities = new HashMap(); - + boolean securityGroupsEnabled = false; List dc = _dcDao.listSecurityGroupEnabledZones(); if (dc != null && !dc.isEmpty()) { securityGroupsEnabled = true; } - + String userPublicTemplateEnabled = _configs.get(Config.AllowPublicUserTemplates.key()); - capabilities.put("securityGroupsEnabled", securityGroupsEnabled); + capabilities.put("securityGroupsEnabled", securityGroupsEnabled); capabilities.put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); capabilities.put("cloudStackVersion", getVersion()); return capabilities; } @Override - public GuestOSVO getGuestOs(Long guestOsId) - { - return _guestOSDao.findById(guestOsId); + public GuestOSVO getGuestOs(Long guestOsId) { + return _guestOSDao.findById(guestOsId); } - - @Override - public VolumeVO getRootVolume(Long instanceId) - { - return _volumeDao.findByInstanceAndType(instanceId, Volume.Type.ROOT).get(0); - } - - @Override - public long getPsMaintenanceCount(long podId){ - List poolsInTransition = new ArrayList(); - poolsInTransition.addAll(_poolDao.listPoolsByStatus(StoragePoolStatus.Maintenance)); - poolsInTransition.addAll(_poolDao.listPoolsByStatus(StoragePoolStatus.PrepareForMaintenance)); - poolsInTransition.addAll(_poolDao.listPoolsByStatus(StoragePoolStatus.ErrorInMaintenance)); - return poolsInTransition.size(); - } - @Override - public boolean isPoolUp(long instanceId){ - VolumeVO rootVolume = _volumeDao.findByInstance(instanceId).get(0); - - if(rootVolume!=null){ - StoragePoolStatus poolStatus = _poolDao.findById(rootVolume.getPoolId()).getStatus(); - - if(!poolStatus.equals(Status.Up)) { + public VolumeVO getRootVolume(Long instanceId) { + return _volumeDao.findByInstanceAndType(instanceId, Volume.Type.ROOT).get(0); + } + + @Override + public long getPsMaintenanceCount(long podId) { + List poolsInTransition = new ArrayList(); + poolsInTransition.addAll(_poolDao.listPoolsByStatus(StoragePoolStatus.Maintenance)); + poolsInTransition.addAll(_poolDao.listPoolsByStatus(StoragePoolStatus.PrepareForMaintenance)); + poolsInTransition.addAll(_poolDao.listPoolsByStatus(StoragePoolStatus.ErrorInMaintenance)); + + return poolsInTransition.size(); + } + + @Override + public boolean isPoolUp(long instanceId) { + VolumeVO rootVolume = _volumeDao.findByInstance(instanceId).get(0); + + if (rootVolume != null) { + StoragePoolStatus poolStatus = _poolDao.findById(rootVolume.getPoolId()).getStatus(); + + if (!poolStatus.equals(Status.Up)) { return false; } else { return true; } - } - - return false; + } + + return false; } - @Override @ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true) public Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException { Long volumeId = cmd.getId(); String url = cmd.getUrl(); @@ -4303,61 +4274,62 @@ public class ManagementServerImpl implements ManagementServer { AsyncJobVO job = null; // FIXME: cmd.getJob(); String mode = cmd.getMode(); Account account = UserContext.current().getCaller(); - - VolumeVO volume = _volumeDao.findById(volumeId); + + VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Unable to find volume with id " + volumeId); } if (_dcDao.findById(zoneId) == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone."); } - if(volume.getPoolId() == null){ + if (volume.getPoolId() == null) { throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it"); } - //Extract activity only for detached volumes or for volumes whose instance is stopped - if(volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped ){ + // Extract activity only for detached volumes or for volumes whose instance is stopped + if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) { s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); throw new PermissionDeniedException("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); } - - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - boolean isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; - if( !isExtractable && account!=null && account.getType() != Account.ACCOUNT_TYPE_ADMIN){ // Global admins are allowed to extract - throw new PermissionDeniedException("The volume:" +volumeId+ " is not allowed to be extracted"); + + VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); + boolean isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; + if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global admins are allowed + // to extract + throw new PermissionDeniedException("The volume:" + volumeId + " is not allowed to be extracted"); } - + Upload.Mode extractMode; - if( mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString())) ){ + if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) { throw new InvalidParameterValueException("Please specify a valid extract Mode "); - }else{ + } else { extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD; } - - if (account != null) { - if(!isAdmin(account.getType())){ - if (volume.getAccountId() != account.getId()){ + + if (account != null) { + if (!isAdmin(account.getType())) { + if (volume.getAccountId() != account.getId()) { throw new PermissionDeniedException("Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName()); } } else { Account userAccount = _accountDao.findById(volume.getAccountId()); - if((userAccount == null) || !_domainDao.isChildDomain(account.getDomainId(), userAccount.getDomainId())) { + if ((userAccount == null) || !_domainDao.isChildDomain(account.getDomainId(), userAccount.getDomainId())) { throw new PermissionDeniedException("Unable to extract volume:" + volumeId + " - permission denied."); } } } - + // If mode is upload perform extra checks on url and also see if there is an ongoing upload on the same. - if (extractMode == Upload.Mode.FTP_UPLOAD){ + if (extractMode == Upload.Mode.FTP_UPLOAD) { URI uri = new URI(url); - if ( (uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp") )) { - throw new IllegalArgumentException("Unsupported scheme for url: " + url); + if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp"))) { + throw new IllegalArgumentException("Unsupported scheme for url: " + url); } - + String host = uri.getHost(); try { InetAddress hostAddr = InetAddress.getByName(host); - if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress() ) { + if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { throw new IllegalArgumentException("Illegal host specified in url"); } if (hostAddr instanceof Inet6Address) { @@ -4365,40 +4337,40 @@ public class ManagementServerImpl implements ManagementServer { } } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); - } - - if ( _uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME) ){ + } + + if (_uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME)) { throw new IllegalArgumentException(volume.getName() + " upload is in progress. Please wait for some time to schedule another upload for the same"); } } - - long userId = UserContext.current().getCallerUserId(); - long accountId = volume.getAccountId(); - String secondaryStorageURL = _storageMgr.getSecondaryStorageURL(zoneId); + long userId = UserContext.current().getCallerUserId(); + long accountId = volume.getAccountId(); + + String secondaryStorageURL = _storageMgr.getSecondaryStorageURL(zoneId); StoragePoolVO srcPool = _poolDao.findById(volume.getPoolId()); List storageServers = _hostDao.listByTypeDataCenter(Host.Type.SecondaryStorage, zoneId); HostVO sserver = storageServers.get(0); List extractURLList = _uploadDao.listByTypeUploadStatus(volumeId, Upload.Type.VOLUME, UploadVO.Status.DOWNLOAD_URL_CREATED); - - if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0){ - return extractURLList.get(0).getId(); // If download url already exists then return - }else { + + if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) { + return extractURLList.get(0).getId(); // If download url already exists then return + } else { UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, url, extractMode); - s_logger.debug("Extract Mode - " +uploadJob.getMode()); + s_logger.debug("Extract Mode - " + uploadJob.getMode()); uploadJob = _uploadDao.createForUpdate(uploadJob.getId()); - + // Update the async Job ExtractResponse resultObj = new ExtractResponse(volumeId, volume.getName(), accountId, UploadVO.Status.COPY_IN_PROGRESS.toString(), uploadJob.getId()); resultObj.setResponseName(cmd.getCommandName()); AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if (asyncExecutor != null) { - job = asyncExecutor.getJob(); - _asyncMgr.updateAsyncJobAttachment(job.getId(), Upload.Type.VOLUME.toString(), volumeId); - _asyncMgr.updateAsyncJobStatus(job.getId(), AsyncJobResult.STATUS_IN_PROGRESS, resultObj); + job = asyncExecutor.getJob(); + _asyncMgr.updateAsyncJobAttachment(job.getId(), Upload.Type.VOLUME.toString(), volumeId); + _asyncMgr.updateAsyncJobStatus(job.getId(), AsyncJobResult.STATUS_IN_PROGRESS, resultObj); } - + // Copy the volume from the source storage pool to secondary storage CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true); CopyVolumeAnswer cvAnswer = null; @@ -4409,37 +4381,37 @@ public class ManagementServerImpl implements ManagementServer { } // Check if you got a valid answer. - if (cvAnswer == null || !cvAnswer.getResult()) { + if (cvAnswer == null || !cvAnswer.getResult()) { String errorString = "Failed to copy the volume from the source primary storage pool to secondary storage."; - //Update the async job. + // Update the async job. resultObj.setResultString(errorString); resultObj.setUploadStatus(UploadVO.Status.COPY_ERROR.toString()); if (asyncExecutor != null) { - _asyncMgr.completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, 0, resultObj); + _asyncMgr.completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, 0, resultObj); } - //Update the DB that volume couldn't be copied - uploadJob.setUploadState(UploadVO.Status.COPY_ERROR); + // Update the DB that volume couldn't be copied + uploadJob.setUploadState(UploadVO.Status.COPY_ERROR); uploadJob.setErrorString(errorString); uploadJob.setLastUpdated(new Date()); _uploadDao.update(uploadJob.getId(), uploadJob); - - throw new CloudRuntimeException(errorString); + + throw new CloudRuntimeException(errorString); } - - String volumeLocalPath = "volumes/"+volume.getId()+"/"+cvAnswer.getVolumePath()+".vhd"; - //Update the DB that volume is copied and volumePath + + String volumeLocalPath = "volumes/" + volume.getId() + "/" + cvAnswer.getVolumePath() + ".vhd"; + // Update the DB that volume is copied and volumePath uploadJob.setUploadState(UploadVO.Status.COPY_COMPLETE); uploadJob.setLastUpdated(new Date()); uploadJob.setInstallPath(volumeLocalPath); _uploadDao.update(uploadJob.getId(), uploadJob); - - if (extractMode == Mode.FTP_UPLOAD){ // Now that the volume is copied perform the actual uploading + + if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is copied perform the actual uploading _uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath, cmd.getStartEventId(), job.getId(), _asyncMgr); return uploadJob.getId(); - }else{ // Volume is copied now make it visible under apache and create a URL. - _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId()); + } else { // Volume is copied now make it visible under apache and create a URL. + _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId()); return uploadJob.getId(); } } @@ -4466,7 +4438,7 @@ public class ManagementServerImpl implements ManagementServer { } } - //Check if name is already in use by this account (exclude this group) + // Check if name is already in use by this account (exclude this group) boolean isNameInUse = _vmGroupDao.isNameInUse(group.getAccountId(), groupName); if (isNameInUse && !group.getName().equals(groupName)) { @@ -4474,7 +4446,7 @@ public class ManagementServerImpl implements ManagementServer { } if (groupName != null) { - _vmGroupDao.updateVmGroup(groupId, groupName); + _vmGroupDao.updateVmGroup(groupId, groupName); } InstanceGroupVO vmGroup = _vmGroupDao.findById(groupId); return vmGroup; @@ -4531,11 +4503,11 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria ssc = _vmGroupDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } - - if (id != null) { - sc.setParameters("id", id); - } - + + if (id != null) { + sc.setParameters("id", id); + } + if (name != null) { sc.setParameters("name", "%" + name + "%"); } @@ -4544,206 +4516,197 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("accountId", accountId); } else if (domainId != null) { DomainVO domain = _domainDao.findById(domainId); - if (domain != null){ - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } + if (domain != null) { + sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); + } } return _vmGroupDao.search(sc, searchFilter); } - @Override - public InstanceGroupVO getGroupForVm(long vmId){ - return _vmMgr.getGroupForVm(vmId); - } - @Override - public List searchForZoneWideVlans(long dcId, String vlanType, String vlanId){ - return _vlanDao.searchForZoneWideVlans(dcId, vlanType, vlanId); + public InstanceGroupVO getGroupForVm(long vmId) { + return _vmMgr.getGroupForVm(vmId); } @Override - public String getVersion(){ - final Class c = ManagementServer.class; - String fullVersion = c.getPackage().getImplementationVersion(); - if(fullVersion.length() > 0){ - return fullVersion; - } - - return "unknown"; + public List searchForZoneWideVlans(long dcId, String vlanType, String vlanId) { + return _vlanDao.searchForZoneWideVlans(dcId, vlanType, vlanId); } - private Long saveScheduledEvent(Long userId, Long accountId, String type, String description) - { + @Override + public String getVersion() { + final Class c = ManagementServer.class; + String fullVersion = c.getPackage().getImplementationVersion(); + if (fullVersion.length() > 0) { + return fullVersion; + } + + return "unknown"; + } + + private Long saveScheduledEvent(Long userId, Long accountId, String type, String description) { EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setType(type); event.setState(Event.State.Scheduled); - event.setDescription("Scheduled async job for "+description); + event.setDescription("Scheduled async job for " + description); event = _eventDao.persist(event); return event.getId(); } - + @Override - public Long saveStartedEvent(Long userId, Long accountId, String type, String description, long startEventId) - { + public Long saveStartedEvent(Long userId, Long accountId, String type, String description, long startEventId) { return EventUtils.saveStartedEvent(userId, accountId, type, description, startEventId); } - + @Override - public Long saveCompletedEvent(Long userId, Long accountId, String level, String type, String description, long startEventId) - { + public Long saveCompletedEvent(Long userId, Long accountId, String level, String type, String description, long startEventId) { return EventUtils.saveEvent(userId, accountId, level, type, description, startEventId); } - @Override @DB - public String uploadCertificate(UploadCustomCertificateCmd cmd){ - CertificateVO cert = null; - Long certVOId = null; - try - { - Transaction.currentTxn(); - String certificate = cmd.getCertificate(); - cert = _certDao.listAll().get(0); //always 1 record in db (from the deploydb time) - cert = _certDao.acquireInLockTable(cert.getId()); - if(cert == null){ - String msg = "Unable to obtain lock on the cert from uploadCertificate()"; - s_logger.error(msg); - throw new ConcurrentOperationException(msg); - }else{ - if(cert.getUpdated().equalsIgnoreCase("Y")){ - if(s_logger.isDebugEnabled()) { + @Override + @DB + public String uploadCertificate(UploadCustomCertificateCmd cmd) { + CertificateVO cert = null; + Long certVOId = null; + try { + Transaction.currentTxn(); + String certificate = cmd.getCertificate(); + cert = _certDao.listAll().get(0); // always 1 record in db (from the deploydb time) + cert = _certDao.acquireInLockTable(cert.getId()); + if (cert == null) { + String msg = "Unable to obtain lock on the cert from uploadCertificate()"; + s_logger.error(msg); + throw new ConcurrentOperationException(msg); + } else { + if (cert.getUpdated().equalsIgnoreCase("Y")) { + if (s_logger.isDebugEnabled()) { s_logger.debug("A custom certificate already exists in the DB, will replace it with the new one being uploaded"); } - }else{ - if(s_logger.isDebugEnabled()) { + } else { + if (s_logger.isDebugEnabled()) { s_logger.debug("No custom certificate exists in the DB, will upload a new one"); - } - } - - //validate if the cert follows X509 format, if not, don't persist to db - InputStream is = new ByteArrayInputStream(certificate.getBytes("UTF-8")); - BufferedInputStream bis = new BufferedInputStream(is); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - while (bis.available() > 1) { - Certificate localCert = cf.generateCertificate(bis);//throws certexception if not valid cert format - if(s_logger.isDebugEnabled()){ - s_logger.debug("The custom certificate generated for validation is:"+localCert.toString()); - } - } - - certVOId = _certDao.persistCustomCertToDb(certificate,cert,this.getId());//0 implies failure - if(s_logger.isDebugEnabled()) { + } + } + + // validate if the cert follows X509 format, if not, don't persist to db + InputStream is = new ByteArrayInputStream(certificate.getBytes("UTF-8")); + BufferedInputStream bis = new BufferedInputStream(is); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + while (bis.available() > 1) { + Certificate localCert = cf.generateCertificate(bis);// throws certexception if not valid cert format + if (s_logger.isDebugEnabled()) { + s_logger.debug("The custom certificate generated for validation is:" + localCert.toString()); + } + } + + certVOId = _certDao.persistCustomCertToDb(certificate, cert, this.getId());// 0 implies failure + if (s_logger.isDebugEnabled()) { s_logger.debug("Custom certificate persisted to the DB"); - } - } - - if (certVOId != 0) - { - //certficate uploaded to db successfully - //get a list of all Console proxies from the cp table - List cpList = _consoleProxyDao.listAll(); - if(cpList.size() == 0){ - String msg = "Unable to find any console proxies in the system for certificate update"; - s_logger.warn(msg); - throw new ExecutionException(msg); - } - //get a list of all hosts in host table for type cp - List cpHosts = _hostDao.listByType(com.cloud.host.Host.Type.ConsoleProxy); - if(cpHosts.size() == 0){ - String msg = "Unable to find any console proxy hosts in the system for certificate update"; - s_logger.warn(msg); - throw new ExecutionException(msg); - } - //create a hashmap for fast lookup - Map hostNameToHostIdMap = new HashMap(); - //updated console proxies id list - List updatedCpIdList = new ArrayList(); - for(HostVO cpHost : cpHosts){ - hostNameToHostIdMap.put(cpHost.getName(), cpHost.getId()); - } - for(ConsoleProxyVO cp : cpList) - { - Long cpHostId = hostNameToHostIdMap.get(cp.getName()); - //now send a command to each console proxy host - UpdateCertificateCommand certCmd = new UpdateCertificateCommand(_certDao.findById(certVOId).getCertificate(), false); - try { - Answer updateCertAns = _agentMgr.send(cpHostId, certCmd); - if(updateCertAns.getResult() == true) - { - //we have the cert copied over on cpvm - _consoleProxyMgr.rebootProxy(cp.getId()); - //when cp reboots, the context will be reinit with the new cert - if(s_logger.isDebugEnabled()) { - s_logger.debug("Successfully updated custom certificate on console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId); - } - updatedCpIdList.add(cp.getId()); - } - } catch (AgentUnavailableException e) { - s_logger.warn("Unable to send update certificate command to the console proxy resource as agent is unavailable for console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId, e); - } catch (OperationTimedoutException e) { - s_logger.warn("Unable to send update certificate command to the console proxy resource as there was a timeout for console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId, e); - } - } - - if(updatedCpIdList.size() == cpList.size()){ - //success case, all updated - return ("Updated:"+updatedCpIdList.size()+" out of:"+cpList.size()+" console proxies"); - }else{ - //failure case, if even one update fails - throw new ManagementServerException("Updated:"+updatedCpIdList.size()+" out of:"+cpList.size()+" console proxies with successfully updated console proxy ids being:"+(updatedCpIdList.size() > 0 ? updatedCpIdList.toString():"")); - } - } - else - { - throw new ManagementServerException("Unable to persist custom certificate to the cloud db"); - } - }catch (Exception e) { - s_logger.warn("Failed to successfully update the cert across console proxies on management server:"+this.getId()); - if(e instanceof ExecutionException) { + } + } + + if (certVOId != 0) { + // certficate uploaded to db successfully + // get a list of all Console proxies from the cp table + List cpList = _consoleProxyDao.listAll(); + if (cpList.size() == 0) { + String msg = "Unable to find any console proxies in the system for certificate update"; + s_logger.warn(msg); + throw new ExecutionException(msg); + } + // get a list of all hosts in host table for type cp + List cpHosts = _hostDao.listByType(com.cloud.host.Host.Type.ConsoleProxy); + if (cpHosts.size() == 0) { + String msg = "Unable to find any console proxy hosts in the system for certificate update"; + s_logger.warn(msg); + throw new ExecutionException(msg); + } + // create a hashmap for fast lookup + Map hostNameToHostIdMap = new HashMap(); + // updated console proxies id list + List updatedCpIdList = new ArrayList(); + for (HostVO cpHost : cpHosts) { + hostNameToHostIdMap.put(cpHost.getName(), cpHost.getId()); + } + for (ConsoleProxyVO cp : cpList) { + Long cpHostId = hostNameToHostIdMap.get(cp.getName()); + // now send a command to each console proxy host + UpdateCertificateCommand certCmd = new UpdateCertificateCommand(_certDao.findById(certVOId).getCertificate(), false); + try { + Answer updateCertAns = _agentMgr.send(cpHostId, certCmd); + if (updateCertAns.getResult() == true) { + // we have the cert copied over on cpvm + _consoleProxyMgr.rebootProxy(cp.getId()); + // when cp reboots, the context will be reinit with the new cert + if (s_logger.isDebugEnabled()) { + s_logger.debug("Successfully updated custom certificate on console proxy vm id:" + cp.getId() + " ,console proxy host id:" + cpHostId); + } + updatedCpIdList.add(cp.getId()); + } + } catch (AgentUnavailableException e) { + s_logger.warn("Unable to send update certificate command to the console proxy resource as agent is unavailable for console proxy vm id:" + cp.getId() + + " ,console proxy host id:" + cpHostId, e); + } catch (OperationTimedoutException e) { + s_logger.warn("Unable to send update certificate command to the console proxy resource as there was a timeout for console proxy vm id:" + cp.getId() + + " ,console proxy host id:" + cpHostId, e); + } + } + + if (updatedCpIdList.size() == cpList.size()) { + // success case, all updated + return ("Updated:" + updatedCpIdList.size() + " out of:" + cpList.size() + " console proxies"); + } else { + // failure case, if even one update fails + throw new ManagementServerException("Updated:" + updatedCpIdList.size() + " out of:" + cpList.size() + " console proxies with successfully updated console proxy ids being:" + + (updatedCpIdList.size() > 0 ? updatedCpIdList.toString() : "")); + } + } else { + throw new ManagementServerException("Unable to persist custom certificate to the cloud db"); + } + } catch (Exception e) { + s_logger.warn("Failed to successfully update the cert across console proxies on management server:" + this.getId()); + if (e instanceof ExecutionException) { throw new CloudRuntimeException(e.getMessage()); - } else if(e instanceof ManagementServerException) { + } else if (e instanceof ManagementServerException) { throw new CloudRuntimeException(e.getMessage()); - } else if(e instanceof IndexOutOfBoundsException){ - String msg = "Custom certificate record in the db deleted; this should never happen. Please create a new record in the certificate table"; - s_logger.error(msg,e); - throw new CloudRuntimeException(msg); - } - else if(e instanceof FileNotFoundException){ - String msg = "Invalid file path for custom cert found during cert validation"; - s_logger.error(msg,e); - throw new InvalidParameterValueException(msg); - } - else if(e instanceof CertificateException){ - String msg = "The file format for custom cert does not conform to the X.509 specification"; - s_logger.error(msg,e); - throw new CloudRuntimeException(msg); - } - else if(e instanceof UnsupportedEncodingException){ - String msg = "Unable to encode the certificate into UTF-8 input stream for validation"; - s_logger.error(msg,e); - throw new CloudRuntimeException(msg); - } - else if(e instanceof IOException){ - String msg = "Cannot generate input stream during custom cert validation"; - s_logger.error(msg,e); - throw new CloudRuntimeException(msg); - } else { - String msg = "Cannot upload custom certificate, internal error."; - s_logger.error(msg,e); - throw new CloudRuntimeException(msg); - } - - }finally{ - _certDao.releaseFromLockTable(cert.getId()); - } + } else if (e instanceof IndexOutOfBoundsException) { + String msg = "Custom certificate record in the db deleted; this should never happen. Please create a new record in the certificate table"; + s_logger.error(msg, e); + throw new CloudRuntimeException(msg); + } else if (e instanceof FileNotFoundException) { + String msg = "Invalid file path for custom cert found during cert validation"; + s_logger.error(msg, e); + throw new InvalidParameterValueException(msg); + } else if (e instanceof CertificateException) { + String msg = "The file format for custom cert does not conform to the X.509 specification"; + s_logger.error(msg, e); + throw new CloudRuntimeException(msg); + } else if (e instanceof UnsupportedEncodingException) { + String msg = "Unable to encode the certificate into UTF-8 input stream for validation"; + s_logger.error(msg, e); + throw new CloudRuntimeException(msg); + } else if (e instanceof IOException) { + String msg = "Cannot generate input stream during custom cert validation"; + s_logger.error(msg, e); + throw new CloudRuntimeException(msg); + } else { + String msg = "Cannot upload custom certificate, internal error."; + s_logger.error(msg, e); + throw new CloudRuntimeException(msg); + } + + } finally { + _certDao.releaseFromLockTable(cert.getId()); + } } @Override public String[] getHypervisors(ListHypervisorsCmd cmd) { Long zoneId = cmd.getZoneId(); - if(zoneId == null) { + if (zoneId == null) { String hypers = _configDao.getValue(Config.HypervisorList.key()); if (hypers == "" || hypers == null) { return null; @@ -4752,9 +4715,9 @@ public class ManagementServerImpl implements ManagementServer { } else { int i = 0; List clustersForZone = _clusterDao.listByZoneId(zoneId); - if(clustersForZone != null && clustersForZone.size() > 0) { + if (clustersForZone != null && clustersForZone.size() > 0) { String[] result = new String[clustersForZone.size()]; - for(ClusterVO cluster : clustersForZone) { + for (ClusterVO cluster : clustersForZone) { result[i++] = cluster.getHypervisorType().toString(); } return result; @@ -4763,24 +4726,24 @@ public class ManagementServerImpl implements ManagementServer { return null; } - @Override - public String getHashKey() { - // although we may have race conditioning here, database transaction serialization should - // give us the same key - if(_hashKey == null) { - _hashKey = _configDao.getValueAndInitIfNotExist(Config.HashKey.key(), UUID.randomUUID().toString()); - } - return _hashKey; - } - + @Override + public String getHashKey() { + // although we may have race conditioning here, database transaction serialization should + // give us the same key + if (_hashKey == null) { + _hashKey = _configDao.getValueAndInitIfNotExist(Config.HashKey.key(), UUID.randomUUID().toString()); + } + return _hashKey; + } + @Override public SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd) { Account caller = UserContext.current().getCaller(); String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); - + Account owner = _accountMgr.finalizeOwner(caller, accountName, domainId); - + SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s != null) { throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists."); @@ -4801,14 +4764,14 @@ public class ManagementServerImpl implements ManagementServer { Account caller = UserContext.current().getCaller(); String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); - Account owner = null; + Account owner = null; _accountMgr.finalizeOwner(caller, accountName, domainId); SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s == null) { throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in domain id=" + owner.getDomainId()); } - + return _sshKeyPairDao.deleteByName(caller.getAccountId(), caller.getDomainId(), cmd.getName()); } @@ -4820,7 +4783,7 @@ public class ManagementServerImpl implements ManagementServer { Long accountId = null; Long domainId = null; String path = null; - + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { accountId = caller.getId(); domainId = caller.getDomainId(); @@ -4828,40 +4791,40 @@ public class ManagementServerImpl implements ManagementServer { DomainVO domain = _domainDao.findById(caller.getDomainId()); path = domain.getPath(); } - + SearchBuilder sb = _sshKeyPairDao.createSearchBuilder(); Filter searchFilter = new Filter(SSHKeyPairVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - + if (path != null) { - //for domain admin we should show only subdomains information + // for domain admin we should show only subdomains information SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + SearchCriteria sc = sb.create(); - + if (name != null) { sc.addAnd("name", SearchCriteria.Op.EQ, name); } - + if (accountId != null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } - + if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } - + if (fingerPrint != null) { sc.addAnd("fingerprint", SearchCriteria.Op.EQ, fingerPrint); } - + if (path != null) { sc.setJoinParameters("domainSearch", "path", path + "%"); } - - return _sshKeyPairDao.search(sc, searchFilter); + + return _sshKeyPairDao.search(sc, searchFilter); } @Override @@ -4882,7 +4845,7 @@ public class ManagementServerImpl implements ManagementServer { return createAndSaveSSHKeyPair(name, fingerprint, publicKey, null); } - + private SSHKeyPair createAndSaveSSHKeyPair(String name, String fingerprint, String publicKey, String privateKey) { Account account = UserContext.current().getCaller(); SSHKeyPairVO newPair = new SSHKeyPairVO(); @@ -4900,19 +4863,19 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public String getVMPassword(GetVMPasswordCmd cmd) { + public String getVMPassword(GetVMPasswordCmd cmd) { Account caller = UserContext.current().getCaller(); - + UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { throw new InvalidParameterValueException("No VM with id '" + cmd.getId() + "' found."); } - - //make permission check + + // make permission check _accountMgr.checkAccess(caller, vm); - + _userVmDao.loadDetails(vm); - String password = vm.getDetail("Encrypted.Password"); + String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { throw new InvalidParameterValueException("No password for VM with id '" + cmd.getId() + "' found."); } diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index de1511f0dec..52ed19813a2 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -1215,7 +1215,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override @DB - public boolean deletePool(DeletePoolCmd command) throws InvalidParameterValueException { + public boolean deletePool(DeletePoolCmd command) { Long id = command.getId(); boolean deleteFlag = false; @@ -2375,7 +2375,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag return true; } - private boolean validateVolumeSizeRange(long size) throws InvalidParameterValueException { + private boolean validateVolumeSizeRange(long size) { if (size < 0 || (size > 0 && size < 1)) { throw new InvalidParameterValueException("Please specify a size of at least 1 Gb."); } else if (size > _maxVolumeSizeInGb) { diff --git a/server/src/com/cloud/storage/download/DownloadMonitor.java b/server/src/com/cloud/storage/download/DownloadMonitor.java index 739685e9722..dd5dbe67094 100644 --- a/server/src/com/cloud/storage/download/DownloadMonitor.java +++ b/server/src/com/cloud/storage/download/DownloadMonitor.java @@ -21,7 +21,6 @@ package com.cloud.storage.download; import java.util.List; import java.util.Map; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.HostVO; import com.cloud.storage.VMTemplateVO; @@ -42,7 +41,7 @@ public interface DownloadMonitor extends Manager{ public void handleTemplateSync(long id, Map templateInfo); public void copyTemplate(VMTemplateVO template, HostVO sourceServer, HostVO destServer) - throws InvalidParameterValueException, StorageUnavailableException; + throws StorageUnavailableException; /*When new host added, take a look at if there are templates needed to be downloaded for the same hypervisor as the host*/ void handleSysTemplateDownload(HostVO hostId); diff --git a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java index 95750f0458b..32d89868aaf 100755 --- a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java +++ b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java @@ -176,7 +176,7 @@ public class DownloadMonitorImpl implements DownloadMonitor { } @Override - public void copyTemplate(VMTemplateVO template, HostVO sourceServer, HostVO destServer) throws InvalidParameterValueException, StorageUnavailableException{ + public void copyTemplate(VMTemplateVO template, HostVO sourceServer, HostVO destServer) throws StorageUnavailableException{ boolean downloadJobExists = false; VMTemplateHostVO destTmpltHost = null; diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 91f092def1b..42f03943ea7 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -324,7 +324,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Account owner = _accountMgr.getAccount(v.getAccountId()); SnapshotVO snapshot = null; boolean backedUp = false; - //does the caller have the authority to act on this volume + // does the caller have the authority to act on this volume checkAccountPermissions(v.getAccountId(), v.getDomainId(), "volume", volumeId); try { if (v != null && _volsDao.getHypervisorType(v.getId()).equals(HypervisorType.KVM)) { @@ -361,7 +361,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (userVm != null) { if (userVm.getState().equals(State.Destroyed) || userVm.getState().equals(State.Expunging)) { _snapshotDao.expunge(snapshotId); - throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volumeId + " is associated with vm:" + userVm.getInstanceName() + " is in " + userVm.getState().toString() + " state"); + throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volumeId + " is associated with vm:" + userVm.getInstanceName() + " is in " + + userVm.getState().toString() + " state"); } } } @@ -382,7 +383,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (snapshot.getStatus() == Snapshot.Status.CreatedOnPrimary) { backedUp = backupSnapshotToSecondaryStorage(snapshot); } else if (snapshot.getStatus() == Snapshot.Status.BackedUp) { - //For empty snapshot we set status to BackedUp in createSnapshotOnPrimary + // For empty snapshot we set status to BackedUp in createSnapshotOnPrimary backedUp = true; } if (!backedUp) { @@ -397,7 +398,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma postCreateSnapshot(volumeId, snapshot.getId(), policyId, backedUp); _volsDao.releaseFromLockTable(volumeId); if (backedUp) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, v.getSize()); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, + v.getSize()); _usageEventDao.persist(usageEvent); } } else if (snapshot == null || !backedUp) { @@ -487,7 +489,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma long prevSnapshotId = snapshot.getPrevSnapshotId(); if (prevSnapshotId > 0) { prevSnapshot = _snapshotDao.findByIdIncludingRemoved(prevSnapshotId); - if (prevSnapshot.getVersion() != null && prevSnapshot.getVersion().equals("2.2") ) { + if (prevSnapshot.getVersion() != null && prevSnapshot.getVersion().equals("2.2")) { prevBackupUuid = prevSnapshot.getBackupSnapshotId(); if (prevBackupUuid != null) { prevSnapshotUuid = prevSnapshot.getPath(); @@ -497,8 +499,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma boolean isVolumeInactive = _storageMgr.volumeInactive(volume); String vmName = _storageMgr.getVmNameOnVolume(volume); - BackupSnapshotCommand backupSnapshotCommand = new BackupSnapshotCommand(primaryStoragePoolNameLabel, secondaryStoragePoolUrl, dcId, accountId, volumeId, volume.getPath(), snapshotUuid, snapshot.getName(), prevSnapshotUuid, prevBackupUuid, - isVolumeInactive, vmName); + BackupSnapshotCommand backupSnapshotCommand = new BackupSnapshotCommand(primaryStoragePoolNameLabel, secondaryStoragePoolUrl, dcId, accountId, volumeId, volume.getPath(), snapshotUuid, + snapshot.getName(), prevSnapshotUuid, prevBackupUuid, isVolumeInactive, vmName); String backedUpSnapshotUuid = null; // By default, assume failed. @@ -590,16 +592,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Account account = UserContext.current().getCaller(); if (account != null) { - - /*if (!isAdmin(account.getType())) { - if (account.getId() != targetAccountId) { - throw new InvalidParameterValueException("Unable to find a " + targetDesc + " with id " + targetId + " for this account"); - } - } else if (!_domainDao.isChildDomain(account.getDomainId(), targetDomainId)) { - throw new PermissionDeniedException("Unable to perform operation for " + targetDesc + " with id " + targetId + ", permission denied."); - } - accountId = account.getId();*/ - _accountMgr.checkAccess(account, _domainDao.findById(targetDomainId)); + + /* + * if (!isAdmin(account.getType())) { if (account.getId() != targetAccountId) { throw new + * InvalidParameterValueException("Unable to find a " + targetDesc + " with id " + targetId + " for this account"); + * } } else if (!_domainDao.isChildDomain(account.getDomainId(), targetDomainId)) { throw new + * PermissionDeniedException("Unable to perform operation for " + targetDesc + " with id " + targetId + + * ", permission denied."); } accountId = account.getId(); + */ + _accountMgr.checkAccess(account, _domainDao.findById(targetDomainId)); } return accountId; @@ -636,7 +637,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma return status; } - + @DB private boolean deleteSnapshotInternal(Long snapshotId) { if (s_logger.isDebugEnabled()) { @@ -651,7 +652,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _snapshotDao.update(snapshot.getId(), snapshot); } } - + Transaction txn = Transaction.currentTxn(); txn.start(); _snapshotDao.remove(snapshotId); @@ -659,7 +660,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _usageEventDao.persist(usageEvent); _accountMgr.decrementResourceCount(snapshot.getAccountId(), ResourceType.snapshot); txn.commit(); - + long lastId = snapshotId; boolean destroy = false; while (true) { @@ -754,7 +755,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } @Override - public List listSnapshots(ListSnapshotsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List listSnapshots(ListSnapshotsCmd cmd) { Long volumeId = cmd.getVolumeId(); Boolean isRecursive = cmd.isRecursive(); @@ -937,7 +938,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } // Log event after successful deletion - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), volume.getDataCenterId(), snapshot.getId(), snapshot.getName(), null, null, volume.getSize()); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), volume.getDataCenterId(), snapshot.getId(), snapshot.getName(), null, null, + volume.getSize()); _usageEventDao.persist(usageEvent); } } @@ -949,7 +951,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma @Override @DB - public SnapshotPolicyVO createPolicy(CreateSnapshotPolicyCmd cmd) throws InvalidParameterValueException { + public SnapshotPolicyVO createPolicy(CreateSnapshotPolicyCmd cmd) { Long volumeId = cmd.getVolumeId(); VolumeVO volume = _volsDao.findById(cmd.getVolumeId()); if (volume == null) { @@ -1014,7 +1016,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma policy = _snapshotPolicyDao.acquireInLockTable(policy.getId()); policy.setSchedule(cmd.getSchedule()); policy.setTimezone(timezoneId); - policy.setInterval((short)intvType.ordinal()); + policy.setInterval((short) intvType.ordinal()); policy.setMaxSnaps(cmd.getMaxSnaps()); policy.setActive(true); _snapshotPolicyDao.update(policy.getId(), policy); @@ -1036,7 +1038,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } @Override - public List listPoliciesforVolume(ListSnapshotPoliciesCmd cmd) throws InvalidParameterValueException { + public List listPoliciesforVolume(ListSnapshotPoliciesCmd cmd) { Long volumeId = cmd.getVolumeId(); VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { @@ -1093,7 +1095,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma * {@inheritDoc} */ @Override - public List findRecurringSnapshotSchedule(ListRecurringSnapshotScheduleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List findRecurringSnapshotSchedule(ListRecurringSnapshotScheduleCmd cmd) { Long volumeId = cmd.getVolumeId(); Long policyId = cmd.getSnapshotPolicyId(); Account account = UserContext.current().getCaller(); @@ -1196,8 +1198,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma // user Type snapshotType = getSnapshotType(policyId); HypervisorType hypervisorType = this._volsDao.getHypervisorType(volumeId); - SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), null, snapshotName, (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), - hypervisorType); + SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), null, snapshotName, + (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), hypervisorType); SnapshotVO snapshot = _snapshotDao.persist(snapshotVO); if (snapshot != null) { diff --git a/server/src/com/cloud/template/TemplateManager.java b/server/src/com/cloud/template/TemplateManager.java index 27fd46e4e1e..742c510a1ff 100755 --- a/server/src/com/cloud/template/TemplateManager.java +++ b/server/src/com/cloud/template/TemplateManager.java @@ -21,7 +21,6 @@ import java.net.URI; import java.util.List; import com.cloud.exception.InternalErrorException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.StorageUnavailableException; import com.cloud.storage.Storage.ImageFormat; @@ -33,107 +32,115 @@ import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.storage.VMTemplateVO; /** - * TemplateManager manages the templates stored - * on secondary storage. It is responsible for - * creating private/public templates. It is - * also responsible for downloading. + * TemplateManager manages the templates stored on secondary storage. It is responsible for creating private/public templates. + * It is also responsible for downloading. */ public interface TemplateManager { - + /** * Creates a Template * - * @param zoneId zone to create the template in - * @param displayText user readable name. - * @param isPublic is this a public template? - * @param featured is this template featured? - * @param isExtractable is this template extractable? - * @param format which image format is the template. - * @param fs what is the file system on the template - * @param url url to download the template from. - * @param chksum chksum to compare it to. - * @param requiresHvm does this template require hvm? - * @param bits is the os contained on the template 32 bit? - * @param enablePassword Does the template support password change. - * @param guestOSId OS that is on the template - * @param bootable true if this template will represent a bootable ISO + * @param zoneId + * zone to create the template in + * @param displayText + * user readable name. + * @param isPublic + * is this a public template? + * @param featured + * is this template featured? + * @param isExtractable + * is this template extractable? + * @param format + * which image format is the template. + * @param fs + * what is the file system on the template + * @param url + * url to download the template from. + * @param chksum + * chksum to compare it to. + * @param requiresHvm + * does this template require hvm? + * @param bits + * is the os contained on the template 32 bit? + * @param enablePassword + * Does the template support password change. + * @param guestOSId + * OS that is on the template + * @param bootable + * true if this template will represent a bootable ISO * @return id of the template created. */ - Long createInZone(long zoneId, long userId, String displayText, boolean isPublic, boolean featured, boolean isExtractable, ImageFormat format, TemplateType type, URI url, String chksum, boolean requiresHvm, int bits, boolean enablePassword, long guestOSId, boolean bootable); - + Long createInZone(long zoneId, long userId, String displayText, boolean isPublic, boolean featured, boolean isExtractable, ImageFormat format, TemplateType type, URI url, String chksum, + boolean requiresHvm, int bits, boolean enablePassword, long guestOSId, boolean bootable); + /** * Prepares a template for vm creation for a certain storage pool. * - * @param template template to prepare - * @param pool pool to make sure the template is ready in. + * @param template + * template to prepare + * @param pool + * pool to make sure the template is ready in. * @return VMTemplateStoragePoolVO if preparation is complete; null if not. */ VMTemplateStoragePoolVO prepareTemplateForCreate(VMTemplateVO template, StoragePool pool); - + boolean resetTemplateDownloadStateOnPool(long templateStoragePoolRefId); - + /** * Copies a template from its current secondary storage server to the secondary storage server in the specified zone. + * * @param templateId * @param sourceZoneId * @param destZoneId * @return true if success - * @throws InternalErrorException URI uri = new URI(url); - if ( (uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp") )) { - throw new IllegalArgumentException("Unsupported scheme for url: " + url); - } - 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); - } - - if (_dcDao.findById(zoneId) == null) { - throw new IllegalArgumentException("Please specify a valid zone."); - } - - VMTemplateVO template = findTemplateById(templateId); - - VMTemplateHostVO tmpltHostRef = findTemplateHostRef(templateId, zoneId); - if (tmpltHostRef != null && tmpltHostRef.getDownloadState() != com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED){ - throw new IllegalArgumentException("The template hasnt been downloaded "); - } - * @throws StorageUnavailableException - * @throws ResourceAllocationException - * @throws InvalidParameterValueException + * @throws InternalErrorException + * URI uri = new URI(url); if ( (uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp") )) { + * throw new IllegalArgumentException("Unsupported scheme for url: " + url); } 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); } + * + * if (_dcDao.findById(zoneId) == null) { throw new IllegalArgumentException("Please specify a valid zone."); } + * + * VMTemplateVO template = findTemplateById(templateId); + * + * VMTemplateHostVO tmpltHostRef = findTemplateHostRef(templateId, zoneId); if (tmpltHostRef != null && + * tmpltHostRef.getDownloadState() != com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED){ throw + * new IllegalArgumentException("The template hasnt been downloaded "); } + * @throws StorageUnavailableException + * @throws ResourceAllocationException */ boolean copy(long userId, long templateId, long sourceZoneId, long destZoneId) throws StorageUnavailableException, ResourceAllocationException; - + /** * Deletes a template from secondary storage servers + * * @param userId * @param templateId - * @param zoneId - optional. If specified, will only delete the template from the specified zone's secondary storage server. + * @param zoneId + * - optional. If specified, will only delete the template from the specified zone's secondary storage server. * @return true if success */ boolean delete(long userId, long templateId, Long zoneId); - + /** * Lists templates in the specified storage pool that are not being used by any VM. + * * @param pool * @return list of VMTemplateStoragePoolVO */ List getUnusedTemplatesInPool(StoragePoolVO pool); - + /** * Deletes a template in the specified storage pool. + * * @param templatePoolVO */ void evictTemplateFromStoragePool(VMTemplateStoragePoolVO templatePoolVO); - + boolean templateIsDeleteable(VMTemplateHostVO templateHostRef); - + } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 7a6275ca790..a0154d08648 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -496,7 +496,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @Override - public List searchForLimits(ListResourceLimitsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List searchForLimits(ListResourceLimitsCmd cmd) { String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); Long accountId = null; @@ -1230,7 +1230,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_USER_UPDATE, eventDescription = "updating User") - public UserAccount updateUser(UpdateUserCmd cmd) throws InvalidParameterValueException { + public UserAccount updateUser(UpdateUserCmd cmd) { Long id = cmd.getId(); String apiKey = cmd.getApiKey(); String firstName = cmd.getFirstname(); @@ -1316,7 +1316,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_USER_DISABLE, eventDescription = "disabling User", async = true) - public UserAccount disableUser(DisableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public UserAccount disableUser(DisableUserCmd cmd) { Long userId = cmd.getId(); Account adminAccount = UserContext.current().getCaller(); @@ -1347,7 +1347,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_USER_ENABLE, eventDescription = "enabling User") - public UserAccount enableUser(EnableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public UserAccount enableUser(EnableUserCmd cmd) { Long userId = cmd.getId(); Account adminAccount = UserContext.current().getCaller(); boolean success = false; @@ -1469,7 +1469,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @Override - public AccountVO enableAccount(EnableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public AccountVO enableAccount(EnableAccountCmd cmd) { String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); boolean success = false; @@ -1530,7 +1530,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "disabling account", async = true) - public AccountVO disableAccount(DisableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, ResourceUnavailableException { + public AccountVO disableAccount(DisableAccountCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException { String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); @@ -1551,7 +1551,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @Override - public AccountVO updateAccount(UpdateAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public AccountVO updateAccount(UpdateAccountCmd cmd) { Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); String newAccountName = cmd.getNewName(); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index adabfb8dcd5..1efc61879db 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -200,74 +200,129 @@ import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDetailsDao; -@Local(value={UserVmManager.class, UserVmService.class}) +@Local(value = { UserVmManager.class, UserVmService.class }) public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager { private static final Logger s_logger = Logger.getLogger(UserVmManagerImpl.class); - private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds + private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds + + @Inject + protected HostDao _hostDao = null; + @Inject + protected DetailsDao _detailsDao = null; + @Inject + protected DomainRouterDao _routerDao = null; + @Inject + protected ServiceOfferingDao _offeringDao = null; + @Inject + protected DiskOfferingDao _diskOfferingDao = null; + @Inject + protected UserStatisticsDao _userStatsDao = null; + @Inject + protected VMTemplateDao _templateDao = null; + @Inject + protected VMTemplateHostDao _templateHostDao = null; + @Inject + protected VMTemplateZoneDao _templateZoneDao = null; + @Inject + protected DomainDao _domainDao = null; + @Inject + protected ResourceLimitDao _limitDao = null; + @Inject + protected UserVmDao _vmDao = null; + @Inject + protected VolumeDao _volsDao = null; + @Inject + protected DataCenterDao _dcDao = null; + @Inject + protected FirewallRulesDao _rulesDao = null; + @Inject + protected LoadBalancerVMMapDao _loadBalancerVMMapDao = null; + @Inject + protected LoadBalancerDao _loadBalancerDao = null; + @Inject + protected IPAddressDao _ipAddressDao = null; + @Inject + protected HostPodDao _podDao = null; + @Inject + protected CapacityDao _capacityDao = null; + @Inject + protected NetworkManager _networkMgr = null; + @Inject + protected StorageManager _storageMgr = null; + @Inject + protected SnapshotManager _snapshotMgr = null; + @Inject + protected AgentManager _agentMgr = null; + @Inject + protected ConfigurationManager _configMgr = null; + @Inject + protected AccountDao _accountDao = null; + @Inject + protected UserDao _userDao = null; + @Inject + protected SnapshotDao _snapshotDao = null; + @Inject + protected GuestOSDao _guestOSDao = null; + @Inject + protected GuestOSCategoryDao _guestOSCategoryDao = null; + @Inject + protected HighAvailabilityManager _haMgr = null; + @Inject + protected AlertManager _alertMgr = null; + @Inject + protected AccountManager _accountMgr; + @Inject + protected AccountService _accountService; + @Inject + protected AsyncJobManager _asyncMgr; + @Inject + protected VlanDao _vlanDao; + @Inject + protected ClusterDao _clusterDao; + @Inject + protected AccountVlanMapDao _accountVlanMapDao; + @Inject + protected StoragePoolDao _storagePoolDao; + @Inject + protected VMTemplateHostDao _vmTemplateHostDao; + @Inject + protected SecurityGroupManager _networkGroupMgr; + @Inject + protected ServiceOfferingDao _serviceOfferingDao; + @Inject + protected NetworkOfferingDao _networkOfferingDao; + @Inject + protected EventDao _eventDao = null; + @Inject + protected InstanceGroupDao _vmGroupDao; + @Inject + protected InstanceGroupVMMapDao _groupVMMapDao; + @Inject + protected VirtualMachineManager _itMgr; + @Inject + protected NetworkDao _networkDao; + @Inject + protected VirtualNetworkApplianceManager _routerMgr; + @Inject + protected NicDao _nicDao; + @Inject + protected RulesManager _rulesMgr; + @Inject + protected LoadBalancingRulesManager _lbMgr; + @Inject + protected UsageEventDao _usageEventDao; + @Inject + protected SSHKeyPairDao _sshKeyPairDao; + @Inject + protected UserVmDetailsDao _vmDetailsDao; - @Inject protected HostDao _hostDao = null; - @Inject protected DetailsDao _detailsDao = null; - @Inject protected DomainRouterDao _routerDao = null; - @Inject protected ServiceOfferingDao _offeringDao = null; - @Inject protected DiskOfferingDao _diskOfferingDao = null; - @Inject protected UserStatisticsDao _userStatsDao = null; - @Inject protected VMTemplateDao _templateDao = null; - @Inject protected VMTemplateHostDao _templateHostDao = null; - @Inject protected VMTemplateZoneDao _templateZoneDao = null; - @Inject protected DomainDao _domainDao = null; - @Inject protected ResourceLimitDao _limitDao = null; - @Inject protected UserVmDao _vmDao = null; - @Inject protected VolumeDao _volsDao = null; - @Inject protected DataCenterDao _dcDao = null; - @Inject protected FirewallRulesDao _rulesDao = null; - @Inject protected LoadBalancerVMMapDao _loadBalancerVMMapDao = null; - @Inject protected LoadBalancerDao _loadBalancerDao = null; - @Inject protected IPAddressDao _ipAddressDao = null; - @Inject protected HostPodDao _podDao = null; - @Inject protected CapacityDao _capacityDao = null; - @Inject protected NetworkManager _networkMgr = null; - @Inject protected StorageManager _storageMgr = null; - @Inject protected SnapshotManager _snapshotMgr = null; - @Inject protected AgentManager _agentMgr = null; - @Inject protected ConfigurationManager _configMgr = null; - @Inject protected AccountDao _accountDao = null; - @Inject protected UserDao _userDao = null; - @Inject protected SnapshotDao _snapshotDao = null; - @Inject protected GuestOSDao _guestOSDao = null; - @Inject protected GuestOSCategoryDao _guestOSCategoryDao = null; - @Inject protected HighAvailabilityManager _haMgr = null; - @Inject protected AlertManager _alertMgr = null; - @Inject protected AccountManager _accountMgr; - @Inject protected AccountService _accountService; - @Inject protected AsyncJobManager _asyncMgr; - @Inject protected VlanDao _vlanDao; - @Inject protected ClusterDao _clusterDao; - @Inject protected AccountVlanMapDao _accountVlanMapDao; - @Inject protected StoragePoolDao _storagePoolDao; - @Inject protected VMTemplateHostDao _vmTemplateHostDao; - @Inject protected SecurityGroupManager _networkGroupMgr; - @Inject protected ServiceOfferingDao _serviceOfferingDao; - @Inject protected NetworkOfferingDao _networkOfferingDao; - @Inject protected EventDao _eventDao = null; - @Inject protected InstanceGroupDao _vmGroupDao; - @Inject protected InstanceGroupVMMapDao _groupVMMapDao; - @Inject protected VirtualMachineManager _itMgr; - @Inject protected NetworkDao _networkDao; - @Inject protected VirtualNetworkApplianceManager _routerMgr; - @Inject protected NicDao _nicDao; - @Inject protected RulesManager _rulesMgr; - @Inject protected LoadBalancingRulesManager _lbMgr; - @Inject protected UsageEventDao _usageEventDao; - @Inject protected SSHKeyPairDao _sshKeyPairDao; - @Inject protected UserVmDetailsDao _vmDetailsDao; - protected ScheduledExecutorService _executor = null; protected int _expungeInterval; protected int _expungeDelay; protected String _name; protected String _instance; - protected String _zone; + protected String _zone; private ConfigurationDao _configDao; @@ -281,40 +336,41 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return _vmDao.listByHostId(hostId); } - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_RESETPASSWORD, eventDescription="resetting Vm password", async=true) - public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException{ + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_RESETPASSWORD, eventDescription = "resetting Vm password", async = true) + public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException { Account account = UserContext.current().getCaller(); - Long userId = UserContext.current().getCallerUserId(); - Long vmId = cmd.getId(); - UserVmVO userVm = _vmDao.findById(cmd.getId()); - - //Do parameters input validation - if (userVm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + cmd.getId()); - } - - VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId()); - if (template == null || !template.getEnablePassword()) { - throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled"); - } - + Long userId = UserContext.current().getCallerUserId(); + Long vmId = cmd.getId(); + UserVmVO userVm = _vmDao.findById(cmd.getId()); + + // Do parameters input validation + if (userVm == null) { + throw new InvalidParameterValueException("unable to find a virtual machine with id " + cmd.getId()); + } + + VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId()); + if (template == null || !template.getEnablePassword()) { + throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled"); + } + if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) { s_logger.error("vm is not in the right state: " + vmId); throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state"); } - - userId = accountAndUserValidation(vmId, account, userId, userVm); - - boolean result = resetVMPasswordInternal(cmd, password); - + + userId = accountAndUserValidation(vmId, account, userId, userVm); + + boolean result = resetVMPasswordInternal(cmd, password); + if (result) { userVm.setPassword(password); } - + return userVm; } - private boolean resetVMPasswordInternal(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException{ + private boolean resetVMPasswordInternal(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException { Long vmId = cmd.getId(); Long userId = UserContext.current().getCallerUserId(); VMInstanceVO vmInstance = _vmDao.findById(vmId); @@ -330,22 +386,21 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.error("Unable to reset password for vm " + vmInstance + " as the instance doesn't have default nic"); return false; } - + Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId()); NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null); VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance); vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password); - List elements = _networkMgr.getPasswordResetElements(); - + boolean result = true; for (PasswordResetElement element : elements) { if (!element.savePassword(defaultNetwork, defaultNicProfile, vmProfile)) { result = false; } } - + // Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM if (!result) { s_logger.debug("Failed to reset password for the virutal machine; no need to reboot the vm"); @@ -364,54 +419,54 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } } else { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Reset password called for a vm that is not using a password enabled template"); - } - return false; + if (s_logger.isDebugEnabled()) { + s_logger.debug("Reset password called for a vm that is not using a password enabled template"); + } + return false; } } - + @Override public boolean stopVirtualMachine(long userId, long vmId) { boolean status = false; if (s_logger.isDebugEnabled()) { s_logger.debug("Stopping vm=" + vmId); } - UserVmVO vm = _vmDao.findById(vmId); + UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is either removed or deleted."); - } + } return true; } User user = _userDao.findById(userId); Account account = _accountDao.findById(user.getAccountId()); - + try { status = _itMgr.stop(vm, user, account); } catch (ResourceUnavailableException e) { s_logger.debug("Unable to stop due to ", e); status = false; } - - if(status){ + + if (status) { return status; - } - else { + } else { return status; } } - - @Override @ActionEvent(eventType = EventTypes.EVENT_VOLUME_ATTACH, eventDescription = "attaching volume", async=true) + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_ATTACH, eventDescription = "attaching volume", async = true) public Volume attachVolumeToVM(AttachVolumeCmd command) { - Long vmId = command.getVirtualMachineId(); - Long volumeId = command.getId(); - Long deviceId = command.getDeviceId(); - Account account = UserContext.current().getCaller(); - - // Check that the volume ID is valid - VolumeVO volume = _volsDao.findById(volumeId); + Long vmId = command.getVirtualMachineId(); + Long volumeId = command.getId(); + Long deviceId = command.getDeviceId(); + Account account = UserContext.current().getCaller(); + + // Check that the volume ID is valid + VolumeVO volume = _volsDao.findById(volumeId); // Check that the volume is a data volume if (volume == null || volume.getVolumeType() != Volume.Type.DATADISK) { throw new InvalidParameterValueException("Please specify a valid data volume."); @@ -421,7 +476,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (!Volume.State.Allocated.equals(volume.getState()) && !_storageMgr.volumeOnSharedStoragePool(volume)) { throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); } - + // Check that the volume is not currently attached to any VM if (volume.getInstanceId() != null) { throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); @@ -432,257 +487,252 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Please specify a volume that is not destroyed."); } - // Check that the virtual machine ID is valid and it's a user vm - UserVmVO vm = _vmDao.findById(vmId); - if (vm == null || vm.getType() != VirtualMachine.Type.User) { + // Check that the virtual machine ID is valid and it's a user vm + UserVmVO vm = _vmDao.findById(vmId); + if (vm == null || vm.getType() != VirtualMachine.Type.User) { throw new InvalidParameterValueException("Please specify a valid User VM."); } - + // Check that the VM is in the correct state if (vm.getState() != State.Running && vm.getState() != State.Stopped) { - throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); + throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); } // Check that the device ID is valid - if( deviceId != null ) { - if(deviceId.longValue() == 0) { - throw new InvalidParameterValueException ("deviceId can't be 0, which is used by Root device"); + if (deviceId != null) { + if (deviceId.longValue() == 0) { + throw new InvalidParameterValueException("deviceId can't be 0, which is used by Root device"); } } - + // Check that the VM has less than 6 data volumes attached List existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK); if (existingDataVolumes.size() >= 6) { throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (6). Please specify another VM."); } - + // Check that the VM and the volume are in the same zone if (vm.getDataCenterId() != volume.getDataCenterId()) { - throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume."); + throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume."); } - - //Verify account information - if (volume.getAccountId() != vm.getAccountId()) { - throw new PermissionDeniedException ("Virtual machine and volume belong to different accounts, can not attach. Permission denied."); - } - - // If the account is not an admin, check that the volume and the virtual machine are owned by the account that was passed in - _accountMgr.checkAccess(account, volume); - /*if (account != null) { - if (!isAdmin(account.getType())) { - if (account.getId() != volume.getAccountId()) { - throw new PermissionDeniedException("Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName() + ". Permission denied."); - } - if (account.getId() != vm.getAccountId()) { - throw new PermissionDeniedException("Unable to find VM with ID: " + vmId + " for account: " + account.getAccountName() + ". Permission denied"); - } - } else { - if (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId()) || - !_domainDao.isChildDomain(account.getDomainId(), vm.getDomainId())) { - throw new PermissionDeniedException("Unable to attach volume " + volumeId + " to virtual machine instance " + vmId + ". Permission denied."); - } - } - }*/ + // Verify account information + if (volume.getAccountId() != vm.getAccountId()) { + throw new PermissionDeniedException("Virtual machine and volume belong to different accounts, can not attach. Permission denied."); + } + + // If the account is not an admin, check that the volume and the virtual machine are owned by the account that was + // passed in + _accountMgr.checkAccess(account, volume); + /* + * if (account != null) { if (!isAdmin(account.getType())) { if (account.getId() != volume.getAccountId()) { throw new + * PermissionDeniedException("Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName() + * + ". Permission denied."); } + * + * if (account.getId() != vm.getAccountId()) { throw new PermissionDeniedException("Unable to find VM with ID: " + vmId + * + " for account: " + account.getAccountName() + ". Permission denied"); } } else { if + * (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId()) || + * !_domainDao.isChildDomain(account.getDomainId(), vm.getDomainId())) { throw new + * PermissionDeniedException("Unable to attach volume " + volumeId + " to virtual machine instance " + vmId + + * ". Permission denied."); } } } + */ VolumeVO rootVolumeOfVm = null; List rootVolumesOfVm = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT); if (rootVolumesOfVm.size() != 1) { - throw new CloudRuntimeException("The VM " + vm.getName() + " has more than one ROOT volume and is in an invalid state. Please contact Cloud Support."); + throw new CloudRuntimeException("The VM " + vm.getName() + " has more than one ROOT volume and is in an invalid state. Please contact Cloud Support."); } else { - rootVolumeOfVm = rootVolumesOfVm.get(0); + rootVolumeOfVm = rootVolumesOfVm.get(0); } - + HypervisorType rootDiskHyperType = _volsDao.getHypervisorType(rootVolumeOfVm.getId()); - + if (volume.getState().equals(Volume.State.Allocated)) { - /*Need to create the volume*/ - VMTemplateVO rootDiskTmplt = _templateDao.findById(vm.getTemplateId()); - DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterId()); - HostPodVO pod = _podDao.findById(vm.getPodId()); - StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); - ServiceOfferingVO svo = _serviceOfferingDao.findById(vm.getServiceOfferingId()); - DiskOfferingVO diskVO = _diskOfferingDao.findById(volume.getDiskOfferingId()); - - volume = _storageMgr.createVolume(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); - - if (volume == null) { - throw new CloudRuntimeException("Failed to create volume when attaching it to VM: " + vm.getName()); - } - } - + /* Need to create the volume */ + VMTemplateVO rootDiskTmplt = _templateDao.findById(vm.getTemplateId()); + DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterId()); + HostPodVO pod = _podDao.findById(vm.getPodId()); + StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); + ServiceOfferingVO svo = _serviceOfferingDao.findById(vm.getServiceOfferingId()); + DiskOfferingVO diskVO = _diskOfferingDao.findById(volume.getDiskOfferingId()); + + volume = _storageMgr.createVolume(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); + + if (volume == null) { + throw new CloudRuntimeException("Failed to create volume when attaching it to VM: " + vm.getName()); + } + } + HypervisorType dataDiskHyperType = _volsDao.getHypervisorType(volume.getId()); if (rootDiskHyperType != dataDiskHyperType) { - throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm"); + throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm"); } - + List vols = _volsDao.findByInstance(vmId); - if( deviceId != null ) { - if( deviceId.longValue() > 15 || deviceId.longValue() == 0 || deviceId.longValue() == 3) { + if (deviceId != null) { + if (deviceId.longValue() > 15 || deviceId.longValue() == 0 || deviceId.longValue() == 3) { throw new RuntimeException("deviceId should be 1,2,4-15"); } for (VolumeVO vol : vols) { if (vol.getDeviceId().equals(deviceId)) { throw new RuntimeException("deviceId " + deviceId + " is used by VM " + vm.getName()); } - } + } } else { // allocate deviceId here List devIds = new ArrayList(); - for( int i = 1; i < 15; i++ ) { + for (int i = 1; i < 15; i++) { devIds.add(String.valueOf(i)); } devIds.remove("3"); for (VolumeVO vol : vols) { devIds.remove(vol.getDeviceId().toString().trim()); - } - deviceId = Long.parseLong(devIds.iterator().next()); + } + deviceId = Long.parseLong(devIds.iterator().next()); } - + StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); DiskOfferingVO volumeDiskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); String[] volumeTags = volumeDiskOffering.getTagsArray(); - + StoragePoolVO sourcePool = _storagePoolDao.findById(volume.getPoolId()); List sharedVMPools = _storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), volumeTags, true); boolean moveVolumeNeeded = true; if (sharedVMPools.size() == 0) { - String poolType; - if (vmRootVolumePool.getClusterId() != null) { - poolType = "cluster"; - } else if (vmRootVolumePool.getPodId() != null) { - poolType = "pod"; - } else { - poolType = "zone"; - } - throw new CloudRuntimeException("There are no storage pools in the VM's " + poolType + " with all of the volume's tags (" + volumeDiskOffering.getTags() + ")."); - } else { - Long sourcePoolDcId = sourcePool.getDataCenterId(); - Long sourcePoolPodId = sourcePool.getPodId(); - Long sourcePoolClusterId = sourcePool.getClusterId(); - for (StoragePoolVO vmPool : sharedVMPools) { - Long vmPoolDcId = vmPool.getDataCenterId(); - Long vmPoolPodId = vmPool.getPodId(); - Long vmPoolClusterId = vmPool.getClusterId(); - - if (sourcePoolDcId == vmPoolDcId && sourcePoolPodId == vmPoolPodId && sourcePoolClusterId == vmPoolClusterId) { - moveVolumeNeeded = false; - break; - } - } - } - - if (moveVolumeNeeded) { - // Move the volume to a storage pool in the VM's zone, pod, or cluster - volume = _storageMgr.moveVolume(volume, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), dataDiskHyperType); - } - - AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); - if(asyncExecutor != null) { - AsyncJobVO job = asyncExecutor.getJob(); - - if(s_logger.isInfoEnabled()) { - s_logger.info("Trying to attaching volume " + volumeId +" to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); + String poolType; + if (vmRootVolumePool.getClusterId() != null) { + poolType = "cluster"; + } else if (vmRootVolumePool.getPodId() != null) { + poolType = "pod"; + } else { + poolType = "zone"; + } + throw new CloudRuntimeException("There are no storage pools in the VM's " + poolType + " with all of the volume's tags (" + volumeDiskOffering.getTags() + ")."); + } else { + Long sourcePoolDcId = sourcePool.getDataCenterId(); + Long sourcePoolPodId = sourcePool.getPodId(); + Long sourcePoolClusterId = sourcePool.getClusterId(); + for (StoragePoolVO vmPool : sharedVMPools) { + Long vmPoolDcId = vmPool.getDataCenterId(); + Long vmPoolPodId = vmPool.getPodId(); + Long vmPoolClusterId = vmPool.getClusterId(); + + if (sourcePoolDcId == vmPoolDcId && sourcePoolPodId == vmPoolPodId && sourcePoolClusterId == vmPoolClusterId) { + moveVolumeNeeded = false; + break; + } } - - _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); - _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); } - - String errorMsg = "Failed to attach volume: " + volume.getName() + " to VM: " + vm.getName(); - boolean sendCommand = (vm.getState() == State.Running); - AttachVolumeAnswer answer = null; - Long hostId = vm.getHostId(); - if(hostId == null) { - hostId = vm.getLastHostId(); - HostVO host = _hostDao.findById(hostId); - if(host != null && host.getHypervisorType() == HypervisorType.VMware) { + + if (moveVolumeNeeded) { + // Move the volume to a storage pool in the VM's zone, pod, or cluster + volume = _storageMgr.moveVolume(volume, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), dataDiskHyperType); + } + + AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); + if (asyncExecutor != null) { + AsyncJobVO job = asyncExecutor.getJob(); + + if (s_logger.isInfoEnabled()) { + s_logger.info("Trying to attaching volume " + volumeId + " to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status"); + } + + _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); + _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); + } + + String errorMsg = "Failed to attach volume: " + volume.getName() + " to VM: " + vm.getName(); + boolean sendCommand = (vm.getState() == State.Running); + AttachVolumeAnswer answer = null; + Long hostId = vm.getHostId(); + if (hostId == null) { + hostId = vm.getLastHostId(); + HostVO host = _hostDao.findById(hostId); + if (host != null && host.getHypervisorType() == HypervisorType.VMware) { sendCommand = true; } - } - - if (sendCommand) { - StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); - AttachVolumeCommand cmd = new AttachVolumeCommand(true, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), deviceId, volume.getChainInfo()); - cmd.setPoolUuid(volumePool.getUuid()); - - try { - answer = (AttachVolumeAnswer)_agentMgr.send(hostId, cmd); - } catch (Exception e) { - throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage()); - } - } + } + + if (sendCommand) { + StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); + AttachVolumeCommand cmd = new AttachVolumeCommand(true, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), deviceId, volume.getChainInfo()); + cmd.setPoolUuid(volumePool.getUuid()); + + try { + answer = (AttachVolumeAnswer) _agentMgr.send(hostId, cmd); + } catch (Exception e) { + throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage()); + } + } if (!sendCommand || (answer != null && answer.getResult())) { - // Mark the volume as attached - if( sendCommand ) { + // Mark the volume as attached + if (sendCommand) { _volsDao.attachVolume(volume.getId(), vmId, answer.getDeviceId()); } else { _volsDao.attachVolume(volume.getId(), vmId, deviceId); } return _volsDao.findById(volumeId); - } else { - if (answer != null) { - String details = answer.getDetails(); - if (details != null && !details.isEmpty()) { + } else { + if (answer != null) { + String details = answer.getDetails(); + if (details != null && !details.isEmpty()) { errorMsg += "; " + details; } - } - throw new CloudRuntimeException(errorMsg); - } + } + throw new CloudRuntimeException(errorMsg); + } } - - @Override @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async=true) - public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) { - Account account = UserContext.current().getCaller(); - if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) || - (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) || - (cmmd.getId() == null && (cmmd.getDeviceId()==null || cmmd.getVirtualMachineId() == null))) { - throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)"); - } - Long volumeId = cmmd.getId(); - VolumeVO volume = null; - - if(volumeId != null) { - volume = _volsDao.findById(volumeId); - } else { - volume = _volsDao.findByInstanceAndDeviceId(cmmd.getVirtualMachineId(), cmmd.getDeviceId()).get(0); - } + @Override + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true) + public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) { + Account account = UserContext.current().getCaller(); + if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) || (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) + || (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) { + throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)"); + } - Long vmId = null; - - if (cmmd.getVirtualMachineId() == null) { - vmId = volume.getInstanceId(); - } else { - vmId = cmmd.getVirtualMachineId(); - } + Long volumeId = cmmd.getId(); + VolumeVO volume = null; - boolean isAdmin; - if (account == null) { - // Admin API call - isAdmin = true; - } else { - // User API call - isAdmin = isAdmin(account.getType()); - } + if (volumeId != null) { + volume = _volsDao.findById(volumeId); + } else { + volume = _volsDao.findByInstanceAndDeviceId(cmmd.getVirtualMachineId(), cmmd.getDeviceId()).get(0); + } - // Check that the volume ID is valid - if (volume == null) { + Long vmId = null; + + if (cmmd.getVirtualMachineId() == null) { + vmId = volume.getInstanceId(); + } else { + vmId = cmmd.getVirtualMachineId(); + } + + boolean isAdmin; + if (account == null) { + // Admin API call + isAdmin = true; + } else { + // User API call + isAdmin = isAdmin(account.getType()); + } + + // Check that the volume ID is valid + if (volume == null) { throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId); } - // If the account is not an admin, check that the volume is owned by the account that was passed in - _accountMgr.checkAccess(account, volume); - /*if (!isAdmin) { - if (account.getId() != volume.getAccountId()) { - throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName()); - } - } else if (account != null) { - if (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId())) { - throw new PermissionDeniedException("Unable to detach volume with ID: " + volumeId + ", permission denied."); - } - }*/ + // If the account is not an admin, check that the volume is owned by the account that was passed in + _accountMgr.checkAccess(account, volume); + /* + * if (!isAdmin) { if (account.getId() != volume.getAccountId()) { throw new + * InvalidParameterValueException("Unable to find volume with ID: " + volumeId + " for account: " + + * account.getAccountName()); } } else if (account != null) { if (!_domainDao.isChildDomain(account.getDomainId(), + * volume.getDomainId())) { throw new PermissionDeniedException("Unable to detach volume with ID: " + volumeId + + * ", permission denied."); } } + */ // Check that the volume is a data volume if (volume.getVolumeType() != Volume.Type.DATADISK) { @@ -702,107 +752,106 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Check that the VM is in the correct state UserVmVO vm = _vmDao.findById(vmId); if (vm.getState() != State.Running && vm.getState() != State.Stopped && vm.getState() != State.Destroyed) { - throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); + throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); } - + AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); - if(asyncExecutor != null) { - AsyncJobVO job = asyncExecutor.getJob(); + if (asyncExecutor != null) { + AsyncJobVO job = asyncExecutor.getJob(); - if(s_logger.isInfoEnabled()) { - s_logger.info("Trying to attaching volume " + volumeId +"to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Trying to attaching volume " + volumeId + "to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status"); } - - _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); - _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); + + _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); + _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); } - - String errorMsg = "Failed to detach volume: " + volume.getName() + " from VM: " + vm.getName(); - boolean sendCommand = (vm.getState() == State.Running); - Answer answer = null; - - if (sendCommand) { - AttachVolumeCommand cmd = new AttachVolumeCommand(false, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), - cmmd.getDeviceId() != null ? cmmd.getDeviceId() : volume.getDeviceId(), volume.getChainInfo()); - StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); - cmd.setPoolUuid(volumePool.getUuid()); + String errorMsg = "Failed to detach volume: " + volume.getName() + " from VM: " + vm.getName(); + boolean sendCommand = (vm.getState() == State.Running); + Answer answer = null; + + if (sendCommand) { + AttachVolumeCommand cmd = new AttachVolumeCommand(false, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), + cmmd.getDeviceId() != null ? cmmd.getDeviceId() : volume.getDeviceId(), volume.getChainInfo()); + + StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); + cmd.setPoolUuid(volumePool.getUuid()); + + try { + answer = _agentMgr.send(vm.getHostId(), cmd); + } catch (Exception e) { + throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage()); + } + } + + if (!sendCommand || (answer != null && answer.getResult())) { + // Mark the volume as detached + _volsDao.detachVolume(volume.getId()); + if (answer != null && answer instanceof AttachVolumeAnswer) { + volume.setChainInfo(((AttachVolumeAnswer) answer).getChainInfo()); + _volsDao.update(volume.getId(), volume); + } - try { - answer = _agentMgr.send(vm.getHostId(), cmd); - } catch (Exception e) { - throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage()); - } - } - - if (!sendCommand || (answer != null && answer.getResult())) { - // Mark the volume as detached - _volsDao.detachVolume(volume.getId()); - if(answer != null && answer instanceof AttachVolumeAnswer) { - volume.setChainInfo(((AttachVolumeAnswer)answer).getChainInfo()); - _volsDao.update(volume.getId(), volume); - } - return _volsDao.findById(volumeId); - } else { - - if (answer != null) { - String details = answer.getDetails(); - if (details != null && !details.isEmpty()) { + } else { + + if (answer != null) { + String details = answer.getDetails(); + if (details != null && !details.isEmpty()) { errorMsg += "; " + details; } - } - - throw new CloudRuntimeException(errorMsg); - } + } + + throw new CloudRuntimeException(errorMsg); + } } - + @Override public boolean attachISOToVM(long vmId, long isoId, boolean attach) { - UserVmVO vm = _vmDao.findById(vmId); - - if (vm == null) { + UserVmVO vm = _vmDao.findById(vmId); + + if (vm == null) { return false; - } else if (vm.getState() != State.Running) { - return true; - } + } else if (vm.getState() != State.Running) { + return true; + } String isoPath; - VMTemplateVO tmplt = _templateDao.findById(isoId); - if ( tmplt == null ) { - s_logger.warn("ISO: " + isoId +" does not exist"); + VMTemplateVO tmplt = _templateDao.findById(isoId); + if (tmplt == null) { + s_logger.warn("ISO: " + isoId + " does not exist"); return false; } // Get the path of the ISO Pair isoPathPair = null; - if ( tmplt.getTemplateType() == TemplateType.PERHOST ) { + if (tmplt.getTemplateType() == TemplateType.PERHOST) { isoPath = tmplt.getName(); } else { - isoPathPair = _storageMgr.getAbsoluteIsoPath(isoId, vm.getDataCenterId()); + isoPathPair = _storageMgr.getAbsoluteIsoPath(isoId, vm.getDataCenterId()); if (isoPathPair == null) { - s_logger.warn("Couldn't get absolute iso path"); - return false; - } else { - isoPath = isoPathPair.first(); - } + s_logger.warn("Couldn't get absolute iso path"); + return false; + } else { + isoPath = isoPathPair.first(); + } } - String vmName = vm.getInstanceName(); + String vmName = vm.getInstanceName(); - HostVO host = _hostDao.findById(vm.getHostId()); - if (host == null) { - s_logger.warn("Host: " + vm.getHostId() +" does not exist"); + HostVO host = _hostDao.findById(vm.getHostId()); + if (host == null) { + s_logger.warn("Host: " + vm.getHostId() + " does not exist"); return false; - } - AttachIsoCommand cmd = new AttachIsoCommand(vmName, isoPath, attach); - if (isoPathPair != null) { - cmd.setStoreUrl(isoPathPair.second()); - } - Answer a = _agentMgr.easySend(vm.getHostId(), cmd); - return (a != null); + } + AttachIsoCommand cmd = new AttachIsoCommand(vmName, isoPath, attach); + if (isoPathPair != null) { + cmd.setStoreUrl(isoPathPair.second()); + } + Answer a = _agentMgr.easySend(vm.getHostId(), cmd); + return (a != null); } - - private UserVm rebootVirtualMachine(long userId, long vmId) throws InsufficientCapacityException, ResourceUnavailableException{ + private UserVm rebootVirtualMachine(long userId, long vmId) throws InsufficientCapacityException, ResourceUnavailableException { UserVmVO vm = _vmDao.findById(vmId); User caller = _accountMgr.getActiveUser(userId); Account owner = _accountMgr.getAccount(vm.getAccountId()); @@ -813,18 +862,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (vm.getState() == State.Running && vm.getHostId() != null) { - return _itMgr.reboot(vm, null, caller, owner); + return _itMgr.reboot(vm, null, caller, owner); } else { s_logger.error("Vm id=" + vmId + " is not in Running state, failed to reboot"); return null; } } - - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_UPGRADE, eventDescription="upgrading Vm") + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_UPGRADE, eventDescription = "upgrading Vm") /* * TODO: cleanup eventually - Refactored API call */ - public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd){ + public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) { Long virtualMachineId = cmd.getId(); Long serviceOfferingId = cmd.getServiceOfferingId(); Account account = UserContext.current().getCaller(); @@ -833,79 +883,80 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vmInstance = _vmDao.findById(virtualMachineId); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + virtualMachineId); - } + throw new InvalidParameterValueException("unable to find a virtual machine with id " + virtualMachineId); + } + + userId = accountAndUserValidation(virtualMachineId, account, userId, vmInstance); - userId = accountAndUserValidation(virtualMachineId, account, userId,vmInstance); - // Check that the specified service offering ID is valid ServiceOfferingVO newServiceOffering = _offeringDao.findById(serviceOfferingId); if (newServiceOffering == null) { - throw new InvalidParameterValueException("Unable to find a service offering with id " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find a service offering with id " + serviceOfferingId); } - + // Check that the VM is stopped if (!vmInstance.getState().equals(State.Stopped)) { s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState()); - throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before upgrading."); + throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState() + + "; make sure the virtual machine is stopped and not in an error state before upgrading."); } - + // Check if the service offering being upgraded to is what the VM is already running with if (vmInstance.getServiceOfferingId() == newServiceOffering.getId()) { if (s_logger.isInfoEnabled()) { s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested service offering (" + newServiceOffering.getName() + ")"); } - + throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already has the requested service offering (" + newServiceOffering.getName() + ")"); } - + ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); - + // Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering // NOTE: With the new network refactoring in 2.2, we shouldn't need the check for same guest IP type anymore. /* - if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) { - String errorMsg = "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType(); - errorMsg += ". Please select a service offering with the same guest IP type as the VM's current service offering (" + currentServiceOffering.getGuestIpType() + ")."; - throw new InvalidParameterValueException(errorMsg); - } - */ - - // Check that the service offering being upgraded to has the same storage pool preference as the VM's current service offering + * if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) { String errorMsg = + * "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType(); errorMsg += + * ". Please select a service offering with the same guest IP type as the VM's current service offering (" + + * currentServiceOffering.getGuestIpType() + ")."; throw new InvalidParameterValueException(errorMsg); } + */ + + // Check that the service offering being upgraded to has the same storage pool preference as the VM's current service + // offering if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) { - throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + ", cannot switch between local storage and shared storage service offerings. Current offering useLocalStorage=" + - currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage()); + throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + + ", cannot switch between local storage and shared storage service offerings. Current offering useLocalStorage=" + currentServiceOffering.getUseLocalStorage() + + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage()); } // Check that there are enough resources to upgrade the service offering if (!_agentMgr.isVirtualMachineUpgradable(vmInstance, newServiceOffering)) { - throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available for an offering of " + - newServiceOffering.getCpu() + " cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory"); + throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available for an offering of " + newServiceOffering.getCpu() + " cpu(s) at " + + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory"); } - + // Check that the service offering being upgraded to has all the tags of the current service offering List currentTags = _configMgr.csvTagsToList(currentServiceOffering.getTags()); List newTags = _configMgr.csvTagsToList(newServiceOffering.getTags()); if (!newTags.containsAll(currentTags)) { - throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering does not have all the tags of the " + - "current service offering. Current service offering tags: " + currentTags + "; " + - "new service offering tags: " + newTags); + throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering does not have all the tags of the " + + "current service offering. Current service offering tags: " + currentTags + "; " + "new service offering tags: " + newTags); } - UserVmVO vmForUpdate = _vmDao.createForUpdate(); - vmForUpdate.setServiceOfferingId(serviceOfferingId); - vmForUpdate.setHaEnabled(_serviceOfferingDao.findById(serviceOfferingId).getOfferHA()); - _vmDao.update(vmInstance.getId(), vmForUpdate); - - return _vmDao.findById(vmInstance.getId()); + UserVmVO vmForUpdate = _vmDao.createForUpdate(); + vmForUpdate.setServiceOfferingId(serviceOfferingId); + vmForUpdate.setHaEnabled(_serviceOfferingDao.findById(serviceOfferingId).getOfferHA()); + _vmDao.update(vmInstance.getId(), vmForUpdate); + + return _vmDao.findById(vmInstance.getId()); } - private Long accountAndUserValidation(Long virtualMachineId,Account account, Long userId, UserVmVO vmInstance) { - if (account != null) { + private Long accountAndUserValidation(Long virtualMachineId, Account account, Long userId, UserVmVO vmInstance) { + if (account != null) { if (!isAdmin(account.getType()) && (account.getId() != vmInstance.getAccountId())) { throw new InvalidParameterValueException("Unable to find a virtual machine with id " + virtualMachineId + " for this account"); - } else if (!_domainDao.isChildDomain(account.getDomainId(),vmInstance.getDomainId())) { - throw new InvalidParameterValueException( "Invalid virtual machine id (" + virtualMachineId + ") given, unable to upgrade virtual machine."); + } else if (!_domainDao.isChildDomain(account.getDomainId(), vmInstance.getDomainId())) { + throw new InvalidParameterValueException("Invalid virtual machine id (" + virtualMachineId + ") given, unable to upgrade virtual machine."); } } @@ -913,61 +964,61 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (userId == null) { userId = Long.valueOf(User.UID_SYSTEM); } - return userId; - } + return userId; + } @Override public HashMap getVirtualMachineStatistics(long hostId, String hostName, List vmIds) throws CloudRuntimeException { - HashMap vmStatsById = new HashMap(); - - if (vmIds.isEmpty()) { - return vmStatsById; - } - - List vmNames = new ArrayList(); - - for (Long vmId : vmIds) { - UserVmVO vm = _vmDao.findById(vmId); - vmNames.add(vm.getInstanceName()); - } - - Answer answer = _agentMgr.easySend(hostId, new GetVmStatsCommand(vmNames,_hostDao.findById(hostId).getGuid(), hostName)); - if (answer == null || !answer.getResult()) { - s_logger.warn("Unable to obtain VM statistics."); - return null; - } else { - HashMap vmStatsByName = ((GetVmStatsAnswer) answer).getVmStatsMap(); + HashMap vmStatsById = new HashMap(); - if(vmStatsByName == null) - { - s_logger.warn("Unable to obtain VM statistics."); - return null; - } - - for (String vmName : vmStatsByName.keySet()) { - vmStatsById.put(vmIds.get(vmNames.indexOf(vmName)), vmStatsByName.get(vmName)); - } - } - - return vmStatsById; + if (vmIds.isEmpty()) { + return vmStatsById; + } + + List vmNames = new ArrayList(); + + for (Long vmId : vmIds) { + UserVmVO vm = _vmDao.findById(vmId); + vmNames.add(vm.getInstanceName()); + } + + Answer answer = _agentMgr.easySend(hostId, new GetVmStatsCommand(vmNames, _hostDao.findById(hostId).getGuid(), hostName)); + if (answer == null || !answer.getResult()) { + s_logger.warn("Unable to obtain VM statistics."); + return null; + } else { + HashMap vmStatsByName = ((GetVmStatsAnswer) answer).getVmStatsMap(); + + if (vmStatsByName == null) { + s_logger.warn("Unable to obtain VM statistics."); + return null; + } + + for (String vmName : vmStatsByName.keySet()) { + vmStatsById.put(vmIds.get(vmNames.indexOf(vmName)), vmStatsByName.get(vmName)); + } + } + + return vmStatsById; } - - @Override @DB + + @Override + @DB public UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException { - + Long vmId = cmd.getId(); Account accountHandle = UserContext.current().getCaller(); - - //if account is removed, return error - if(accountHandle!=null && accountHandle.getRemoved() != null) { - throw new InvalidParameterValueException("The account " + accountHandle.getId()+" is removed"); + + // if account is removed, return error + if (accountHandle != null && accountHandle.getRemoved() != null) { + throw new InvalidParameterValueException("The account " + accountHandle.getId() + " is removed"); } // Verify input parameters UserVmVO vm = _vmDao.findById(vmId.longValue()); - + if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } if ((accountHandle != null) && !_domainDao.isChildDomain(accountHandle.getDomainId(), vm.getDomainId())) { @@ -981,7 +1032,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } throw new InvalidParameterValueException("Unable to find vm by id " + vmId); } - + if (vm.getState() != State.Destroyed) { if (s_logger.isDebugEnabled()) { s_logger.debug("vm is not in the right state: " + vmId); @@ -995,23 +1046,23 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Transaction txn = Transaction.currentTxn(); AccountVO account = null; - txn.start(); + txn.start(); account = _accountDao.lockRow(vm.getAccountId(), true); - - //if the account is deleted, throw error - if(account.getRemoved()!=null) { + + // if the account is deleted, throw error + if (account.getRemoved() != null) { throw new CloudRuntimeException("Unable to recover VM as the account is deleted"); } - - // First check that the maximum number of UserVMs for the given accountId will not be exceeded + + // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { - ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); - rae.setResourceType("vm"); - txn.commit(); - throw rae; + ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); + rae.setResourceType("vm"); + txn.commit(); + throw rae; } - + _haMgr.cancelDestroy(vm, vm.getHostId()); _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); @@ -1020,7 +1071,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId); throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId); } - + // Recover the VM's disks List volumes = _volsDao.findByInstance(vmId); for (VolumeVO volume : volumes) { @@ -1029,23 +1080,25 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long templateId = volume.getTemplateId(); Long diskOfferingId = volume.getDiskOfferingId(); Long offeringId = null; - if(diskOfferingId != null){ + if (diskOfferingId != null) { DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId); - if(offering!=null && (offering.getType() == DiskOfferingVO.Type.Disk)){ + if (offering != null && (offering.getType() == DiskOfferingVO.Type.Disk)) { offeringId = offering.getId(); } } - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId , volume.getSize()); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, + volume.getSize()); _usageEventDao.persist(usageEvent); } } - + _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, new Long(volumes.size())); - - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString()); + + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm + .getHypervisorType().toString()); _usageEventDao.persist(usageEvent); txn.commit(); - + return _vmDao.findById(vmId); } @@ -1060,25 +1113,25 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } Map configs = _configDao.getConfiguration("AgentManager", params); - + _instance = configs.get("instance.name"); if (_instance == null) { _instance = "DEFAULT"; } - + String workers = configs.get("expunge.workers"); int wrks = NumbersUtil.parseInt(workers, 10); - + String time = configs.get("expunge.interval"); _expungeInterval = NumbersUtil.parseInt(time, 86400); - + time = configs.get("expunge.delay"); _expungeDelay = NumbersUtil.parseInt(time, _expungeInterval); - + _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("UserVm-Scavenger")); - + _itMgr.registerGuru(VirtualMachine.Type.User, this); - + s_logger.info("User VM Manager is configured."); return true; @@ -1091,13 +1144,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override public boolean start() { - _executor.scheduleWithFixedDelay(new ExpungeTask(), _expungeInterval, _expungeInterval, TimeUnit.SECONDS); + _executor.scheduleWithFixedDelay(new ExpungeTask(), _expungeInterval, _expungeInterval, TimeUnit.SECONDS); return true; } @Override public boolean stop() { - _executor.shutdown(); + _executor.shutdown(); return true; } @@ -1105,7 +1158,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } public String getRandomPrivateTemplateName() { - return UUID.randomUUID().toString(); + return UUID.randomUUID().toString(); } @Override @@ -1120,30 +1173,30 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager public boolean expunge(UserVmVO vm, long callerUserId, Account caller) { UserContext ctx = UserContext.current(); ctx.setAccountId(vm.getAccountId()); - - try { - if (!_itMgr.advanceExpunge(vm, _accountMgr.getSystemUser(), caller)) { + + try { + if (!_itMgr.advanceExpunge(vm, _accountMgr.getSystemUser(), caller)) { s_logger.info("Did not expunge " + vm); return false; } - - //Only if vm is not expunged already, cleanup it's resources - if (vm != null && vm.getRemoved() == null) { - //Cleanup vm resources - all the PF/LB/StaticNat rules associated with vm - s_logger.debug("Starting cleaning up vm " + vm + " resources..."); - if (cleanupVmResources(vm.getId())) { - s_logger.debug("Successfully cleaned up vm " + vm + " resources as a part of expunge process"); - } else { - s_logger.warn("Failed to cleanup resources as a part of vm " + vm + " expunge"); - return false; - } - - _itMgr.remove(vm, _accountMgr.getSystemUser(), caller); - _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); - } - - return true; - + + // Only if vm is not expunged already, cleanup it's resources + if (vm != null && vm.getRemoved() == null) { + // Cleanup vm resources - all the PF/LB/StaticNat rules associated with vm + s_logger.debug("Starting cleaning up vm " + vm + " resources..."); + if (cleanupVmResources(vm.getId())) { + s_logger.debug("Successfully cleaned up vm " + vm + " resources as a part of expunge process"); + } else { + s_logger.warn("Failed to cleanup resources as a part of vm " + vm + " expunge"); + return false; + } + + _itMgr.remove(vm, _accountMgr.getSystemUser(), caller); + _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); + } + + return true; + } catch (ResourceUnavailableException e) { s_logger.warn("Unable to expunge " + vm, e); return false; @@ -1155,33 +1208,33 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return false; } } - + private boolean cleanupVmResources(long vmId) { boolean success = true; - - //Remove vm from security groups + + // Remove vm from security groups _networkGroupMgr.removeInstanceFromGroups(vmId); - - //Remove vm from instance group + + // Remove vm from instance group removeInstanceFromInstanceGroup(vmId); - - //cleanup port forwarding rules + + // cleanup port forwarding rules if (_rulesMgr.revokePortForwardingRulesForVm(vmId)) { s_logger.debug("Port forwarding rules are removed successfully as a part of vm id=" + vmId + " expunge"); } else { success = false; s_logger.warn("Fail to remove port forwarding rules as a part of vm id=" + vmId + " expunge"); } - - //cleanup load balancer rules + + // cleanup load balancer rules if (_lbMgr.removeVmFromLoadBalancers(vmId)) { s_logger.debug("Removed vm id=" + vmId + " from all load balancers as a part of expunge process"); } else { success = false; s_logger.warn("Fail to remove vm id=" + vmId + " from load balancers as a part of expunge process"); } - - //If vm is assigned to static nat, disable static nat for the ip address + + // If vm is assigned to static nat, disable static nat for the ip address IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(vmId); try { if (ip != null) { @@ -1201,15 +1254,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } @Override - public void deletePrivateTemplateRecord(Long templateId){ - if ( templateId != null) { + public void deletePrivateTemplateRecord(Long templateId) { + if (templateId != null) { _templateDao.remove(templateId); } } - @Override - public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ResourceAllocationException { + public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd) throws ResourceAllocationException { Long userId = UserContext.current().getCallerUserId(); if (userId == null) { userId = User.UID_SYSTEM; @@ -1217,20 +1269,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Account account = UserContext.current().getCaller(); boolean isAdmin = ((account == null) || isAdmin(account.getType())); - - VMTemplateVO privateTemplate = null; - - UserVO user = _userDao.findById(userId); - - if (user == null) { - throw new InvalidParameterValueException("User " + userId + " does not exist"); - } + + VMTemplateVO privateTemplate = null; + + UserVO user = _userDao.findById(userId); + + if (user == null) { + throw new InvalidParameterValueException("User " + userId + " does not exist"); + } String name = cmd.getTemplateName(); if ((name == null) || (name.length() > 32)) { throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters"); } - + // do some parameter defaulting Integer bits = cmd.getBits(); Boolean requiresHvm = cmd.getRequiresHvm(); @@ -1243,41 +1295,42 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (isPublic == null) { isPublic = Boolean.FALSE; } - boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); + boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); if (!isAdmin && !allowPublicUserTemplates && isPublic) { throw new PermissionDeniedException("Failed to create template " + name + ", only private templates can be created."); } - - Long volumeId = cmd.getVolumeId(); - Long snapshotId = cmd.getSnapshotId(); - if ( (volumeId == null) && (snapshotId == null) ) { + + Long volumeId = cmd.getVolumeId(); + Long snapshotId = cmd.getSnapshotId(); + if ((volumeId == null) && (snapshotId == null)) { throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified."); - } - if ( (volumeId != null) && (snapshotId != null) ) { + } + if ((volumeId != null) && (snapshotId != null)) { throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")"); } - + long domainId; long accountId; HypervisorType hyperType; VolumeVO volume = null; - if (volumeId != null) { // create template from volume - volume = _volsDao.findById(volumeId); - if (volume == null) { - throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId); - } - // If private template is created from Volume, check that the volume will not be active when the private template is created + if (volumeId != null) { // create template from volume + volume = _volsDao.findById(volumeId); + if (volume == null) { + throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId); + } + // If private template is created from Volume, check that the volume will not be active when the private template is + // created if (!_storageMgr.volumeInactive(volume)) { - String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is attached to a non-stopped VM, please stop the VM first" ; + String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is attached to a non-stopped VM, please stop the VM first"; if (s_logger.isInfoEnabled()) { s_logger.info(msg); } throw new CloudRuntimeException(msg); } - domainId = volume.getDomainId(); - accountId = volume.getAccountId(); - hyperType = _volsDao.getHypervisorType(volumeId); - } else { // create template from snapshot + domainId = volume.getDomainId(); + accountId = volume.getAccountId(); + hyperType = _volsDao.getHypervisorType(volumeId); + } else { // create template from snapshot SnapshotVO snapshot = _snapshotDao.findById(snapshotId); if (snapshot == null) { throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId); @@ -1286,7 +1339,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager accountId = snapshot.getAccountId(); hyperType = snapshot.getHypervisorType(); volume = _volsDao.findById(snapshot.getVolumeId()); - } + } if (!isAdmin) { if (account.getId() != accountId) { @@ -1303,47 +1356,30 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager AccountVO ownerAccount = _accountDao.findById(accountId); if (_accountMgr.resourceLimitExceeded(ownerAccount, ResourceType.template)) { - ResourceAllocationException rae = new ResourceAllocationException("Maximum number of templates and ISOs for account: " + account.getAccountName() + " has been exceeded."); - rae.setResourceType("template"); - throw rae; - } - + ResourceAllocationException rae = new ResourceAllocationException("Maximum number of templates and ISOs for account: " + account.getAccountName() + " has been exceeded."); + rae.setResourceType("template"); + throw rae; + } + if (!isAdmin || featured == null) { featured = Boolean.FALSE; } - Long guestOSId = cmd.getOsTypeId(); - GuestOSVO guestOS = _guestOSDao.findById(guestOSId); - if (guestOS == null) { - throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist."); - } - - String uniqueName = Long.valueOf((userId == null)?1:userId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString(); - Long nextTemplateId = _templateDao.getNextInSequence(Long.class, "id"); - String description = cmd.getDisplayText(); - boolean isExtractable = false; - if ( volume != null ) { - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM ; - } - privateTemplate = new VMTemplateVO(nextTemplateId, - uniqueName, - name, - ImageFormat.RAW, - isPublic, - featured, - isExtractable, - TemplateType.USER, - null, - null, - requiresHvmValue, - bitsValue, - accountId, - null, - description, - passwordEnabledValue, - guestOS.getId(), - true, - hyperType); + Long guestOSId = cmd.getOsTypeId(); + GuestOSVO guestOS = _guestOSDao.findById(guestOSId); + if (guestOS == null) { + throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist."); + } + + String uniqueName = Long.valueOf((userId == null) ? 1 : userId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString(); + Long nextTemplateId = _templateDao.getNextInSequence(Long.class, "id"); + String description = cmd.getDisplayText(); + boolean isExtractable = false; + if (volume != null) { + VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); + isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; + } + privateTemplate = new VMTemplateVO(nextTemplateId, uniqueName, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, null, requiresHvmValue, bitsValue, accountId, + null, description, passwordEnabledValue, guestOS.getId(), true, hyperType); VMTemplateVO template = _templateDao.persist(privateTemplate); // Increment the number of templates @@ -1354,7 +1390,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return template; } - @Override @DB + @Override + @DB public VMTemplateVO createPrivateTemplate(CreateTemplateCmd command) throws CloudRuntimeException { Long userId = UserContext.current().getCallerUserId(); if (userId == null) { @@ -1363,25 +1400,25 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long templateId = command.getEntityId(); Long volumeId = command.getVolumeId(); Long snapshotId = command.getSnapshotId(); - SnapshotCommand cmd = null; + SnapshotCommand cmd = null; VMTemplateVO privateTemplate = null; - - String uniqueName = getRandomPrivateTemplateName(); - StoragePoolVO pool = null; - HostVO secondaryStorageHost = null; - long zoneId; - Long accountId = null; - - try { - if (snapshotId != null) { // create template from snapshot + String uniqueName = getRandomPrivateTemplateName(); + + StoragePoolVO pool = null; + HostVO secondaryStorageHost = null; + long zoneId; + Long accountId = null; + + try { + if (snapshotId != null) { // create template from snapshot SnapshotVO snapshot = _snapshotDao.findById(snapshotId); - if( snapshot == null ) { + if (snapshot == null) { throw new CloudRuntimeException("Unable to find Snapshot for Id " + snapshotId); } zoneId = snapshot.getDataCenterId(); secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId); - if ( secondaryStorageHost == null ) { + if (secondaryStorageHost == null) { throw new CloudRuntimeException("Can not find the secondary storage for zoneId " + zoneId); } String secondaryStorageURL = secondaryStorageHost.getStorageUrl(); @@ -1391,34 +1428,34 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (backupSnapshotUUID == null) { throw new CloudRuntimeException("Unable to create private template from snapshot " + snapshotId + " due to there is no backupSnapshotUUID for this snapshot"); } - + Long dcId = snapshot.getDataCenterId(); accountId = snapshot.getAccountId(); volumeId = snapshot.getVolumeId(); String origTemplateInstallPath = null; List storagePools = _storagePoolDao.listByDataCenterId(zoneId); - if( storagePools == null || storagePools.size() == 0) { + if (storagePools == null || storagePools.size() == 0) { throw new CloudRuntimeException("Unable to find storage pools in zone " + zoneId); } pool = storagePools.get(0); - if ( snapshot.getVersion() == "2.1" ) { + if (snapshot.getVersion() == "2.1") { VolumeVO volume = _volsDao.findByIdIncludingRemoved(volumeId); - if ( volume == null ) { + if (volume == null) { throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to unable to find orignal volume:" + volumeId + ", try it later "); } VMTemplateVO template = _templateDao.findByIdIncludingRemoved(volume.getTemplateId()); - if ( template == null ) { + if (template == null) { throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to unalbe to find orignal template :" + volume.getTemplateId() + ", try it later "); } Long origTemplateId = template.getId(); Long origTmpltAccountId = template.getAccountId(); - if( ! _volsDao.lockInLockTable(volumeId.toString(), 10)) { + if (!_volsDao.lockInLockTable(volumeId.toString(), 10)) { throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to volume:" + volumeId + " is being used, try it later "); } - cmd = new UpgradeSnapshotCommand(null, secondaryStorageURL, dcId, accountId, - volumeId, origTemplateId, origTmpltAccountId, null, snapshot.getBackupSnapshotId(), snapshot.getName(), "2.1" ); - if( ! _volsDao.lockInLockTable(volumeId.toString(), 10)) { + cmd = new UpgradeSnapshotCommand(null, secondaryStorageURL, dcId, accountId, volumeId, origTemplateId, origTmpltAccountId, null, snapshot.getBackupSnapshotId(), + snapshot.getName(), "2.1"); + if (!_volsDao.lockInLockTable(volumeId.toString(), 10)) { throw new CloudRuntimeException("Creating template failed due to volume:" + volumeId + " is being used, try it later "); } Answer answer = null; @@ -1435,29 +1472,27 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new CloudRuntimeException("Unable to upgrade snapshot"); } } - cmd = new CreatePrivateTemplateFromSnapshotCommand(pool.getUuid(), - secondaryStorageURL, dcId, accountId, snapshot.getVolumeId(), backupSnapshotUUID, snapshot.getName(), + cmd = new CreatePrivateTemplateFromSnapshotCommand(pool.getUuid(), secondaryStorageURL, dcId, accountId, snapshot.getVolumeId(), backupSnapshotUUID, snapshot.getName(), origTemplateInstallPath, templateId, name); - } else if (volumeId != null) { + } else if (volumeId != null) { VolumeVO volume = _volsDao.findById(volumeId); - if( volume == null ) { + if (volume == null) { throw new CloudRuntimeException("Unable to find volume for Id " + volumeId); } - if( volume.getPoolId() == null ) { + if (volume.getPoolId() == null) { _templateDao.remove(templateId); throw new CloudRuntimeException("Volume " + volumeId + " is empty, can't create template on it"); } String vmName = _storageMgr.getVmNameOnVolume(volume); - zoneId = volume.getDataCenterId(); + zoneId = volume.getDataCenterId(); secondaryStorageHost = _storageMgr.getSecondaryStorageHost(zoneId); - if ( secondaryStorageHost == null ) { + if (secondaryStorageHost == null) { throw new CloudRuntimeException("Can not find the secondary storage for zoneId " + zoneId); } String secondaryStorageURL = secondaryStorageHost.getStorageUrl(); pool = _storagePoolDao.findById(volume.getPoolId()); - cmd = new CreatePrivateTemplateFromVolumeCommand(secondaryStorageURL, templateId, volume.getAccountId(), - command.getTemplateName(), uniqueName, volume.getPath(), vmName); + cmd = new CreatePrivateTemplateFromVolumeCommand(secondaryStorageURL, templateId, volume.getAccountId(), command.getTemplateName(), uniqueName, volume.getPath(), vmName); } else { throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId"); @@ -1467,11 +1502,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // This can be sent to a KVM host too. CreatePrivateTemplateAnswer answer = null; - if( ! _volsDao.lockInLockTable(volumeId.toString(), 10)) { + if (!_volsDao.lockInLockTable(volumeId.toString(), 10)) { throw new CloudRuntimeException("Creating template failed due to volume:" + volumeId + " is being used, try it later "); } try { - answer = (CreatePrivateTemplateAnswer)_storageMgr.sendToPool(pool, cmd); + answer = (CreatePrivateTemplateAnswer) _storageMgr.sendToPool(pool, cmd); } catch (StorageUnavailableException e) { } finally { _volsDao.unlockFromLockTable(volumeId.toString()); @@ -1492,7 +1527,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Specify RAW format makes it unusable for snapshots. privateTemplate.setFormat(ImageFormat.RAW); } - + _templateDao.update(templateId, privateTemplate); // add template zone ref for this template @@ -1506,99 +1541,95 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager templateHostVO.setPhysicalSize(answer.getphysicalSize()); _templateHostDao.persist(templateHostVO); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), secondaryStorageHost.getDataCenterId(), privateTemplate.getId(), privateTemplate.getName(), null, null , templateHostVO.getSize()); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), secondaryStorageHost.getDataCenterId(), privateTemplate.getId(), + privateTemplate.getName(), null, null, templateHostVO.getSize()); _usageEventDao.persist(usageEvent); - - - } - } finally { - if (privateTemplate == null) { - Transaction txn = Transaction.currentTxn(); + } + } finally { + if (privateTemplate == null) { + Transaction txn = Transaction.currentTxn(); txn.start(); // Remove the template record _templateDao.remove(templateId); - - //decrement resource count + + // decrement resource count _accountMgr.decrementResourceCount(accountId, ResourceType.template); txn.commit(); - } - } - + } + } + return privateTemplate; } - //used for vm transitioning to error state - private void updateVmStateForFailedVmCreation(Long vmId) { - UserVmVO vm = _vmDao.findById(vmId); - if(vm != null){ - if(vm.getState().equals(State.Stopped)){ - _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationFailed, null); - //destroy associated volumes for vm in error state - List volumesForThisVm = _volsDao.findByInstance(vm.getId()); - for(VolumeVO volume : volumesForThisVm) { - try { + // used for vm transitioning to error state + private void updateVmStateForFailedVmCreation(Long vmId) { + UserVmVO vm = _vmDao.findById(vmId); + if (vm != null) { + if (vm.getState().equals(State.Stopped)) { + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationFailed, null); + // destroy associated volumes for vm in error state + List volumesForThisVm = _volsDao.findByInstance(vm.getId()); + for (VolumeVO volume : volumesForThisVm) { + try { _storageMgr.destroyVolume(volume); if (volume.getState() == Volume.State.Ready) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), - volume.getName()); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName()); _usageEventDao.persist(usageEvent); } } catch (ConcurrentOperationException e) { - s_logger.warn("Unable to delete volume:"+volume.getId()+" for vm:"+vmId+" whilst transitioning to error state"); + s_logger.warn("Unable to delete volume:" + volume.getId() + " for vm:" + vmId + " whilst transitioning to error state"); } - } - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName()); - _usageEventDao.persist(usageEvent); - } - } - } - - protected class ExpungeTask implements Runnable { - public ExpungeTask() { - } - - @Override - public void run() { - GlobalLock scanLock = GlobalLock.getInternLock("UserVMExpunge"); - try { - if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { - try { - List vms = _vmDao.findDestroyedVms(new Date(System.currentTimeMillis() - ((long)_expungeDelay << 10))); - if (s_logger.isInfoEnabled()) { - if (vms.size() == 0) { - s_logger.trace("Found " + vms.size() + " vms to expunge."); - } else { - s_logger.info("Found " + vms.size() + " vms to expunge."); - } - } - for (UserVmVO vm : vms) { - try { - expunge(vm, _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); - } catch(Exception e) { - s_logger.warn("Unable to expunge " + vm, e); - } - } - } catch (Exception e) { - s_logger.error("Caught the following Exception", e); - } finally { - scanLock.unlock(); - } - } - } finally { - scanLock.releaseRef(); - } - } + } + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName()); + _usageEventDao.persist(usageEvent); + } + } } - private static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } - - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_UPDATE, eventDescription="updating Vm") + protected class ExpungeTask implements Runnable { + public ExpungeTask() { + } + + @Override + public void run() { + GlobalLock scanLock = GlobalLock.getInternLock("UserVMExpunge"); + try { + if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { + try { + List vms = _vmDao.findDestroyedVms(new Date(System.currentTimeMillis() - ((long) _expungeDelay << 10))); + if (s_logger.isInfoEnabled()) { + if (vms.size() == 0) { + s_logger.trace("Found " + vms.size() + " vms to expunge."); + } else { + s_logger.info("Found " + vms.size() + " vms to expunge."); + } + } + for (UserVmVO vm : vms) { + try { + expunge(vm, _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); + } catch (Exception e) { + s_logger.warn("Unable to expunge " + vm, e); + } + } + } catch (Exception e) { + s_logger.error("Caught the following Exception", e); + } finally { + scanLock.unlock(); + } + } + } finally { + scanLock.releaseRef(); + } + } + } + + private static boolean isAdmin(short accountType) { + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_UPDATE, eventDescription = "updating Vm") public UserVm updateVirtualMachine(UpdateVMCmd cmd) { String displayName = cmd.getDisplayName(); String group = cmd.getGroup(); @@ -1608,58 +1639,57 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Account account = UserContext.current().getCaller(); Long userId = UserContext.current().getCallerUserId(); String userData = cmd.getUserData(); - - //Input validation + + // Input validation UserVmVO vmInstance = null; // Verify input parameters - vmInstance = _vmDao.findById(id.longValue()); - + vmInstance = _vmDao.findById(id.longValue()); + if (vmInstance == null) { throw new InvalidParameterValueException("unable to find virtual machine with id " + id); } - + ServiceOffering offering = _configMgr.getServiceOffering(vmInstance.getServiceOfferingId()); if (!offering.getOfferHA() && ha != null && ha) { throw new InvalidParameterValueException("Can't enable ha for the vm as it's created from the Service offering having HA disabled"); } - userId = accountAndUserValidation(id, account, userId,vmInstance); - - - if (displayName == null) { - displayName = vmInstance.getDisplayName(); - } + userId = accountAndUserValidation(id, account, userId, vmInstance); + + if (displayName == null) { + displayName = vmInstance.getDisplayName(); + } + + if (ha == null) { + ha = vmInstance.isHaEnabled(); + } - if (ha == null) { - ha = vmInstance.isHaEnabled(); - } - UserVmVO vm = _vmDao.findById(id); if (vm == null) { throw new CloudRuntimeException("Unable to find virual machine with id " + id); } - + if (vm.getState() == State.Error || vm.getState() == State.Expunging) { s_logger.error("vm is not in the right state: " + id); throw new InvalidParameterValueException("Vm with id " + id + " is not in the right state"); } - if(userData != null){ - validateUserData(userData); - //update userData on domain router. - }else{ - userData = vmInstance.getUserData(); + if (userData != null) { + validateUserData(userData); + // update userData on domain router. + } else { + userData = vmInstance.getUserData(); } - + String description = ""; - - if(displayName != vmInstance.getDisplayName()){ - description += "New display name: "+displayName+". "; + + if (displayName != vmInstance.getDisplayName()) { + description += "New display name: " + displayName + ". "; } - - if(ha != vmInstance.isHaEnabled()){ - if(ha){ + + if (ha != vmInstance.isHaEnabled()) { + if (ha) { description += "Enabled HA. "; } else { description += "Disabled HA. "; @@ -1670,10 +1700,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else { description += "Changed Guest OS Type to " + osTypeId + ". "; } - + if (group != null) { - if(addInstanceToGroup(id, group)){ - description += "Added to group: "+group+"."; + if (addInstanceToGroup(id, group)) { + description += "Added to group: " + group + "."; } } @@ -1682,41 +1712,45 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return _vmDao.findById(id); } - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_START, eventDescription="starting Vm", async=true) - public UserVm startVirtualMachine(StartVMCmd cmd) throws ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - return startVirtualMachine(cmd.getId()); - } + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_START, eventDescription = "starting Vm", async = true) + public UserVm startVirtualMachine(StartVMCmd cmd) throws ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + return startVirtualMachine(cmd.getId()); + } - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_REBOOT, eventDescription="rebooting Vm", async=true) - public UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException{ + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_REBOOT, eventDescription = "rebooting Vm", async = true) + public UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException { Account account = UserContext.current().getCaller(); Long userId = UserContext.current().getCallerUserId(); Long vmId = cmd.getId(); - - //Verify input parameters + + // Verify input parameters UserVmVO vmInstance = _vmDao.findById(vmId.longValue()); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } userId = accountAndUserValidation(vmId, account, userId, vmInstance); - + return rebootVirtualMachine(userId, vmId); - } + } - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_DESTROY, eventDescription="destroying Vm", async=true) - public UserVm destroyVm(DestroyVMCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException { - return destroyVm(cmd.getId()); - } + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_DESTROY, eventDescription = "destroying Vm", async = true) + public UserVm destroyVm(DestroyVMCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException { + return destroyVm(cmd.getId()); + } - @Override @DB - public InstanceGroupVO createVmGroup(CreateVMGroupCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + @Override + @DB + public InstanceGroupVO createVmGroup(CreateVMGroupCmd cmd) { Account account = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Long accountId = null; String groupName = cmd.getGroupName(); - + if (account == null) { account = _accountDao.findById(1L); } @@ -1747,7 +1781,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Failed to create vm group " + groupName + ", unable to find account for which to create a group."); } - //Check if name is already in use by this account + // Check if name is already in use by this account boolean isNameInUse = _vmGroupDao.isNameInUse(accountId, groupName); if (isNameInUse) { @@ -1758,32 +1792,32 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } @DB - private InstanceGroupVO createVmGroup(String groupName, long accountId) { + private InstanceGroupVO createVmGroup(String groupName, long accountId) { Account account = null; - final Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - account = _accountDao.acquireInLockTable(accountId); //to ensure duplicate vm group names are not created. - if (account == null) { - s_logger.warn("Failed to acquire lock on account"); - return null; - } - InstanceGroupVO group = _vmGroupDao.findByAccountAndName(accountId, groupName); - if (group == null){ - group = new InstanceGroupVO(groupName, accountId); - group = _vmGroupDao.persist(group); - } - return group; - } finally { - if (account != null) { - _accountDao.releaseFromLockTable(accountId); - } - txn.commit(); - } + final Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + account = _accountDao.acquireInLockTable(accountId); // to ensure duplicate vm group names are not created. + if (account == null) { + s_logger.warn("Failed to acquire lock on account"); + return null; + } + InstanceGroupVO group = _vmGroupDao.findByAccountAndName(accountId, groupName); + if (group == null) { + group = new InstanceGroupVO(groupName, accountId); + group = _vmGroupDao.persist(group); + } + return group; + } finally { + if (account != null) { + _accountDao.releaseFromLockTable(accountId); + } + txn.commit(); + } } @Override - public boolean deleteVmGroup(DeleteVMGroupCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public boolean deleteVmGroup(DeleteVMGroupCmd cmd) { Account account = UserContext.current().getCaller(); Long groupId = cmd.getId(); @@ -1806,105 +1840,105 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } @Override - public boolean deleteVmGroup(long groupId) { - //delete all the mappings from group_vm_map table + public boolean deleteVmGroup(long groupId) { + // delete all the mappings from group_vm_map table List groupVmMaps = _groupVMMapDao.listByGroupId(groupId); for (InstanceGroupVMMapVO groupMap : groupVmMaps) { - SearchCriteria sc = _groupVMMapDao.createSearchCriteria(); - sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); - _groupVMMapDao.expunge(sc); + SearchCriteria sc = _groupVMMapDao.createSearchCriteria(); + sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); + _groupVMMapDao.expunge(sc); + } + + if (_vmGroupDao.remove(groupId)) { + return true; + } else { + return false; } - - if (_vmGroupDao.remove(groupId)) { - return true; - } else { - return false; - } } - @Override @DB - public boolean addInstanceToGroup(long userVmId, String groupName) { - UserVmVO vm = _vmDao.findById(userVmId); + @Override + @DB + public boolean addInstanceToGroup(long userVmId, String groupName) { + UserVmVO vm = _vmDao.findById(userVmId); InstanceGroupVO group = _vmGroupDao.findByAccountAndName(vm.getAccountId(), groupName); - //Create vm group if the group doesn't exist for this account + // Create vm group if the group doesn't exist for this account if (group == null) { - group = createVmGroup(groupName, vm.getAccountId()); + group = createVmGroup(groupName, vm.getAccountId()); } - if (group != null) { - final Transaction txn = Transaction.currentTxn(); - txn.start(); - UserVm userVm = _vmDao.acquireInLockTable(userVmId); - if (userVm == null) { - s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); - } - try { - //don't let the group be deleted when we are assigning vm to it. - InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(group.getId(), false); - if (ngrpLock == null) { - s_logger.warn("Failed to acquire lock on vm group id=" + group.getId() + " name=" + group.getName()); - txn.rollback(); - return false; - } - - //Currently don't allow to assign a vm to more than one group - if (_groupVMMapDao.listByInstanceId(userVmId) != null) { - //Delete all mappings from group_vm_map table - List groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId); - for (InstanceGroupVMMapVO groupMap : groupVmMaps) { - SearchCriteria sc = _groupVMMapDao.createSearchCriteria(); - sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); - _groupVMMapDao.expunge(sc); - } - } - InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(group.getId(), userVmId); - _groupVMMapDao.persist(groupVmMapVO); - - txn.commit(); - return true; - } finally { - if (userVm != null) { - _vmDao.releaseFromLockTable(userVmId); - } - } - } - return false; - } - - @Override - public InstanceGroupVO getGroupForVm(long vmId) { - //TODO - in future releases vm can be assigned to multiple groups; but currently return just one group per vm - try { - List groupsToVmMap = _groupVMMapDao.listByInstanceId(vmId); - - if(groupsToVmMap != null && groupsToVmMap.size() != 0){ - InstanceGroupVO group = _vmGroupDao.findById(groupsToVmMap.get(0).getGroupId()); - return group; - } else { - return null; + if (group != null) { + final Transaction txn = Transaction.currentTxn(); + txn.start(); + UserVm userVm = _vmDao.acquireInLockTable(userVmId); + if (userVm == null) { + s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); } - } - catch (Exception e){ - s_logger.warn("Error trying to get group for a vm: "+e); - return null; - } - } - - @Override - public void removeInstanceFromInstanceGroup(long vmId) { - try { - List groupVmMaps = _groupVMMapDao.listByInstanceId(vmId); - for (InstanceGroupVMMapVO groupMap : groupVmMaps) { - SearchCriteria sc = _groupVMMapDao.createSearchCriteria(); - sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); - _groupVMMapDao.expunge(sc); - } - } catch (Exception e){ - s_logger.warn("Error trying to remove vm from group: "+e); - } - } - + try { + // don't let the group be deleted when we are assigning vm to it. + InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(group.getId(), false); + if (ngrpLock == null) { + s_logger.warn("Failed to acquire lock on vm group id=" + group.getId() + " name=" + group.getName()); + txn.rollback(); + return false; + } + + // Currently don't allow to assign a vm to more than one group + if (_groupVMMapDao.listByInstanceId(userVmId) != null) { + // Delete all mappings from group_vm_map table + List groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId); + for (InstanceGroupVMMapVO groupMap : groupVmMaps) { + SearchCriteria sc = _groupVMMapDao.createSearchCriteria(); + sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); + _groupVMMapDao.expunge(sc); + } + } + InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(group.getId(), userVmId); + _groupVMMapDao.persist(groupVmMapVO); + + txn.commit(); + return true; + } finally { + if (userVm != null) { + _vmDao.releaseFromLockTable(userVmId); + } + } + } + return false; + } + + @Override + public InstanceGroupVO getGroupForVm(long vmId) { + // TODO - in future releases vm can be assigned to multiple groups; but currently return just one group per vm + try { + List groupsToVmMap = _groupVMMapDao.listByInstanceId(vmId); + + if (groupsToVmMap != null && groupsToVmMap.size() != 0) { + InstanceGroupVO group = _vmGroupDao.findById(groupsToVmMap.get(0).getGroupId()); + return group; + } else { + return null; + } + } catch (Exception e) { + s_logger.warn("Error trying to get group for a vm: " + e); + return null; + } + } + + @Override + public void removeInstanceFromInstanceGroup(long vmId) { + try { + List groupVmMaps = _groupVMMapDao.listByInstanceId(vmId); + for (InstanceGroupVMMapVO groupMap : groupVmMaps) { + SearchCriteria sc = _groupVMMapDao.createSearchCriteria(); + sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId()); + _groupVMMapDao.expunge(sc); + } + } catch (Exception e) { + s_logger.warn("Error trying to remove vm from group: " + e); + } + } + protected boolean validPassword(String password) { if (password == null || password.length() == 0) { return false; @@ -1916,137 +1950,137 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } return true; } - + @Override - public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, - Account owner, String hostName, String displayName, Long diskOfferingId, - Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { - + public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, Account owner, + String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { + Account caller = UserContext.current().getCaller(); List networkList = new ArrayList(); - - //Verify that caller can perform actions in behalf of vm owner + + // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, owner); - - //Get default guest network in Basic zone + + // Get default guest network in Basic zone Network defaultNetwork = _networkMgr.getSystemNetworkByZoneAndTrafficType(zone.getId(), TrafficType.Guest); - + if (defaultNetwork == null) { throw new InvalidParameterValueException("Unable to find a default network to start a vm"); } else { networkList.add(_networkDao.findById(defaultNetwork.getId())); } - - return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, - diskSize, networkList, securityGroupIdList, group, userData, sshKeyPair, hypervisor, caller, destinationHost); + + return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, userData, sshKeyPair, hypervisor, + caller, destinationHost); } - - + @Override - public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, List securityGroupIdList, - Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, - HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { - + public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, + List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, + String sshKeyPair, Host destinationHost) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, + ResourceAllocationException { + Account caller = UserContext.current().getCaller(); List networkList = new ArrayList(); - - //Verify that caller can perform actions in behalf of vm owner + + // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, owner); - - //If no network is specified, find system security group enabled network + + // If no network is specified, find system security group enabled network if (networkIdList == null || networkIdList.isEmpty()) { NetworkVO networkWithSecurityGroup = _networkMgr.getNetworkWithSecurityGroupEnabled(zone.getId()); if (networkWithSecurityGroup == null) { throw new InvalidParameterValueException("No network with security enabled is found in zone id=" + zone.getId()); } - + networkList.add(networkWithSecurityGroup); - - } else if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { - //Only one network can be specified, and it should be security group enabled + + } else if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { + // Only one network can be specified, and it should be security group enabled if (networkIdList.size() > 1) { throw new InvalidParameterValueException("Only support one network per VM if security group enabled"); } - + NetworkVO network = _networkDao.findById(networkIdList.get(0).longValue()); - + if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); } - + if (!network.isSecurityGroupEnabled()) { - throw new InvalidParameterValueException("Network is not security group enabled: " + network.getId()); + throw new InvalidParameterValueException("Network is not security group enabled: " + network.getId()); } - + networkList.add(network); - + } else { - //Verify that all the networks are Direct/Guest/AccountSpecific; can't create combination of SG enabled network and regular networks + // Verify that all the networks are Direct/Guest/AccountSpecific; can't create combination of SG enabled network and + // regular networks for (Long networkId : networkIdList) { NetworkVO network = _networkDao.findById(networkId); - + if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); } - + if (network.isSecurityGroupEnabled() && networkIdList.size() > 1) { throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled"); } - + if (network.getTrafficType() != TrafficType.Guest || network.getGuestType() != GuestIpType.Direct || (network.getIsShared() && !network.isSecurityGroupEnabled())) { throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone"); } - - //Perform account permission check + + // Perform account permission check if (!network.getIsShared()) { - //Check account permissions + // Check account permissions List networkMap = _networkDao.listBy(owner.getId(), network.getId()); if (networkMap == null || networkMap.isEmpty()) { throw new PermissionDeniedException("Unable to create a vm using network with id " + network.getId() + ", permission denied"); } - } - + } + networkList.add(network); } } - - return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, - diskSize, networkList, securityGroupIdList, group, userData, sshKeyPair, hypervisor, caller, destinationHost); + + return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, userData, sshKeyPair, hypervisor, + caller, destinationHost); } - - + @Override - public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, String hostName, - String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) + public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, String hostName, + String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Host destinationHost) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { - + Account caller = UserContext.current().getCaller(); List networkList = new ArrayList(); - - //Verify that caller can perform actions in behalf of vm owner + + // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, owner); - + if (networkIdList == null || networkIdList.isEmpty()) { NetworkVO defaultNetwork = null; - - //if no network is passed in - //1) Check if default virtual network offering has Availability=Required. If it's true, search for corresponding network - // * if network is found, use it. If more than 1 virtual network is found, throw an error - // * if network is not found, create a new one and use it - //2) If Availability=Optional, search for default networks for the account. If it's more than 1, throw an error. - // If it's 0, and there are no default direct networks, create default Guest Virtual network - + + // if no network is passed in + // 1) Check if default virtual network offering has Availability=Required. If it's true, search for corresponding + // network + // * if network is found, use it. If more than 1 virtual network is found, throw an error + // * if network is not found, create a new one and use it + // 2) If Availability=Optional, search for default networks for the account. If it's more than 1, throw an error. + // If it's 0, and there are no default direct networks, create default Guest Virtual network + List defaultVirtualOffering = _networkOfferingDao.listByTrafficTypeAndGuestType(false, TrafficType.Guest, GuestIpType.Virtual); - + if (defaultVirtualOffering.get(0).getAvailability() == Availability.Required) { - //get Virtual netowrks + // get Virtual netowrks List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), GuestIpType.Virtual, true); - + if (virtualNetworks.isEmpty()) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, zone.getId(), null, null, null, null, owner, false, null); + Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, + zone.getId(), null, null, null, null, owner, false, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + owner + "; please specify networkIds"); @@ -2058,46 +2092,47 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (defaultNetworks.isEmpty()) { if (defaultVirtualOffering.get(0).getAvailability() == Availability.Optional) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, zone.getId(), null, null, null, null, owner, false, null); + Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, + zone.getId(), null, null, null, null, owner, false, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else { throw new InvalidParameterValueException("Unable to find default networks for account " + owner); } - + } else if (defaultNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default network is found for accoun " + owner); } else { defaultNetwork = defaultNetworks.get(0); } } - - //Check that network offering doesn't have Availability=Unavailable + + // Check that network offering doesn't have Availability=Unavailable NetworkOffering networkOffering = _configMgr.getNetworkOffering(defaultNetwork.getNetworkOfferingId()); - + if (networkOffering.getAvailability() == Availability.Unavailable) { throw new InvalidParameterValueException("Unable to find default network; please specify networkOfferingIds"); } - + networkList.add(defaultNetwork); - + } else { - + boolean requiredNetworkOfferingIsPresent = false; List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); Long requiredOfferingId = null; - + if (!requiredOfferings.isEmpty()) { - //in 2.2.x there can be only one required offering - default Virtual + // in 2.2.x there can be only one required offering - default Virtual requiredOfferingId = requiredOfferings.get(0).getId(); } - - for (Long networkId : networkIdList) { + + for (Long networkId : networkIdList) { NetworkVO network = _networkDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); } - - //Perform account permission check + + // Perform account permission check if (!network.getIsShared()) { List networkMap = _networkDao.listBy(owner.getId(), network.getId()); if (networkMap == null || networkMap.isEmpty()) { @@ -2108,94 +2143,93 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new PermissionDeniedException("Shared network id=" + networkId + " is not available in domain id=" + owner.getDomainId()); } } - - //check that corresponding offering is available + + // check that corresponding offering is available NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - + if (networkOffering.getAvailability() == Availability.Unavailable) { throw new InvalidParameterValueException("Network id=" + network.getId() + " can't be used; corresponding network offering is " + Availability.Unavailable); } - + if (requiredOfferingId != null && network.getNetworkOfferingId() == requiredOfferingId.longValue()) { requiredNetworkOfferingIsPresent = true; } - + networkList.add(network); } - - //If default Virtual network offering is Required, it has to be specified in the network list + + // If default Virtual network offering is Required, it has to be specified in the network list if (requiredOfferingId != null && !requiredNetworkOfferingIsPresent) { - throw new InvalidParameterValueException("Network created from the network offering id=" + requiredOfferingId + " is required; change network offering availability to be Optional to relax this requirement"); + throw new InvalidParameterValueException("Network created from the network offering id=" + requiredOfferingId + + " is required; change network offering availability to be Optional to relax this requirement"); } } - - return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, - diskSize, networkList, null, group, userData, sshKeyPair, hypervisor, caller, destinationHost); + + return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, null, group, userData, sshKeyPair, hypervisor, caller, + destinationHost); } - - - - @DB @ActionEvent (eventType=EventTypes.EVENT_VM_CREATE, eventDescription="deploying Vm", create=true) - protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, String hostName, String displayName, Account owner, Long diskOfferingId, - Long diskSize, List networkList, List securityGroupIdList, String group, String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Host destinationHost) - throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { - + + @DB + @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true) + protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, String hostName, String displayName, Account owner, Long diskOfferingId, + Long diskSize, List networkList, List securityGroupIdList, String group, String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, + Host destinationHost) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { + _accountMgr.checkAccess(caller, owner); long accountId = owner.getId(); - - if(destinationHost != null && !_accountMgr.isRootAdmin(caller.getType())){ - throw new PermissionDeniedException("Destination Host can only be specified by a Root Admin, permission denied"); - } - - if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ - throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zone.getId() ); - } - + + if (destinationHost != null && !_accountMgr.isRootAdmin(caller.getType())) { + throw new PermissionDeniedException("Destination Host can only be specified by a Root Admin, permission denied"); + } + + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { + throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId()); + } + if (zone.getDomainId() != null) { DomainVO domain = _domainDao.findById(zone.getDomainId()); if (domain == null) { throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone); } - //check that caller can operate with domain + // check that caller can operate with domain _accountMgr.checkAccess(caller, domain); - //check that vm owner can create vm in the domain + // check that vm owner can create vm in the domain _accountMgr.checkAccess(owner, domain); } - //check if account/domain is with in resource limits to create a new vm - if (_accountMgr.resourceLimitExceeded(owner, ResourceType.user_vm)) - { - ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + owner.getAccountName() + " has been exceeded."); - rae.setResourceType("vm"); - throw rae; + // check if account/domain is with in resource limits to create a new vm + if (_accountMgr.resourceLimitExceeded(owner, ResourceType.user_vm)) { + ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + owner.getAccountName() + " has been exceeded."); + rae.setResourceType("vm"); + throw rae; } - - //check if we have available pools for vm deployment + + // check if we have available pools for vm deployment List availablePools = _storagePoolDao.listPoolsByStatus(StoragePoolStatus.Up); - - if( availablePools == null || availablePools.size() < 1) { - throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment",-1); + + if (availablePools == null || availablePools.size() < 1) { + throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1); } - + ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId()); - + if (template.getTemplateType().equals(TemplateType.SYSTEM)) { - throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm"); + throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm"); + } + List listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId()); + if (listZoneTemplate == null || listZoneTemplate.isEmpty()) { + throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use"); } - List listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(),template.getId()); - if (listZoneTemplate==null || listZoneTemplate.isEmpty()){ - throw new InvalidParameterValueException("The template " +template.getId()+ " is not available for use"); - } boolean isIso = Storage.ImageFormat.ISO == template.getFormat(); if (isIso && !template.isBootable()) { throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId()); } - + // 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 Pair rootDiskOffering = new Pair(null, null); List> dataDiskOfferings = new ArrayList>(); - + if (isIso) { if (diskOfferingId == null) { throw new InvalidParameterValueException("Installing from ISO requires a disk offering to be specified for the root disk."); @@ -2232,77 +2266,78 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } validateUserData(userData); - + // Find an SSH public key corresponding to the key pair name, if one is given String sshPublicKey = null; if (sshKeyPair != null && !sshKeyPair.equals("")) { Account account = UserContext.current().getCaller(); - SSHKeyPair pair = _sshKeyPairDao.findByName(account.getAccountId(), account.getDomainId(), sshKeyPair); - if (pair == null) { + SSHKeyPair pair = _sshKeyPairDao.findByName(account.getAccountId(), account.getDomainId(), sshKeyPair); + if (pair == null) { throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found."); } - - sshPublicKey = pair.getPublicKey(); + + sshPublicKey = pair.getPublicKey(); } - + _accountMgr.checkAccess(caller, template); - + DataCenterDeployment plan = null; - if(destinationHost != null){ - s_logger.debug("Destination Host to deploy the VM is specified, adding it to the deployment plan"); - plan = new DataCenterDeployment(zone.getId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null); - }else{ - plan = new DataCenterDeployment(zone.getId()); + if (destinationHost != null) { + s_logger.debug("Destination Host to deploy the VM is specified, adding it to the deployment plan"); + plan = new DataCenterDeployment(zone.getId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null); + } else { + plan = new DataCenterDeployment(zone.getId()); } - + s_logger.debug("Allocating in the DB for vm"); - + List> networks = new ArrayList>(); short defaultNetworkNumber = 0; for (NetworkVO network : networkList) { - + if (network.isDefault()) { defaultNetworkNumber++; } - + networks.add(new Pair(network, null)); } - - //Verify network information - network default network has to be set; and vm can't have more than one default network - //This is a part of business logic because default network is required by Agent Manager in order to configure default gateway for the vm + + // Verify network information - network default network has to be set; and vm can't have more than one default network + // This is a part of business logic because default network is required by Agent Manager in order to configure default + // gateway for the vm if (defaultNetworkNumber == 0) { throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm"); - } else if (defaultNetworkNumber >1) { + } else if (defaultNetworkNumber > 1) { throw new InvalidParameterValueException("Only 1 default network per vm is supported"); } - + long id = _vmDao.getNextInSequence(Long.class, "id"); - + String instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance); if (hostName == null) { hostName = instanceName; } else { - //verify hostName (hostname doesn't have to be unique) + // verify hostName (hostname doesn't have to be unique) if (!NetUtils.verifyDomainNameLabel(hostName, true)) { - throw new InvalidParameterValueException("Invalid name. Vm name can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + - "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit"); + throw new InvalidParameterValueException("Invalid name. Vm name can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit"); } } - + HypervisorType hypervisorType = null; if (template == null || template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) { hypervisorType = hypervisor; } else { hypervisorType = template.getHypervisorType(); } - - UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, - template.getGuestOSId(), offering.getOfferHA(), owner.getDomainId(), owner.getId(), offering.getId(), userData, hostName); + + UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.getOfferHA(), owner.getDomainId(), owner.getId(), + offering.getId(), userData, hostName); if (sshPublicKey != null) { vm.setDetail("SSH.PublicKey", sshPublicKey); } - + if (isIso) { vm.setIsoId(template.getId()); } @@ -2310,19 +2345,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (_itMgr.allocate(vm, _templateDao.findById(template.getId()), offering, rootDiskOffering, dataDiskOfferings, networks, null, plan, hypervisorType, owner) == null) { return null; } - + _vmDao.saveDetails(vm); - + if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully allocated DB entry for " + vm); } - UserContext.current().setEventDetails("Vm Id: "+vm.getId()); + UserContext.current().setEventDetails("Vm Id: " + vm.getId()); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getName(), offering.getId(), template.getId(), hypervisorType.toString()); _usageEventDao.persist(usageEvent); - + _accountMgr.incrementResourceCount(accountId, ResourceType.user_vm); - - //Assign instance to the group + + // Assign instance to the group try { if (group != null) { boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group); @@ -2333,41 +2368,43 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } catch (Exception ex) { throw new CloudRuntimeException("Unable to assign Vm to the group " + group); } - + _networkGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList); - + return vm; - } - - private void validateUserData(String userData){ - byte [] decodedUserData = null; + } + + private void validateUserData(String userData) { + byte[] decodedUserData = null; if (userData != null) { if (userData.length() >= 2 * 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 > MAX_USER_DATA_LENGTH_BYTES){ + if (decodedUserData.length > 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"); } } - } - - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_CREATE, eventDescription="starting Vm", async=true) - public UserVm startVirtualMachine(DeployVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { - return startVirtualMachine(cmd, null); - } - - protected UserVm startVirtualMachine(DeployVMCmd cmd, Map additonalParams) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { - long vmId = cmd.getEntityId(); - UserVmVO vm = _vmDao.findById(vmId); - _vmDao.loadDetails(vm); - + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "starting Vm", async = true) + public UserVm startVirtualMachine(DeployVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { + return startVirtualMachine(cmd, null); + } + + protected UserVm startVirtualMachine(DeployVMCmd cmd, Map additonalParams) throws ResourceUnavailableException, InsufficientCapacityException, + ConcurrentOperationException { + long vmId = cmd.getEntityId(); + UserVmVO vm = _vmDao.findById(vmId); + _vmDao.loadDetails(vm); + // Check that the password was passed in and is valid VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId()); - + String password = "saved_password"; if (template.getEnablePassword()) { password = generateRandomPassword(); @@ -2377,144 +2414,142 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("A valid password for this virtual machine was not provided."); } - // Check if an SSH key pair was selected for the instance and if so use it to encrypt & save the vm password String sshPublicKey = vm.getDetail("SSH.PublicKey"); - if (sshPublicKey != null && !sshPublicKey.equals("") && password != null && !password.equals("saved_password") ) { - String encryptedPasswd = RSAHelper.encryptWithSSHPublicKey(sshPublicKey, password); - if (encryptedPasswd == null) { + if (sshPublicKey != null && !sshPublicKey.equals("") && password != null && !password.equals("saved_password")) { + String encryptedPasswd = RSAHelper.encryptWithSSHPublicKey(sshPublicKey, password); + if (encryptedPasswd == null) { throw new CloudRuntimeException("Error encrypting password"); } - - vm.setDetail("Encrypted.Password", encryptedPasswd); - _vmDao.saveDetails(vm); - } - - long userId = UserContext.current().getCallerUserId(); - UserVO caller = _userDao.findById(userId); - - AccountVO owner = _accountDao.findById(vm.getAccountId()); - - try { - Map params = new HashMap(); - if (additonalParams != null) { - params.putAll(additonalParams); - } - params.put(VirtualMachineProfile.Param.VmPassword, password); - vm = _itMgr.start(vm, params, caller, owner); - } finally { - updateVmStateForFailedVmCreation(vm.getId()); - } - - if (template.getEnablePassword()) { - //this value is not being sent to the backend; need only for api dispaly purposes - vm.setPassword(password); - } - - return vm; - } - - @Override - public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { - UserVmVO vm = profile.getVirtualMachine(); - Account owner = _accountDao.findById(vm.getAccountId()); - if (owner == null) { - throw new PermissionDeniedException("The owner of " + vm + " does not exist: " + vm.getAccountId()); - } - - if (owner.getState() == Account.State.disabled) { - throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId()); - } - - VirtualMachineTemplate template = profile.getTemplate(); - if (vm.getIsoId() != null) { - template = _templateDao.findById(vm.getIsoId()); - } - if (template != null && template.getFormat() == ImageFormat.ISO && vm.getIsoId() != null) { - String isoPath = null; - Pair isoPathPair = _storageMgr.getAbsoluteIsoPath(template.getId(), vm.getDataCenterId()); - if (isoPathPair == null) { - s_logger.warn("Couldn't get absolute iso path"); - return false; - } else { - isoPath = isoPathPair.first(); - } - if (template.isBootable()) { + vm.setDetail("Encrypted.Password", encryptedPasswd); + _vmDao.saveDetails(vm); + } + + long userId = UserContext.current().getCallerUserId(); + UserVO caller = _userDao.findById(userId); + + AccountVO owner = _accountDao.findById(vm.getAccountId()); + + try { + Map params = new HashMap(); + if (additonalParams != null) { + params.putAll(additonalParams); + } + params.put(VirtualMachineProfile.Param.VmPassword, password); + vm = _itMgr.start(vm, params, caller, owner); + } finally { + updateVmStateForFailedVmCreation(vm.getId()); + } + + if (template.getEnablePassword()) { + // this value is not being sent to the backend; need only for api dispaly purposes + vm.setPassword(password); + } + + return vm; + } + + @Override + public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { + UserVmVO vm = profile.getVirtualMachine(); + Account owner = _accountDao.findById(vm.getAccountId()); + + if (owner == null) { + throw new PermissionDeniedException("The owner of " + vm + " does not exist: " + vm.getAccountId()); + } + + if (owner.getState() == Account.State.disabled) { + throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId()); + } + + VirtualMachineTemplate template = profile.getTemplate(); + if (vm.getIsoId() != null) { + template = _templateDao.findById(vm.getIsoId()); + } + if (template != null && template.getFormat() == ImageFormat.ISO && vm.getIsoId() != null) { + String isoPath = null; + Pair isoPathPair = _storageMgr.getAbsoluteIsoPath(template.getId(), vm.getDataCenterId()); + if (isoPathPair == null) { + s_logger.warn("Couldn't get absolute iso path"); + return false; + } else { + isoPath = isoPathPair.first(); + } + if (template.isBootable()) { profile.setBootLoaderType(BootloaderType.CD); } - GuestOSVO guestOS = _guestOSDao.findById(template.getGuestOSId()); - String displayName = null; - if (guestOS != null) { - displayName = guestOS.getDisplayName(); - } - VolumeTO iso = new VolumeTO(profile.getId(), Volume.Type.ISO, StoragePoolType.ISO, null, template.getName(), null, isoPath, 0, - null, displayName); - - iso.setDeviceId(3); - profile.addDisk(iso); - } else { - /*create a iso placeholder*/ - VolumeTO iso = new VolumeTO(profile.getId(), Volume.Type.ISO, StoragePoolType.ISO, null, template.getName(), null, null, 0, - null); - iso.setDeviceId(3); - profile.addDisk(iso); - } - - return true; - } - - @Override - public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { - UserVmVO userVm = profile.getVirtualMachine(); - List nics = _nicDao.listByVmId(userVm.getId()); - for (NicVO nic : nics) { - NetworkVO network = _networkDao.findById(nic.getNetworkId()); - if (network.getTrafficType() == TrafficType.Guest || network.getTrafficType() == TrafficType.Public) { - userVm.setPrivateIpAddress(nic.getIp4Address()); - userVm.setPrivateMacAddress(nic.getMacAddress()); - } - } - _vmDao.update(userVm.getId(), userVm); - return true; - } - - @Override + GuestOSVO guestOS = _guestOSDao.findById(template.getGuestOSId()); + String displayName = null; + if (guestOS != null) { + displayName = guestOS.getDisplayName(); + } + VolumeTO iso = new VolumeTO(profile.getId(), Volume.Type.ISO, StoragePoolType.ISO, null, template.getName(), null, isoPath, 0, null, displayName); + + iso.setDeviceId(3); + profile.addDisk(iso); + } else { + /* create a iso placeholder */ + VolumeTO iso = new VolumeTO(profile.getId(), Volume.Type.ISO, StoragePoolType.ISO, null, template.getName(), null, null, 0, null); + iso.setDeviceId(3); + profile.addDisk(iso); + } + + return true; + } + + @Override + public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { + UserVmVO userVm = profile.getVirtualMachine(); + List nics = _nicDao.listByVmId(userVm.getId()); + for (NicVO nic : nics) { + NetworkVO network = _networkDao.findById(nic.getNetworkId()); + if (network.getTrafficType() == TrafficType.Guest || network.getTrafficType() == TrafficType.Public) { + userVm.setPrivateIpAddress(nic.getIp4Address()); + userVm.setPrivateMacAddress(nic.getMacAddress()); + } + } + _vmDao.update(userVm.getId(), userVm); + return true; + } + + @Override public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile profile) { return true; } @Override public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Commands cmds, ReservationContext context) { - UserVmVO vm = profile.getVirtualMachine(); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_START, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString()); + UserVmVO vm = profile.getVirtualMachine(); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_START, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm + .getHypervisorType().toString()); _usageEventDao.persist(usageEvent); - + List nics = _nicDao.listByVmId(vm.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); long isDefault = (nic.isDefaultNic()) ? 1 : 0; usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), network.getNetworkOfferingId(), null, isDefault); - _usageEventDao.persist(usageEvent); + _usageEventDao.persist(usageEvent); } - - return true; + + return true; } - + @Override public void finalizeExpunge(UserVmVO vm) { } - + @Override public UserVmVO persist(UserVmVO vm) { return _vmDao.persist(vm); } - + @Override public UserVmVO findById(long id) { return _vmDao.findById(id); } - + @Override public UserVmVO findByName(String name) { if (!VirtualMachineName.isValidVmName(name)) { @@ -2523,23 +2558,24 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return findById(VirtualMachineName.getVmId(name)); } - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_STOP, eventDescription="stopping Vm", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_STOP, eventDescription = "stopping Vm", async = true) public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException { - - //Input validation + + // Input validation Account caller = UserContext.current().getCaller(); Long userId = UserContext.current().getCallerUserId(); - - //if account is removed, return error + + // if account is removed, return error if (caller != null && caller.getRemoved() != null) { - throw new PermissionDeniedException("The account " + caller.getId()+" is removed"); + throw new PermissionDeniedException("The account " + caller.getId() + " is removed"); } - + UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - + userId = accountAndUserValidation(vmId, caller, userId, vm); UserVO user = _userDao.findById(userId); @@ -2549,41 +2585,40 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e); } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e); - } - + } + return _vmDao.findById(vmId); } - + @Override public void finalizeStop(VirtualMachineProfile profile, StopAnswer answer) { - VMInstanceVO vm = profile.getVirtualMachine(); + VMInstanceVO vm = profile.getVirtualMachine(); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_STOP, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName()); _usageEventDao.persist(usageEvent); - + List nics = _nicDao.listByVmId(vm.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), null, network.getNetworkOfferingId(), null, 0L); - _usageEventDao.persist(usageEvent); + _usageEventDao.persist(usageEvent); } } - + public String generateRandomPassword() { return PasswordGenerator.generateRandomPassword(6); } - @Override public UserVm startVirtualMachine(long vmId) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - //Input validation + // Input validation Account account = UserContext.current().getCaller(); Long userId = UserContext.current().getCallerUserId(); - - //if account is removed, return error - if(account!=null && account.getRemoved() != null) { - throw new PermissionDeniedException("The account " + account.getId()+" is removed"); + + // if account is removed, return error + if (account != null && account.getRemoved() != null) { + throw new PermissionDeniedException("The account " + account.getId() + " is removed"); } - + UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); @@ -2593,13 +2628,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVO user = _userDao.findById(userId); return _itMgr.start(vm, null, user, account); } - + @Override public UserVm destroyVm(long vmId) throws ResourceUnavailableException, ConcurrentOperationException { Account account = UserContext.current().getCaller(); Long userId = UserContext.current().getCallerUserId(); - - //Verify input parameters + + // Verify input parameters UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId); @@ -2607,7 +2642,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager userId = accountAndUserValidation(vmId, account, userId, vm); User caller = _userDao.findById(userId); - + boolean status; State vmState = vm.getState(); @@ -2616,14 +2651,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Unable to destroy " + vm, e); } - + if (status) { // Mark the account's volumes as destroyed List volumes = _volsDao.findByInstance(vmId); for (VolumeVO volume : volumes) { if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), - volume.getName()); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName()); _usageEventDao.persist(usageEvent); } } @@ -2634,14 +2668,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); } - return _vmDao.findById(vmId); + return _vmDao.findById(vmId); } else { throw new CloudRuntimeException("Failed to destroy vm with id " + vmId); } } @Override - public List searchForUserVMs(ListVMsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + public List searchForUserVMs(ListVMsCmd cmd) { Account caller = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); @@ -2649,13 +2683,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager String hypervisor = cmd.getHypervisor(); Long accountId = null; String path = null; - - if (isRecursive != null && isRecursive && domainId == null){ + + if (isRecursive != null && isRecursive && domainId == null) { throw new InvalidParameterValueException("Please enter a parent domain id for listing vms recursively"); } - + if (domainId != null) { - //Verify if user is authorized to see instances belonging to the domain + // Verify if user is authorized to see instances belonging to the domain DomainVO domain = _domainDao.findById(domainId); if (domain == null) { throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); @@ -2666,7 +2700,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isAdmin = false; if (_accountMgr.isAdmin(caller.getType())) { - isAdmin = true; + isAdmin = true; if (accountName != null && domainId != null) { caller = _accountDao.findActiveAccount(accountName, domainId); if (caller == null) { @@ -2674,25 +2708,25 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } accountId = caller.getId(); } - - if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + + if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { if (isRecursive == null) { DomainVO domain = _domainDao.findById(caller.getDomainId()); path = domain.getPath(); - } + } } } else { accountId = caller.getId(); } - + if (isRecursive != null && isRecursive && isAdmin) { if (isRecursive) { DomainVO domain = _domainDao.findById(domainId); path = domain.getPath(); domainId = null; } - } - + } + Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); c.addCriteria(Criteria.KEYWORD, cmd.getKeyword()); c.addCriteria(Criteria.ID, cmd.getId()); @@ -2702,7 +2736,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager c.addCriteria(Criteria.GROUPID, cmd.getGroupId()); c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork()); c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId()); - + if (domainId != null) { c.addCriteria(Criteria.DOMAINID, domainId); } @@ -2710,12 +2744,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (path != null) { c.addCriteria(Criteria.PATH, path); } - - if (HypervisorType.getType(hypervisor) != HypervisorType.None){ - c.addCriteria(Criteria.HYPERVISOR, hypervisor); - } else if (hypervisor != null){ - throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); - } + + if (HypervisorType.getType(hypervisor) != HypervisorType.None) { + c.addCriteria(Criteria.HYPERVISOR, hypervisor); + } else if (hypervisor != null) { + throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); + } // ignore these search requests if it's not an admin if (isAdmin) { @@ -2723,20 +2757,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager c.addCriteria(Criteria.HOSTID, cmd.getHostId()); c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId()); } - + if (accountId != null) { - c.addCriteria(Criteria.ACCOUNTID, new Object[] {accountId}); + c.addCriteria(Criteria.ACCOUNTID, new Object[] { accountId }); } - c.addCriteria(Criteria.ISADMIN, isAdmin); + c.addCriteria(Criteria.ISADMIN, isAdmin); return searchForUserVMs(c); } - @Override public List searchForUserVMs(Criteria c) { Filter searchFilter = new Filter(UserVmVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); - + SearchBuilder sb = _vmDao.createSearchBuilder(); Object[] accountIds = (Object[]) c.getCriteria(Criteria.ACCOUNTID); Object domainId = c.getCriteria(Criteria.DOMAINID); @@ -2756,7 +2789,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Object networkId = c.getCriteria(Criteria.NETWORKID); Object hypervisor = c.getCriteria(Criteria.HYPERVISOR); Object storageId = c.getCriteria(Criteria.STORAGE_ID); - + sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("accountIdEQ", sb.entity().getAccountId(), SearchCriteria.Op.EQ); @@ -2771,14 +2804,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); sb.and("hostIdIN", sb.entity().getHostId(), SearchCriteria.Op.IN); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - + if (path != null) { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - - if (groupId != null && (Long)groupId == -1) { + + if (groupId != null && (Long) groupId == -1) { SearchBuilder vmSearch = _groupVMMapDao.createSearchBuilder(); vmSearch.and("instanceId", vmSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); sb.join("vmSearch", vmSearch, sb.entity().getId(), vmSearch.entity().getInstanceId(), JoinBuilder.JoinType.LEFTOUTER); @@ -2787,46 +2820,46 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager groupSearch.and("groupId", groupSearch.entity().getGroupId(), SearchCriteria.Op.EQ); sb.join("groupSearch", groupSearch, sb.entity().getId(), groupSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + if (networkId != null) { SearchBuilder nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - + SearchBuilder networkSearch = _networkDao.createSearchBuilder(); networkSearch.and("networkId", networkSearch.entity().getId(), SearchCriteria.Op.EQ); nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); - + sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + if (storageId != null) { SearchBuilder volumeSearch = _volsDao.createSearchBuilder(); volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ); sb.join("volumeSearch", volumeSearch, sb.entity().getId(), volumeSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + // populate the search criteria with the values passed in - SearchCriteria sc = sb.create(); - if (groupId != null && (Long)groupId == -1){ - sc.setJoinParameters("vmSearch", "instanceId", (Object)null); - } else if (groupId != null ) { + SearchCriteria sc = sb.create(); + if (groupId != null && (Long) groupId == -1) { + sc.setJoinParameters("vmSearch", "instanceId", (Object) null); + } else if (groupId != null) { sc.setJoinParameters("groupSearch", "groupId", groupId); } - + if (keyword != null) { SearchCriteria ssc = _vmDao.createSearchCriteria(); ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("state", SearchCriteria.Op.EQ, keyword); - + sc.addAnd("displayName", SearchCriteria.Op.SC, ssc); } if (id != null) { sc.setParameters("id", id); } - + if (accountIds != null) { if (accountIds.length == 1) { if (accountIds[0] != null) { @@ -2835,16 +2868,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else { sc.setParameters("accountIdIN", accountIds); } - } - + } + if (domainId != null) { sc.setParameters("domainId", domainId); } - + if (path != null) { sc.setJoinParameters("domainSearch", "path", path + "%"); } - + if (networkId != null) { sc.setJoinParameters("nicSearch", "networkId", networkId); } @@ -2852,7 +2885,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (name != null) { sc.setParameters("name", "%" + name + "%"); } - + if (state != null) { if (notState != null && (Boolean) notState == true) { sc.setParameters("stateNEQ", state); @@ -2861,26 +2894,26 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } - if (hypervisor != null){ - sc.setParameters("hypervisorType", hypervisor); + if (hypervisor != null) { + sc.setParameters("hypervisorType", hypervisor); } - - //Don't show Destroyed and Expunging vms to the end user + + // Don't show Destroyed and Expunging vms to the end user if ((isAdmin != null) && ((Boolean) isAdmin != true)) { sc.setParameters("stateNIN", "Destroyed", "Expunging"); } if (zone != null) { sc.setParameters("dataCenterId", zone); - + if (state == null) { sc.setParameters("stateNEQ", "Destroyed"); } } if (pod != null) { sc.setParameters("podId", pod); - - if(state == null) { + + if (state == null) { sc.setParameters("stateNEQ", "Destroyed"); } } @@ -2902,7 +2935,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } } - + if (storageId != null) { sc.setJoinParameters("volumeSearch", "poolId", storageId); } @@ -2910,69 +2943,70 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return _vmDao.search(sc, searchFilter); } - @Override - public HypervisorType getHypervisorTypeOfUserVM(long vmid) { - UserVmVO userVm = _vmDao.findById(vmid); - if (userVm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmid); - } - - return userVm.getHypervisorType(); - } - - @Override - public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, - StorageUnavailableException, ResourceAllocationException { - // TODO Auto-generated method stub - return null; - } - @Override - public UserVm getUserVm(long vmId){ - return _vmDao.findById(vmId); + public HypervisorType getHypervisorTypeOfUserVM(long vmid) { + UserVmVO userVm = _vmDao.findById(vmid); + if (userVm == null) { + throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmid); + } + + return userVm.getHypervisorType(); } - - @Override @ActionEvent (eventType=EventTypes.EVENT_VM_MIGRATE, eventDescription="migrating VM", async=true) - public UserVm migrateVirtualMachine(UserVm vm, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException{ - //access check - only root admin can migrate VM - Account caller = UserContext.current().getCaller(); - if(caller.getType() != Account.ACCOUNT_TYPE_ADMIN){ - if(s_logger.isDebugEnabled()){ - s_logger.debug("Caller is not a root admin, permission denied to migrate the VM"); - } - throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!"); - } - //business logic - if(vm.getState() != State.Running){ + + @Override + public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, + ResourceAllocationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public UserVm getUserVm(long vmId) { + return _vmDao.findById(vmId); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true) + public UserVm migrateVirtualMachine(UserVm vm, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { + // access check - only root admin can migrate VM + Account caller = UserContext.current().getCaller(); + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Caller is not a root admin, permission denied to migrate the VM"); + } + throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!"); + } + // business logic + if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is not Running, unable to migrate the vm " + vm); } throw new InvalidParameterValueException("VM is not Running, unable to migrate the vm " + vm); } - if(!vm.getHypervisorType().equals(HypervisorType.XenServer)){ - if(s_logger.isDebugEnabled()){ - s_logger.debug(vm + " is not XenServer, cannot migrate this VM."); - } + if (!vm.getHypervisorType().equals(HypervisorType.XenServer)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug(vm + " is not XenServer, cannot migrate this VM."); + } throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer only"); - } - - ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId()); - if(svcOffering.getUseLocalStorage()){ - if(s_logger.isDebugEnabled()){ - s_logger.debug(vm + " is using Local Storage, cannot migrate this VM."); - } - throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); - } + } - //call to core process - DataCenterVO dcVO = _dcDao.findById(destinationHost.getDataCenterId()); - HostPodVO pod = _podDao.findById(destinationHost.getPodId()); - long srcHostId = vm.getHostId(); - Cluster cluster = _clusterDao.findById(destinationHost.getClusterId()); - DeployDestination dest = new DeployDestination(dcVO, pod,cluster,destinationHost); - - UserVmVO migratedVm = _itMgr.migrate((UserVmVO)vm, srcHostId, dest); - return migratedVm; + ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId()); + if (svcOffering.getUseLocalStorage()) { + if (s_logger.isDebugEnabled()) { + s_logger.debug(vm + " is using Local Storage, cannot migrate this VM."); + } + throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); + } + + // call to core process + DataCenterVO dcVO = _dcDao.findById(destinationHost.getDataCenterId()); + HostPodVO pod = _podDao.findById(destinationHost.getPodId()); + long srcHostId = vm.getHostId(); + Cluster cluster = _clusterDao.findById(destinationHost.getClusterId()); + DeployDestination dest = new DeployDestination(dcVO, pod, cluster, destinationHost); + + UserVmVO migratedVm = _itMgr.migrate((UserVmVO) vm, srcHostId, dest); + return migratedVm; } - + }