From 14bd345f1f9fd4f78addf4714a7c6561c46f4be9 Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Wed, 9 Jan 2013 04:41:27 -0800 Subject: [PATCH] merge compiles --- developer/pom.xml | 225 +- engine/api/pom.xml | 5 + .../service/api/ProvisioningService.java | 4 - .../cloud/entity/api/db/VMEntityVO.java | 110 +- .../datacenter/entity/api/db/ClusterVO.java | 134 +- .../entity/api/db/DataCenterVO.java | 257 +- .../datacenter/entity/api/db/HostPodVO.java | 279 +- .../datacenter/entity/api/db/HostVO.java | 94 +- .../storage/image/db/ImageDataDaoImpl.java | 33 +- .../storage/image/db/ImageDataVO.java | 11 +- .../storage/volume/db/VolumeVO.java | 11 +- .../datastore/db/PrimaryDataStoreVO.java | 22 +- .../acl/StaticRoleBasedAPIAccessChecker.java | 25 +- .../server/auth/LDAPUserAuthenticator.java | 58 +- server/pom.xml | 5 + server/src/com/cloud/api/ApiServer.java | 187 +- .../network/StorageNetworkManagerImpl.java | 580 +- .../com/cloud/network/dao/NetworkDaoImpl.java | 74 +- .../cloud/network/rules/FirewallRuleVO.java | 6 +- .../cloud/projects/ProjectManagerImpl.java | 474 +- .../cloud/server/ConfigurationServerImpl.java | 122 +- .../cloud/server/ManagementServerImpl.java | 655 +- .../cloud/servlet/CloudStartupServlet.java | 81 +- .../cloud/storage/dao/VolumeHostDaoImpl.java | 148 +- .../com/cloud/user/AccountManagerImpl.java | 76 +- .../src/com/cloud/user/DomainManagerImpl.java | 1 - .../uuididentity/IdentityServiceImpl.java | 59 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 7979 +++++++++-------- setup/db/create-schema.sql | 1 + utils/src/com/cloud/utils/StringUtils.java | 15 +- 30 files changed, 5902 insertions(+), 5829 deletions(-) diff --git a/developer/pom.xml b/developer/pom.xml index 4ebb903289d..659c4970714 100644 --- a/developer/pom.xml +++ b/developer/pom.xml @@ -1,4 +1,4 @@ - - - simulator - - deploydb-simulator - - - - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-2 - - - initialize - - read-project-properties - - - - ${project.parent.basedir}/utils/conf/db.properties - ${project.parent.basedir}/utils/conf/db.properties.override - - true - - - - - - org.codehaus.mojo - sql-maven-plugin - 1.5 - - - mysql - mysql-connector-java - ${cs.mysql.version} - - - - org.gjt.mm.mysql.Driver - jdbc:mysql://${db.simulator.host}:3306/simulator - ${db.simulator.username} - ${db.simulator.password} - ${maven.test.skip} - true - - + + + simulator + + + deploydb-simulator + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + - drop-database + initialize + + read-project-properties + + + + ${project.parent.basedir}/utils/conf/db.properties + ${project.parent.basedir}/utils/conf/db.properties.override + + true + + + + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + + + mysql + mysql-connector-java + ${cs.mysql.version} + + + + org.gjt.mm.mysql.Driver + jdbc:mysql://${db.simulator.host}:3306/simulator + ${db.simulator.username} + ${db.simulator.password} + ${maven.test.skip} + true + + + + drop-database process-test-resources execute @@ -575,12 +562,12 @@ root ${db.root.password} - jdbc:mysql://${db.simulator.host}:3306 - drop database if exists `simulator` - - - - create-database + jdbc:mysql://${db.simulator.host}:3306 + drop database if exists `simulator` + + + + create-database process-test-resources execute @@ -588,51 +575,51 @@ root ${db.root.password} - jdbc:mysql://${db.simulator.host}:3306 - create database `simulator` - - - - grant-user-cloud - process-test-resources - - execute - - - root - ${db.root.password} - jdbc:mysql://${db.simulator.host}:3306 - GRANT ALL ON simulator.* to - ${db.simulator.username}@`localhost` identified by - '${db.simulator.password}'; - - - - grant-user-cloud-all - process-test-resources - - execute - - - root - ${db.root.password} - jdbc:mysql://${db.simulator.host}:3306 - GRANT ALL ON simulator.* to - ${db.simulator.username}@`%` identified by - '${db.simulator.password}'; - - - - create-schema - process-test-resources - - execute - - - - ${basedir}/target/db/create-schema-simulator.sql - ${basedir}/target/db/templates.simulator.sql - + jdbc:mysql://${db.simulator.host}:3306 + create database `simulator` + + + + grant-user-cloud + process-test-resources + + execute + + + root + ${db.root.password} + jdbc:mysql://${db.simulator.host}:3306 + GRANT ALL ON simulator.* to + ${db.simulator.username}@`localhost` identified by + '${db.simulator.password}'; + + + + grant-user-cloud-all + process-test-resources + + execute + + + root + ${db.root.password} + jdbc:mysql://${db.simulator.host}:3306 + GRANT ALL ON simulator.* to + ${db.simulator.username}@`%` identified by + '${db.simulator.password}'; + + + + create-schema + process-test-resources + + execute + + + + ${basedir}/target/db/create-schema-simulator.sql + ${basedir}/target/db/templates.simulator.sql + diff --git a/engine/api/pom.xml b/engine/api/pom.xml index 63071b3b09e..99c01510f99 100644 --- a/engine/api/pom.xml +++ b/engine/api/pom.xml @@ -20,6 +20,11 @@ ../pom.xml + + org.apache.cloudstack + cloud-utils + ${project.version} + org.apache.cloudstack cloud-api diff --git a/engine/api/src/org/apache/cloudstack/engine/service/api/ProvisioningService.java b/engine/api/src/org/apache/cloudstack/engine/service/api/ProvisioningService.java index 8648f56bb9b..e1ba1de587c 100755 --- a/engine/api/src/org/apache/cloudstack/engine/service/api/ProvisioningService.java +++ b/engine/api/src/org/apache/cloudstack/engine/service/api/ProvisioningService.java @@ -21,8 +21,6 @@ package org.apache.cloudstack.engine.service.api; import java.util.List; import java.util.Map; -import javax.ws.rs.POST; - import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity; import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; @@ -42,10 +40,8 @@ public interface ProvisioningService { StorageEntity registerStorage(String name, List tags, Map details); - @POST ZoneEntity registerZone(String zoneUuid, String name, String owner, List tags, Map details); - @POST PodEntity registerPod(String podUuid, String name, String owner, String zoneUuid, List tags, Map details); ClusterEntity registerCluster(String clusterUuid, String name, String owner, List tags, Map details); diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java index cebca33e214..93ac691a4c4 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java @@ -159,30 +159,30 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject computeTags; - + @Transient List rootDiskTags; - + @Column(name="hostname") private String hostname = null; @Column(name="displayname") private String displayname = null; - + @Transient List networkIds; - - + + public VMEntityVO(long id, long serviceOfferingId, String name, @@ -227,8 +227,8 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject getComputeTags() { - return computeTags; - } + public List getComputeTags() { + return computeTags; + } - public void setComputeTags(List computeTags) { - this.computeTags = computeTags; - } + public void setComputeTags(List computeTags) { + this.computeTags = computeTags; + } - public List getRootDiskTags() { - return rootDiskTags; - } + public List getRootDiskTags() { + return rootDiskTags; + } - public void setRootDiskTags(List rootDiskTags) { - this.rootDiskTags = rootDiskTags; - } + public void setRootDiskTags(List rootDiskTags) { + this.rootDiskTags = rootDiskTags; + } - public String getHostname() { - return hostname; - } + public String getHostname() { + return hostname; + } - public void setHostname(String hostname) { - this.hostname = hostname; - } + public void setHostname(String hostname) { + this.hostname = hostname; + } - public String getDisplayname() { - return displayname; - } + public String getDisplayname() { + return displayname; + } - public void setDisplayname(String displayname) { - this.displayname = displayname; - } + public void setDisplayname(String displayname) { + this.displayname = displayname; + } - public List getNetworkIds() { - return networkIds; - } + public List getNetworkIds() { + return networkIds; + } - public void setNetworkIds(List networkIds) { - this.networkIds = networkIds; - } + public void setNetworkIds(List networkIds) { + this.networkIds = networkIds; + } + + @Override + public long getDiskOfferingId() { + // TODO Auto-generated method stub + return 0; + } } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/ClusterVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/ClusterVO.java index f13bde603bf..ab423231e13 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/ClusterVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/ClusterVO.java @@ -26,14 +26,14 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import com.cloud.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; -import com.cloud.org.Managed.ManagedState; import com.cloud.org.Grouping; +import com.cloud.org.Managed.ManagedState; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.StateMachine; @@ -46,52 +46,52 @@ public class ClusterVO implements Cluster, Identity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="name") String name; - + @Column(name="guid") String guid; - + @Column(name="data_center_id") long dataCenterId; - + @Column(name="pod_id") long podId; - + @Column(name="hypervisor_type") String hypervisorType; @Column(name="cluster_type") @Enumerated(value=EnumType.STRING) Cluster.ClusterType clusterType; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; - + @Column(name="managed_state") @Enumerated(value=EnumType.STRING) ManagedState managedState; - + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @Column(name="uuid") String uuid; - + //orchestration - + @Column(name="owner") private String owner = null; - + @Column(name=GenericDao.CREATED_COLUMN) protected Date created; @Column(name="lastUpdated", updatable=true) @Temporal(value=TemporalType.TIMESTAMP) protected Date lastUpdated; - + /** * Note that state is intentionally missing the setter. Any updates to * the state machine needs to go through the DAO object because someone @@ -101,59 +101,66 @@ public class ClusterVO implements Cluster, Identity { @StateMachine(state=State.class, event=Event.class) @Column(name="state", updatable=true, nullable=false, length=32) protected State state = null; - - + + public ClusterVO() { - clusterType = Cluster.ClusterType.CloudManaged; - allocationState = Grouping.AllocationState.Enabled; - - this.uuid = UUID.randomUUID().toString(); - this.state = State.Disabled; + clusterType = Cluster.ClusterType.CloudManaged; + allocationState = Grouping.AllocationState.Enabled; + + this.uuid = UUID.randomUUID().toString(); + this.state = State.Disabled; } - + public ClusterVO(long dataCenterId, long podId, String name) { this.dataCenterId = dataCenterId; this.podId = podId; this.name = name; - this.clusterType = Cluster.ClusterType.CloudManaged; - this.allocationState = Grouping.AllocationState.Enabled; - this.managedState = ManagedState.Managed; - this.uuid = UUID.randomUUID().toString(); - this.state = State.Disabled; + this.clusterType = Cluster.ClusterType.CloudManaged; + this.allocationState = Grouping.AllocationState.Enabled; + this.managedState = ManagedState.Managed; + this.uuid = UUID.randomUUID().toString(); + this.state = State.Disabled; } + @Override public long getId() { return id; } + @Override public String getName() { return name; } + @Override public long getDataCenterId() { return dataCenterId; } + @Override public long getPodId() { return podId; } - + + @Override public Cluster.ClusterType getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(Cluster.ClusterType clusterType) { - this.clusterType = clusterType; + this.clusterType = clusterType; } - + + @Override public AllocationState getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(AllocationState allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - + + @Override public ManagedState getManagedState() { return managedState; } @@ -170,7 +177,7 @@ public class ClusterVO implements Cluster, Identity { public int hashCode() { return NumbersUtil.hash(id); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof ClusterVO)) { @@ -179,19 +186,20 @@ public class ClusterVO implements Cluster, Identity { ClusterVO that = (ClusterVO)obj; return this.id == that.id; } - + + @Override public HypervisorType getHypervisorType() { - return HypervisorType.getType(hypervisorType); + return HypervisorType.getType(hypervisorType); } - public void setHypervisorType(String hy) { - hypervisorType = hy; + public void setHypervisorType(String hy) { + hypervisorType = hy; } - + public String getGuid() { return guid; } - + public void setGuid(String guid) { this.guid = guid; } @@ -203,33 +211,33 @@ public class ClusterVO implements Cluster, Identity { public void setName(String name) { this.name = name; } - + @Override public String getUuid() { - return this.uuid; + return this.uuid; } - + public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } - - public String getOwner() { - return owner; - } - public void setOwner(String owner) { - this.owner = owner; - } + public String getOwner() { + return owner; + } - public Date getCreated() { - return created; - } + public void setOwner(String owner) { + this.owner = owner; + } - public Date getLastUpdated() { - return lastUpdated; - } + public Date getCreated() { + return created; + } - public State getState() { - return state; - } + public Date getLastUpdated() { + return lastUpdated; + } + + public State getState() { + return state; + } } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/DataCenterVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/DataCenterVO.java index beccb6fe129..66fc67b3d9c 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/DataCenterVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/DataCenterVO.java @@ -29,10 +29,10 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; +import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import com.cloud.api.Identity; import com.cloud.dc.DataCenter; import com.cloud.network.Network.Provider; import com.cloud.org.Grouping; @@ -43,107 +43,107 @@ import com.cloud.utils.db.StateMachine; @Entity @Table(name="data_center") public class DataCenterVO implements DataCenter, Identity { - + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - - @Column(name="name") - private String name = null; - + + @Column(name="name") + private String name = null; + @Column(name="description") private String description = null; - + @Column(name="dns1") private String dns1 = null; - + @Column(name="dns2") private String dns2 = null; - + @Column(name="internal_dns1") private String internalDns1 = null; - + @Column(name="internal_dns2") private String internalDns2 = null; - + @Column(name="router_mac_address", updatable = false, nullable=false) private String routerMacAddress = "02:00:00:00:00:01"; - + @Column(name="guest_network_cidr") private String guestNetworkCidr = null; - + @Column(name="domain_id") private Long domainId = null; @Column(name="domain") private String domain; - + @Column(name="networktype") @Enumerated(EnumType.STRING) NetworkType networkType; - + @Column(name="dns_provider") private String dnsProvider; - + @Column(name="dhcp_provider") private String dhcpProvider; - + @Column(name="gateway_provider") private String gatewayProvider; - + @Column(name="vpn_provider") private String vpnProvider; - + @Column(name="userdata_provider") private String userDataProvider; - + @Column(name="lb_provider") private String loadBalancerProvider; - + @Column(name="firewall_provider") private String firewallProvider; - + @Column(name="mac_address", nullable=false) @TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1) private long macAddress = 1; - - @Column(name="zone_token") - private String zoneToken; - + + @Column(name="zone_token") + private String zoneToken; + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call the dao to load it. @Transient Map details; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; - @Column(name="uuid") - private String uuid; - + @Column(name="uuid") + private String uuid; + @Column(name="is_security_group_enabled") boolean securityGroupEnabled; - + @Column(name="is_local_storage_enabled") boolean localStorageEnabled; - + //orchestration @Column(name="owner") private String owner = null; - + @Column(name=GenericDao.CREATED_COLUMN) protected Date created; @Column(name="lastUpdated", updatable=true) @Temporal(value=TemporalType.TIMESTAMP) protected Date lastUpdated; - + /** * Note that state is intentionally missing the setter. Any updates to * the state machine needs to go through the DAO object because someone @@ -199,13 +199,13 @@ public class DataCenterVO implements DataCenter, Identity { public void setFirewallProvider(String firewallProvider) { this.firewallProvider = firewallProvider; } - + public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false); this.id = id; this.allocationState = Grouping.AllocationState.Enabled; this.uuid = UUID.randomUUID().toString(); - } + } public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled, boolean localStorageEnabled) { this.name = name; @@ -221,7 +221,7 @@ public class DataCenterVO implements DataCenter, Identity { this.allocationState = Grouping.AllocationState.Enabled; this.securityGroupEnabled = securityGroupEnabled; this.localStorageEnabled = localStorageEnabled; - + if (zoneType == NetworkType.Advanced) { loadBalancerProvider = Provider.VirtualRouter.getName(); firewallProvider = Provider.VirtualRouter.getName(); @@ -242,7 +242,7 @@ public class DataCenterVO implements DataCenter, Identity { this.uuid = UUID.randomUUID().toString(); this.state = State.Disabled; } - + @Override public String getVpnProvider() { return vpnProvider; @@ -260,27 +260,27 @@ public class DataCenterVO implements DataCenter, Identity { public void setUserDataProvider(String userDataProvider) { this.userDataProvider = userDataProvider; } - + @Override public String getGuestNetworkCidr() { - return guestNetworkCidr; + return guestNetworkCidr; } - + public void setGuestNetworkCidr(String guestNetworkCidr) { - this.guestNetworkCidr = guestNetworkCidr; + this.guestNetworkCidr = guestNetworkCidr; } @Override public Long getDomainId() { - return domainId; - } + return domainId; + } - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + @Override public String getDescription() { return description; @@ -289,12 +289,12 @@ public class DataCenterVO implements DataCenter, Identity { public String getRouterMacAddress() { return routerMacAddress; } - + @Override public String getDns1() { return dns1; } - + @Override public String getDns2() { return dns2; @@ -310,43 +310,43 @@ public class DataCenterVO implements DataCenter, Identity { return internalDns2; } - protected DataCenterVO() { + protected DataCenterVO() { } - @Override + @Override public long getId() { - return id; - } - - @Override + return id; + } + + @Override public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public void setDns1(String dns1) { - this.dns1 = dns1; - } - - public void setDns2(String dns2) { - this.dns2 = dns2; - } - - public void setInternalDns1(String dns3) { - this.internalDns1 = dns3; - } - - public void setInternalDns2(String dns4) { - this.internalDns2 = dns4; - } + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + public void setInternalDns1(String dns3) { + this.internalDns1 = dns3; + } + + public void setInternalDns2(String dns4) { + this.internalDns2 = dns4; + } public void setRouterMacAddress(String routerMacAddress) { this.routerMacAddress = routerMacAddress; } - + @Override public String getDomain() { return domain; @@ -355,7 +355,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setDomain(String domain) { this.domain = domain; } - + public void setNetworkType(NetworkType zoneNetworkType) { this.networkType = zoneNetworkType; } @@ -364,16 +364,16 @@ public class DataCenterVO implements DataCenter, Identity { public NetworkType getNetworkType() { return networkType; } - + @Override public boolean isSecurityGroupEnabled() { return securityGroupEnabled; } - + public void setSecurityGroupEnabled(boolean enabled) { this.securityGroupEnabled = enabled; } - + @Override public boolean isLocalStorageEnabled() { return localStorageEnabled; @@ -392,32 +392,33 @@ public class DataCenterVO implements DataCenter, Identity { public void setDetails(Map details2) { details = details2; } - + public String getDetail(String name) { assert (details != null) : "Did you forget to load the details?"; - + return details != null ? details.get(name) : null; } - + public void setDetail(String name, String value) { assert (details != null) : "Did you forget to load the details?"; - + details.put(name, value); } - + + @Override public AllocationState getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(AllocationState allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - + @Override public int hashCode() { return NumbersUtil.hash(id); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof DataCenterVO)) { @@ -429,25 +430,25 @@ public class DataCenterVO implements DataCenter, Identity { @Override public String getZoneToken() { - return zoneToken; - } - - public void setZoneToken(String zoneToken) { - this.zoneToken = zoneToken; - } - - public Date getRemoved() { - return removed; - } - - @Override - public String getUuid() { - return this.uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } + return zoneToken; + } + + public void setZoneToken(String zoneToken) { + this.zoneToken = zoneToken; + } + + public Date getRemoved() { + return removed; + } + + @Override + public String getUuid() { + return this.uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } public long getMacAddress() { return macAddress; @@ -457,23 +458,23 @@ public class DataCenterVO implements DataCenter, Identity { this.macAddress = macAddress; } - public String getOwner() { - return owner; - } + public String getOwner() { + return owner; + } - public void setOwner(String owner) { - this.owner = owner; - } + public void setOwner(String owner) { + this.owner = owner; + } - public Date getCreated() { - return created; - } + public Date getCreated() { + return created; + } - public Date getLastUpdated() { - return lastUpdated; - } + public Date getLastUpdated() { + return lastUpdated; + } - public State getState() { - return state; - } + public State getState() { + return state; + } } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostPodVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostPodVO.java index 6467a4b679e..6c71136a518 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostPodVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostPodVO.java @@ -26,10 +26,10 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import com.cloud.api.Identity; import com.cloud.dc.Pod; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; @@ -39,52 +39,52 @@ import com.cloud.utils.db.StateMachine; @Entity @Table(name = "host_pod_ref") public class HostPodVO implements Pod, Identity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + long id; - @Column(name = "name") - private String name = null; + @Column(name = "name") + private String name = null; - @Column(name = "data_center_id") - private long dataCenterId; - - @Column(name = "gateway") - private String gateway; + @Column(name = "data_center_id") + private long dataCenterId; + + @Column(name = "gateway") + private String gateway; - @Column(name = "cidr_address") - private String cidrAddress; + @Column(name = "cidr_address") + private String cidrAddress; - @Column(name = "cidr_size") - private int cidrSize; + @Column(name = "cidr_size") + private int cidrSize; - @Column(name = "description") - private String description; - + @Column(name = "description") + private String description; + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; - @Column(name = "external_dhcp") - private Boolean externalDhcp; - + @Column(name = "external_dhcp") + private Boolean externalDhcp; + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - @Column(name = "uuid") - private String uuid; - + @Column(name = "uuid") + private String uuid; + //orchestration @Column(name="owner") private String owner = null; - + @Column(name=GenericDao.CREATED_COLUMN) protected Date created; @Column(name="lastUpdated", updatable=true) @Temporal(value=TemporalType.TIMESTAMP) protected Date lastUpdated; - + /** * Note that state is intentionally missing the setter. Any updates to * the state machine needs to go through the DAO object because someone @@ -95,147 +95,152 @@ public class HostPodVO implements Pod, Identity { @Column(name="state", updatable=true, nullable=false, length=32) protected State state = null; - public HostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { - this.name = name; - this.dataCenterId = dcId; - this.gateway = gateway; - this.cidrAddress = cidrAddress; - this.cidrSize = cidrSize; - this.description = description; - this.allocationState = Grouping.AllocationState.Enabled; - this.externalDhcp = false; - this.uuid = UUID.randomUUID().toString(); - this.state = State.Disabled; - } + public HostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { + this.name = name; + this.dataCenterId = dcId; + this.gateway = gateway; + this.cidrAddress = cidrAddress; + this.cidrSize = cidrSize; + this.description = description; + this.allocationState = Grouping.AllocationState.Enabled; + this.externalDhcp = false; + this.uuid = UUID.randomUUID().toString(); + this.state = State.Disabled; + } - /* - * public HostPodVO(String name, long dcId) { this(null, name, dcId); } - */ - protected HostPodVO() { - this.uuid = UUID.randomUUID().toString(); - } + /* + * public HostPodVO(String name, long dcId) { this(null, name, dcId); } + */ + protected HostPodVO() { + this.uuid = UUID.randomUUID().toString(); + } - @Override + @Override public long getId() { - return id; - } + return id; + } - public long getDataCenterId() { - return dataCenterId; - } + @Override + public long getDataCenterId() { + return dataCenterId; + } - public void setDataCenterId(long dataCenterId) { - this.dataCenterId = dataCenterId; - } + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @Override + @Override public String getCidrAddress() { - return cidrAddress; - } + return cidrAddress; + } - public void setCidrAddress(String cidrAddress) { - this.cidrAddress = cidrAddress; - } + public void setCidrAddress(String cidrAddress) { + this.cidrAddress = cidrAddress; + } - @Override + @Override public int getCidrSize() { - return cidrSize; - } + return cidrSize; + } - public void setCidrSize(int cidrSize) { - this.cidrSize = cidrSize; - } - - @Override + public void setCidrSize(int cidrSize) { + this.cidrSize = cidrSize; + } + + @Override public String getGateway() { - return gateway; - } - - public void setGateway(String gateway) { - this.gateway = gateway; - } + return gateway; + } + + public void setGateway(String gateway) { + this.gateway = gateway; + } - public String getDescription() { - return description; - } + @Override + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } - + public void setDescription(String description) { + this.description = description; + } + + @Override public AllocationState getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(AllocationState allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - - // Use for comparisons only. - public HostPodVO(Long id) { - this.id = id; - } - - @Override + + // Use for comparisons only. + public HostPodVO(Long id) { + this.id = id; + } + + @Override public int hashCode() { - return NumbersUtil.hash(id); - } - - public boolean getExternalDhcp() { - return externalDhcp; - } - - public void setExternalDhcp(boolean use) { - externalDhcp = use; - } - - @Override + return NumbersUtil.hash(id); + } + + @Override + public boolean getExternalDhcp() { + return externalDhcp; + } + + public void setExternalDhcp(boolean use) { + externalDhcp = use; + } + + @Override public boolean equals(Object obj) { - if (obj instanceof HostPodVO) { - return id == ((HostPodVO)obj).id; - } else { - return false; - } - } - + if (obj instanceof HostPodVO) { + return id == ((HostPodVO)obj).id; + } else { + return false; + } + } + public Date getRemoved() { return removed; } - + @Override public String getUuid() { - return this.uuid; + return this.uuid; } - + public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } - - public String getOwner() { - return owner; - } - public void setOwner(String owner) { - this.owner = owner; - } - - public Date getCreated() { - return created; - } + public String getOwner() { + return owner; + } - public Date getLastUpdated() { - return lastUpdated; - } - - public State getState() { - return state; - } + public void setOwner(String owner) { + this.owner = owner; + } + + public Date getCreated() { + return created; + } + + public Date getLastUpdated() { + return lastUpdated; + } + + public State getState() { + return state; + } } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostVO.java index 964d7b32e3a..2537b75a244 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/HostVO.java @@ -37,10 +37,10 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; +import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import com.cloud.api.Identity; import com.cloud.host.Host; import com.cloud.host.Status; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -134,20 +134,20 @@ public class HostVO implements Host, Identity { @Column(name="setup") private boolean setup = false; - + @Column(name="resource_state", nullable=false) @Enumerated(value=EnumType.STRING) private ResourceState resourceState; @Column(name="hypervisor_version") private String hypervisorVersion; - + @Column(name="update_count", updatable = true, nullable=false) protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code. @Column(name="uuid") private String uuid; - + // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call host dao to load it. @@ -367,15 +367,15 @@ public class HostVO implements Host, Identity { @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + //orchestration @Column(name="owner") private String owner = null; - + @Column(name="lastUpdated", updatable=true) @Temporal(value=TemporalType.TIMESTAMP) protected Date lastUpdated; - + /** * Note that state is intentionally missing the setter. Any updates to * the state machine needs to go through the DAO object because someone @@ -719,61 +719,61 @@ public class HostVO implements Host, Identity { return hypervisorVersion; } - @Override - - // TODO, I tempoerary disable it as it breaks GenericSearchBuild when @Transient is applied - // @Transient - public Status getState() { - return status; - } - + @Override + + // TODO, I tempoerary disable it as it breaks GenericSearchBuild when @Transient is applied + // @Transient + public Status getState() { + return status; + } + @Override public ResourceState getResourceState() { return resourceState; } - + public void setResourceState(ResourceState state) { - resourceState = state; + resourceState = state; } - + @Override public boolean isInMaintenanceStates() { return (getResourceState() == ResourceState.Maintenance || getResourceState() == ResourceState.ErrorInMaintenance || getResourceState() == ResourceState.PrepareForMaintenance); } - + public long getUpdated() { - return updated; + return updated; } - - public long incrUpdated() { - updated++; - return updated; - } - - @Override - public String getUuid() { - return this.uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getOwner() { - return owner; - } - public void setOwner(String owner) { - this.owner = owner; - } + public long incrUpdated() { + updated++; + return updated; + } + + @Override + public String getUuid() { + return this.uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } - public Date getLastUpdated() { - return lastUpdated; - } + public Date getLastUpdated() { + return lastUpdated; + } - public State getOrchestrationState() { - return state; - } + public State getOrchestrationState() { + return state; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java index 5444a28096d..f710a2d6ab7 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java @@ -29,14 +29,12 @@ import java.util.List; import java.util.Map; import java.util.Set; -import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.cloudstack.storage.image.format.ISO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.BaseCmd; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.domain.DomainVO; @@ -48,9 +46,9 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.storage.Storage; -import com.cloud.storage.VMTemplateZoneVO; import com.cloud.storage.Storage.TemplateType; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.storage.VMTemplateZoneVO; import com.cloud.storage.dao.VMTemplateDaoImpl; import com.cloud.storage.dao.VMTemplateDetailsDao; import com.cloud.storage.dao.VMTemplateZoneDao; @@ -59,8 +57,6 @@ import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.utils.Pair; -import com.cloud.utils.component.ComponentInject; -import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; @@ -68,8 +64,8 @@ import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -78,10 +74,10 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen VMTemplateZoneDao _templateZoneDao = null; - + VMTemplateDetailsDao _templateDetailsDao = null; - + ConfigurationDao _configDao = null; HostDao _hostDao = null; @@ -674,15 +670,17 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen } // for now, defaulting pageSize to a large val if null; may need to // revisit post 2.2RC2 - if (isIso && templateZonePairList.size() < (pageSize != null ? pageSize : 500) && templateFilter != TemplateFilter.community - && !(templateFilter == TemplateFilter.self && !BaseCmd.isRootAdmin(caller.getType()))) { // evaluates - // to - // true - // If - // root - // admin - // and - // filter=self + if (isIso && + templateZonePairList.size() < (pageSize != null ? pageSize : 500) && + templateFilter != TemplateFilter.community && + !(templateFilter == TemplateFilter.self) /* TODO: Fix this! && !BaseCmd.isRootAdmin(caller.getType())*/) { // evaluates + // to + // true + // If + // root + // admin + // and + // filter=self List publicIsos = publicIsoSearch(bootable, false, tags); List userIsos = userIsoSearch(false); @@ -855,6 +853,7 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen } } + @Override public ImageDataVO findSystemVMTemplate(long zoneId, HypervisorType hType) { SearchCriteria sc = tmpltTypeHyperSearch.create(); sc.setParameters("templateType", Storage.TemplateType.SYSTEM); diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java index 19ed0fd74a3..e66b7bbb31d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java @@ -33,11 +33,12 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; + import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage; -import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Storage.TemplateType; +import com.cloud.storage.VMTemplateVO; import com.cloud.utils.db.GenericDao; @Entity @@ -77,7 +78,7 @@ public class ImageDataVO implements Identity { @Temporal(value = TemporalType.TIMESTAMP) @Column(name = GenericDao.CREATED_COLUMN) - private Date created = null; + private final Date created = null; @Column(name = GenericDao.REMOVED) @Temporal(TemporalType.TIMESTAMP) @@ -178,7 +179,7 @@ public class ImageDataVO implements Identity { public boolean requiresHvm() { return requiresHvm; } - + public void setRequireHvm(boolean hvm) { this.requiresHvm = hvm; } @@ -234,7 +235,7 @@ public class ImageDataVO implements Identity { public long getAccountId() { return accountId; } - + public void setAccountId(long accountId) { this.accountId = accountId; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java index 32e6e3bc01b..ee1600ddd4f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java @@ -32,11 +32,11 @@ import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.engine.subsystem.api.storage.disktype.Unknown; -import com.cloud.api.Identity; -import com.cloud.storage.Volume; import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.Volume; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateObject; @@ -124,9 +124,9 @@ public class VolumeVO implements Identity, StateObject { @Column(name = "update_count", updatable = true, nullable = false) protected long updatedCount; // This field should be updated everytime the - // state is updated. There's no set method in - // the vo object because it is done with in the - // dao code. + // state is updated. There's no set method in + // the vo object because it is done with in the + // dao code. @Column(name = "recreatable") boolean recreatable; @@ -345,6 +345,7 @@ public class VolumeVO implements Identity, StateObject { return updated; } + @Override public Volume.State getState() { return state; } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreVO.java b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreVO.java index 4a7a5366045..c8265c7956c 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreVO.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreVO.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.storage.datastore.db; import java.util.Date; -import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; @@ -30,12 +29,10 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import javax.persistence.Transient; +import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.storage.datastore.DataStoreStatus; -import com.cloud.api.Identity; -import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.db.GenericDao; @Entity @@ -98,7 +95,7 @@ public class PrimaryDataStoreVO implements Identity { @Column(name = "cluster_id") private Long clusterId; - + @Column(name = "configurator_key") private String key; @@ -118,6 +115,7 @@ public class PrimaryDataStoreVO implements Identity { return name; } + @Override public String getUuid() { return uuid; } @@ -125,7 +123,7 @@ public class PrimaryDataStoreVO implements Identity { public String getPoolType() { return poolType; } - + public void setPoolType(String protocol) { this.poolType = protocol; } @@ -181,7 +179,7 @@ public class PrimaryDataStoreVO implements Identity { public String getHostAddress() { return hostAddress; } - + public void setHostAddress(String host) { this.hostAddress = host; } @@ -225,7 +223,7 @@ public class PrimaryDataStoreVO implements Identity { public int getPort() { return port; } - + public void setPort(int port) { this.port = port; } @@ -237,13 +235,13 @@ public class PrimaryDataStoreVO implements Identity { public void setName(String name) { this.name = name; } - + public void setKey(String key) { - this.key = key; + this.key = key; } - + public String getKey() { - return this.key; + return this.key; } @Override diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java index d39f87f1048..9236fbace4e 100644 --- a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -21,22 +21,23 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; import javax.ejb.Local; import javax.naming.ConfigurationException; -import org.apache.cloudstack.acl.APIAccessChecker; import org.apache.log4j.Logger; import com.cloud.exception.PermissionDeniedException; -import com.cloud.server.ManagementServer; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.PluggableService; @@ -60,6 +61,7 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA private static List s_allCommands = null; protected @Inject AccountManager _accountMgr; + @Inject protected List _services; protected StaticRoleBasedAPIAccessChecker() { super(); @@ -77,10 +79,10 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA boolean commandExists = s_allCommands.contains(apiCommandName); if(commandExists && user != null){ - Long accountId = user.getAccountId(); - Account userAccount = _accountMgr.getAccount(accountId); - short accountType = userAccount.getType(); - return isCommandAvailableForAccount(accountType, apiCommandName); + Long accountId = user.getAccountId(); + Account userAccount = _accountMgr.getAccount(accountId); + short accountType = userAccount.getType(); + return isCommandAvailableForAccount(accountType, apiCommandName); } return commandExists; @@ -109,13 +111,8 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - // Read command properties files to build the static map per role. - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - List services = locator.getAllPluggableServices(); - services.add((PluggableService) ComponentLocator.getComponent(ManagementServer.Name)); - List configFiles = new ArrayList(); - for (PluggableService service : services) { + for (PluggableService service : _services) { configFiles.addAll(Arrays.asList(service.getPropertiesFiles())); } diff --git a/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java b/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java index 00b4c1fef9b..dba92d0e86f 100644 --- a/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java +++ b/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java @@ -30,10 +30,11 @@ import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; +import org.apache.cloudstack.api.ApiConstants.LDAPParams; import org.apache.log4j.Logger; import org.bouncycastle.util.encoders.Base64; +import org.springframework.stereotype.Component; -import org.apache.cloudstack.api.ApiConstants.LDAPParams; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.server.ManagementServer; import com.cloud.user.UserAccount; @@ -49,7 +50,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { private ConfigurationDao _configDao; private UserAccountDao _userAccountDao; - + @Override public boolean authenticate(String username, String password, Long domainId, Map requestParameters ) { if (s_logger.isDebugEnabled()) { @@ -74,14 +75,14 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { String bindPasswd = _configDao.getValue(LDAPParams.passwd.toString()); String trustStore = _configDao.getValue(LDAPParams.truststore.toString()); String trustStorePassword = _configDao.getValue(LDAPParams.truststorepass.toString()); - + try { // get all params Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); String protocol = "ldap://" ; if (new Boolean(useSSL)){ - env.put(Context.SECURITY_PROTOCOL, "ssl"); + env.put(Context.SECURITY_PROTOCOL, "ssl"); protocol="ldaps://" ; System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); @@ -93,10 +94,10 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { env.put(Context.SECURITY_CREDENTIALS, bindPasswd); } else { - // Use anonymous authentication - env.put(Context.SECURITY_AUTHENTICATION, "none"); + // Use anonymous authentication + env.put(Context.SECURITY_AUTHENTICATION, "none"); } - // Create the initial context + // Create the initial context DirContext ctx = new InitialDirContext(env); // use this context to search @@ -104,7 +105,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { queryFilter = queryFilter.replaceAll("\\%u", username); queryFilter = queryFilter.replaceAll("\\%n", user.getFirstname() + " " + user.getLastname()); queryFilter = queryFilter.replaceAll("\\%e", user.getEmail()); - + SearchControls sc = new SearchControls(); String[] searchFilter = { "dn" }; @@ -112,22 +113,22 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { sc.setReturningAttributes(searchFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setCountLimit(1); - + // Search for objects with those matching attributes NamingEnumeration answer = ctx.search(searchBase, queryFilter, sc); - SearchResult sr = (SearchResult)answer.next(); + SearchResult sr = answer.next(); String cn = sr.getName(); answer.close(); ctx.close(); - + s_logger.info("DN from LDAP =" + cn); - + // check the password env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); protocol = "ldap://" ; if (new Boolean(useSSL)){ - env.put(Context.SECURITY_PROTOCOL, "ssl"); + env.put(Context.SECURITY_PROTOCOL, "ssl"); protocol="ldaps://" ; } env.put(Context.PROVIDER_URL, protocol + url + ":" + port); @@ -136,22 +137,23 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { // Create the initial context ctx = new InitialDirContext(env); ctx.close(); - + } catch (NamingException ne) { ne.printStackTrace(); s_logger.warn("Authentication failed due to " + ne.getMessage()); return false; } catch (Exception e){ - e.printStackTrace(); + e.printStackTrace(); s_logger.warn("Unknown error encountered " + e.getMessage()); return false; } - + // authenticate return true; } + @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); @@ -161,16 +163,16 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { return true; } - @Override - public String encode(String password) { - // Password is not used, so set to a random string - try { - SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); - byte bytes[] = new byte[20]; - randomGen.nextBytes(bytes); - return Base64.encode(bytes).toString(); - } catch (NoSuchAlgorithmException e) { - throw new CloudRuntimeException("Failed to generate random password",e); - } - } + @Override + public String encode(String password) { + // Password is not used, so set to a random string + try { + SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); + byte bytes[] = new byte[20]; + randomGen.nextBytes(bytes); + return Base64.encode(bytes).toString(); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Failed to generate random password",e); + } + } } diff --git a/server/pom.xml b/server/pom.xml index 9e6bc68f8f6..b6d86e128b5 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -85,6 +85,11 @@ reflections 0.9.8 + + org.apache.cloudstack + cloud-engine-api + ${project.version} + install diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 8a88cbba750..6faaa4a067a 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -52,16 +52,29 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.cloudstack.acl.APIAccessChecker; -import org.apache.cloudstack.acl.ControlledEntity; -import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.response.ExceptionResponse; +import org.apache.cloudstack.api.response.ListResponse; import org.apache.commons.codec.binary.Base64; -import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; @@ -69,6 +82,7 @@ import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpServerConnection; @@ -89,18 +103,9 @@ import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; +import org.reflections.Reflections; -import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; -import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; -import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; -import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; -import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; -import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; -import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import com.cloud.api.response.ApiResponseSerializer; -import org.apache.cloudstack.api.response.ExceptionResponse; -import org.apache.cloudstack.api.response.ListResponse; import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -123,18 +128,15 @@ import com.cloud.user.UserAccount; import com.cloud.user.UserContext; import com.cloud.user.UserVO; import com.cloud.utils.Pair; -import com.cloud.utils.component.Adapters; import com.cloud.utils.StringUtils; +import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.uuididentity.dao.IdentityDao; -import org.reflections.Reflections; - public class ApiServer implements HttpRequestHandler { private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); @@ -143,18 +145,18 @@ public class ApiServer implements HttpRequestHandler { public static String jsonContentType = "text/javascript"; private ApiDispatcher _dispatcher; - @Inject private AccountManager _accountMgr = null; - @Inject private DomainManager _domainMgr = null; - @Inject private AsyncJobManager _asyncMgr = null; - @Inject(adapter = APIAccessChecker.class) - protected Adapters _apiAccessCheckers; + @Inject private final AccountManager _accountMgr = null; + @Inject private final DomainManager _domainMgr = null; + @Inject private final AsyncJobManager _asyncMgr = null; + @Inject private ConfigurationDao _configDao; + @Inject protected List _apiAccessCheckers; private Account _systemAccount = null; private User _systemUser = null; private static int _workerCount = 0; private static ApiServer s_instance = null; private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - private Map> _apiNameCmdClassMap = new HashMap>(); + private final Map> _apiNameCmdClassMap = new HashMap>(); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("ApiServer")); @@ -164,20 +166,13 @@ public class ApiServer implements HttpRequestHandler { public static void initApiServer(String[] apiConfig) { if (s_instance == null) { - //Injecting will create ApiServer object with all its - //vars injected as well, no need to do the following: - //s_instance = new ApiServer(); - s_instance = ComponentLocator.inject(ApiServer.class); + s_instance = new ApiServer(); + s_instance = ComponentContext.inject(s_instance); s_instance.init(apiConfig); } } public static ApiServer getInstance() { - // Assumption: CloudStartupServlet would initialize ApiServer - // initApiServer(null); - if (s_instance == null) { - s_logger.fatal("ApiServer instance failed to initialize"); - } return s_instance; } @@ -188,11 +183,9 @@ public class ApiServer implements HttpRequestHandler { _systemAccount = _accountMgr.getSystemAccount(); _systemUser = _accountMgr.getSystemUser(); _dispatcher = ApiDispatcher.getInstance(); - + Integer apiPort = null; // api port, null by default - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - SearchCriteria sc = configDao.createSearchCriteria(); + SearchCriteria sc = _configDao.createSearchCriteria(); sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port"); List values = _configDao.search(sc, null); if ((values != null) && (values.size() > 0)) { @@ -215,8 +208,8 @@ public class ApiServer implements HttpRequestHandler { _apiNameCmdClassMap.put(apiName, cmdClass); } - encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); - String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key()); + encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key())); + String jsonType = _configDao.getValue(Config.JavaScriptDefaultContentType.key()); if (jsonType != null) { jsonContentType = jsonType; } @@ -357,29 +350,29 @@ public class ApiServer implements HttpRequestHandler { } } catch (Exception ex) { if (ex instanceof InvalidParameterValueException) { - InvalidParameterValueException ref = (InvalidParameterValueException)ex; - ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); + InvalidParameterValueException ref = (InvalidParameterValueException)ex; + ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. ArrayList idList = ref.getIdProxyList(); if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - e.addProxyObject(idList.get(i)); - } + // Iterate through entire arraylist and copy over each proxy id. + for (int i = 0 ; i < idList.size(); i++) { + e.addProxyObject(idList.get(i)); + } } // Also copy over the cserror code and the function/layer in which it was thrown. - e.setCSErrorCode(ref.getCSErrorCode()); + e.setCSErrorCode(ref.getCSErrorCode()); throw e; } else if (ex instanceof PermissionDeniedException) { - PermissionDeniedException ref = (PermissionDeniedException)ex; - ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage()); + PermissionDeniedException ref = (PermissionDeniedException)ex; + ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - e.addProxyObject(idList.get(i)); - } + // Iterate through entire arraylist and copy over each proxy id. + for (int i = 0 ; i < idList.size(); i++) { + e.addProxyObject(idList.get(i)); + } } e.setCSErrorCode(ref.getCSErrorCode()); throw e; @@ -514,15 +507,15 @@ public class ApiServer implements HttpRequestHandler { } } - for (ResponseObject response : responses) { + for (ResponseObject response : responses) { if (response.getObjectId() != null && objectJobMap.containsKey(response.getObjectId())) { AsyncJob job = objectJobMap.get(response.getObjectId()); response.setJobId(job.getUuid()); - response.setJobStatus(job.getStatus()); - } + response.setJobStatus(job.getStatus()); } } } + } private void buildAuditTrail(StringBuffer auditTrailSb, String command, String result) { if (result == null) { @@ -553,7 +546,7 @@ public class ApiServer implements HttpRequestHandler { // if userId not null, that mean that user is logged in if (userId != null) { - User user = ApiDBUtils.findUserById(userId); + User user = ApiDBUtils.findUserById(userId); if (!isCommandAvailable(user, commandName)) { s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); @@ -688,7 +681,7 @@ public class ApiServer implements HttpRequestHandler { } return false; } - + public Long fetchDomainId(String domainUUID){ ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); IdentityDao identityDao = locator.getDao(IdentityDao.class); @@ -739,19 +732,19 @@ public class ApiServer implements HttpRequestHandler { if(user.getUuid() != null){ session.setAttribute("user_UUID", user.getUuid()); } - + session.setAttribute("username", userAcct.getUsername()); session.setAttribute("firstname", userAcct.getFirstname()); session.setAttribute("lastname", userAcct.getLastname()); session.setAttribute("accountobj", account); session.setAttribute("account", account.getAccountName()); - + session.setAttribute("domainid", account.getDomainId()); DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId()); if(domain.getUuid() != null){ session.setAttribute("domain_UUID", domain.getUuid()); } - + session.setAttribute("type", Short.valueOf(account.getType()).toString()); session.setAttribute("registrationtoken", userAcct.getRegistrationToken()); session.setAttribute("registered", new Boolean(userAcct.isRegistered()).toString()); @@ -855,8 +848,8 @@ public class ApiServer implements HttpRequestHandler { _params = new BasicHttpParams(); _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) - .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) - .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); + .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) + .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor BasicHttpProcessor httpproc = new BasicHttpProcessor(); @@ -968,41 +961,41 @@ public class ApiServer implements HttpRequestHandler { // Exception. When invoked from ApiServlet's processRequest(), this can be // a standard exception like NumberFormatException. We'll leave the standard ones alone. if (ex != null) { - if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException - || ex instanceof InvalidParameterValueException) { - // Cast the exception appropriately and retrieve the IdentityProxy - if (ex instanceof ServerApiException) { - ServerApiException ref = (ServerApiException) ex; - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - for (int i=0; i < idList.size(); i++) { - apiResponse.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - apiResponse.setCSErrorCode(ref.getCSErrorCode()); - } else if (ex instanceof PermissionDeniedException) { - PermissionDeniedException ref = (PermissionDeniedException) ex; - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - for (int i=0; i < idList.size(); i++) { - apiResponse.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - apiResponse.setCSErrorCode(ref.getCSErrorCode()); - } else if (ex instanceof InvalidParameterValueException) { - InvalidParameterValueException ref = (InvalidParameterValueException) ex; - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - for (int i=0; i < idList.size(); i++) { - apiResponse.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - apiResponse.setCSErrorCode(ref.getCSErrorCode()); - } - } + if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException + || ex instanceof InvalidParameterValueException) { + // Cast the exception appropriately and retrieve the IdentityProxy + if (ex instanceof ServerApiException) { + ServerApiException ref = (ServerApiException) ex; + ArrayList idList = ref.getIdProxyList(); + if (idList != null) { + for (int i=0; i < idList.size(); i++) { + apiResponse.addProxyObject(idList.get(i)); + } + } + // Also copy over the cserror code and the function/layer in which it was thrown. + apiResponse.setCSErrorCode(ref.getCSErrorCode()); + } else if (ex instanceof PermissionDeniedException) { + PermissionDeniedException ref = (PermissionDeniedException) ex; + ArrayList idList = ref.getIdProxyList(); + if (idList != null) { + for (int i=0; i < idList.size(); i++) { + apiResponse.addProxyObject(idList.get(i)); + } + } + // Also copy over the cserror code and the function/layer in which it was thrown. + apiResponse.setCSErrorCode(ref.getCSErrorCode()); + } else if (ex instanceof InvalidParameterValueException) { + InvalidParameterValueException ref = (InvalidParameterValueException) ex; + ArrayList idList = ref.getIdProxyList(); + if (idList != null) { + for (int i=0; i < idList.size(); i++) { + apiResponse.addProxyObject(idList.get(i)); + } + } + // Also copy over the cserror code and the function/layer in which it was thrown. + apiResponse.setCSErrorCode(ref.getCSErrorCode()); + } + } } SerializationContext.current().setUuidTranslation(true); responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType); diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index 6c2411cb7d4..b3dd357c225 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -27,15 +27,15 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import org.apache.cloudstack.api.command.admin.network.ListStorageNetworkIpRangeCmd; import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import com.cloud.dc.HostPodVO; -import com.cloud.dc.StorageNetworkIpRange; import com.cloud.dc.StorageNetworkIpAddressVO; +import com.cloud.dc.StorageNetworkIpRange; import com.cloud.dc.StorageNetworkIpRangeVO; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.StorageNetworkIpAddressDao; @@ -43,12 +43,11 @@ import com.cloud.dc.dao.StorageNetworkIpRangeDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; -import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; +import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteriaService; import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.SecondaryStorageVmVO; @@ -56,329 +55,332 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.SecondaryStorageVmDao; @Component -@Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) +@Local(value = { StorageNetworkManager.class, StorageNetworkService.class }) public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService { - private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); - - String _name; - @Inject - StorageNetworkIpAddressDao _sNwIpDao; - @Inject - StorageNetworkIpRangeDao _sNwIpRangeDao; + private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); + + String _name; + @Inject + StorageNetworkIpAddressDao _sNwIpDao; + @Inject + StorageNetworkIpRangeDao _sNwIpRangeDao; @Inject NetworkDao _networkDao; - @Inject - HostPodDao _podDao; - @Inject - SecondaryStorageVmDao _ssvmDao; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } + @Inject + HostPodDao _podDao; + @Inject + SecondaryStorageVmDao _ssvmDao; - @Override - public boolean start() { - // TODO Auto-generated method stub - return true; - } + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } - @Override - public boolean stop() { - // TODO Auto-generated method stub - return true; - } + @Override + public boolean start() { + // TODO Auto-generated method stub + return true; + } - @Override - public String getName() { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean stop() { + // TODO Auto-generated method stub + return true; + } - private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new CloudRuntimeException("Cannot find pod " + podId); - } - String[] IpRange = pod.getDescription().split("-"); - if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { - return; - } + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new CloudRuntimeException("Cannot find pod " + podId); + } + String[] IpRange = pod.getDescription().split("-"); + if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { + return; + } if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]); } - } - - private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) { - List curRanges = _sNwIpRangeDao.listByPodId(podId); - for (StorageNetworkIpRangeVO range : curRanges) { - if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { - throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp()); - } - } - } - - private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException { + } + + private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) { + List curRanges = _sNwIpRangeDao.listByPodId(podId); + for (StorageNetworkIpRangeVO range : curRanges) { + if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { + throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp()); + } + } + } + + private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException { long startIPLong = NetUtils.ip2Long(startIp); long endIPLong = NetUtils.ip2Long(endIp); - String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; - String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; - PreparedStatement stmt = null; - Connection conn = txn.getConnection(); - - while (startIPLong <= endIPLong) { - stmt = conn.prepareStatement(insertSql); - stmt.setLong(1, rangeId); - stmt.setString(2, NetUtils.long2Ip(startIPLong++)); - stmt.setLong(3, zoneId); - stmt.setNull(4, java.sql.Types.DATE); + String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; + String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; + PreparedStatement stmt = null; + Connection conn = txn.getConnection(); + + while (startIPLong <= endIPLong) { + stmt = conn.prepareStatement(insertSql); + stmt.setLong(1, rangeId); + stmt.setString(2, NetUtils.long2Ip(startIPLong++)); + stmt.setLong(3, zoneId); + stmt.setNull(4, java.sql.Types.DATE); stmt.executeUpdate(); stmt.close(); - + stmt = txn.prepareStatement(updateSql); stmt.setLong(1, zoneId); stmt.executeUpdate(); stmt.close(); } - } - - @Override - @DB + } + + @Override + @DB public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) { - Integer vlan = cmd.getVlan(); - Long rangeId = cmd.getId(); - String startIp = cmd.getStartIp(); - String endIp = cmd.getEndIp(); - String netmask = cmd.getNetmask(); - - if (netmask != null && !NetUtils.isValidNetmask(netmask)) { - throw new CloudRuntimeException("Invalid netmask:" + netmask); - } - - if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { - throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); - } - - StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); - if (range == null) { - throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); - } - - if (startIp != null || endIp != null) { - long podId = range.getPodId(); - startIp = startIp == null ? range.getStartIp() : startIp; - endIp = endIp == null ? range.getEndIp() : endIp; - checkOverlapPrivateIpRange(podId, startIp, endIp); - checkOverlapStorageIpRange(podId, startIp, endIp); - } - - Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - range = _sNwIpRangeDao.acquireInLockTable(range.getId()); - if (range == null) { - throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); - } - StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); - if (vlan != null) { - vo.setVlan(vlan); - } - if (startIp != null) { - vo.setStartIp(startIp); - } - if (endIp != null) { - vo.setEndIp(endIp); - } - if (netmask != null) { - vo.setNetmask(netmask); - } - _sNwIpRangeDao.update(rangeId, vo); - } finally { - if (range != null) { - _sNwIpRangeDao.releaseFromLockTable(range.getId()); - } - } - txn.commit(); - - return _sNwIpRangeDao.findById(rangeId); + Integer vlan = cmd.getVlan(); + Long rangeId = cmd.getId(); + String startIp = cmd.getStartIp(); + String endIp = cmd.getEndIp(); + String netmask = cmd.getNetmask(); + + if (netmask != null && !NetUtils.isValidNetmask(netmask)) { + throw new CloudRuntimeException("Invalid netmask:" + netmask); + } + + if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { + throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); + } + + StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); + if (range == null) { + throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); + } + + if (startIp != null || endIp != null) { + long podId = range.getPodId(); + startIp = startIp == null ? range.getStartIp() : startIp; + endIp = endIp == null ? range.getEndIp() : endIp; + checkOverlapPrivateIpRange(podId, startIp, endIp); + checkOverlapStorageIpRange(podId, startIp, endIp); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + range = _sNwIpRangeDao.acquireInLockTable(range.getId()); + if (range == null) { + throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); + } + StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); + if (vlan != null) { + vo.setVlan(vlan); + } + if (startIp != null) { + vo.setStartIp(startIp); + } + if (endIp != null) { + vo.setEndIp(endIp); + } + if (netmask != null) { + vo.setNetmask(netmask); + } + _sNwIpRangeDao.update(rangeId, vo); + } finally { + if (range != null) { + _sNwIpRangeDao.releaseFromLockTable(range.getId()); + } + } + txn.commit(); + + return _sNwIpRangeDao.findById(rangeId); } - - @Override - @DB - public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { - Long podId = cmd.getPodId(); - String startIp = cmd.getStartIp(); - String endIp = cmd.getEndIp(); - Integer vlan = cmd.getVlan(); - String netmask = cmd.getNetmask(); - if (endIp == null) { - endIp = startIp; - } - - if (!NetUtils.isValidNetmask(netmask)) { - throw new CloudRuntimeException("Invalid netmask:" + netmask); - } - - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new CloudRuntimeException("Cannot find pod " + podId); - } - Long zoneId = pod.getDataCenterId(); - - List nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); - if (nws.size() == 0) { - throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); - } - if (nws.size() > 1) { - throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); - } - NetworkVO nw = nws.get(0); - - checkOverlapPrivateIpRange(podId, startIp, endIp); - checkOverlapStorageIpRange(podId, startIp, endIp); + @Override + @DB + public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { + Long podId = cmd.getPodId(); + String startIp = cmd.getStartIp(); + String endIp = cmd.getEndIp(); + Integer vlan = cmd.getVlan(); + String netmask = cmd.getNetmask(); - Transaction txn = Transaction.currentTxn(); - StorageNetworkIpRangeVO range = null; + if (endIp == null) { + endIp = startIp; + } - txn.start(); - range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); - _sNwIpRangeDao.persist(range); - try { - createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); - } catch (SQLException e) { - txn.rollback(); - StringBuilder err = new StringBuilder(); - err.append("Create storage network range failed."); - err.append("startIp=" + startIp); - err.append("endIp=" + endIp); - err.append("netmask=" + netmask); - err.append("zoneId=" + zoneId); - s_logger.debug(err.toString(), e); - throw e; - } + if (!NetUtils.isValidNetmask(netmask)) { + throw new CloudRuntimeException("Invalid netmask:" + netmask); + } - txn.commit(); - - return range; - } - - private String getInUseIpAddress(long rangeId) { - List ips = _sNwIpDao.listInUseIpByRangeId(rangeId); - StringBuilder res = new StringBuilder(); - res.append("Below IP of range " + rangeId + " is still in use:"); - for (String ip : ips) { - res.append(ip).append(","); - } - return res.toString(); - } - - @Override - @DB + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new CloudRuntimeException("Cannot find pod " + podId); + } + Long zoneId = pod.getDataCenterId(); + + List nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); + if (nws.size() == 0) { + throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); + } + if (nws.size() > 1) { + throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); + } + NetworkVO nw = nws.get(0); + + checkOverlapPrivateIpRange(podId, startIp, endIp); + checkOverlapStorageIpRange(podId, startIp, endIp); + + Transaction txn = Transaction.currentTxn(); + StorageNetworkIpRangeVO range = null; + + txn.start(); + range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); + _sNwIpRangeDao.persist(range); + try { + createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); + } catch (SQLException e) { + txn.rollback(); + StringBuilder err = new StringBuilder(); + err.append("Create storage network range failed."); + err.append("startIp=" + startIp); + err.append("endIp=" + endIp); + err.append("netmask=" + netmask); + err.append("zoneId=" + zoneId); + s_logger.debug(err.toString(), e); + throw e; + } + + txn.commit(); + + return range; + } + + private String getInUseIpAddress(long rangeId) { + List ips = _sNwIpDao.listInUseIpByRangeId(rangeId); + StringBuilder res = new StringBuilder(); + res.append("Below IP of range " + rangeId + " is still in use:"); + for (String ip : ips) { + res.append(ip).append(","); + } + return res.toString(); + } + + @Override + @DB public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) { - long rangeId = cmd.getId(); - StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); - if (range == null) { - throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); - } - - if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { - throw new CloudRuntimeException(getInUseIpAddress(rangeId)); - } + long rangeId = cmd.getId(); + StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); + if (range == null) { + throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); + } - final Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - range = _sNwIpRangeDao.acquireInLockTable(rangeId); - if (range == null) { - String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; - s_logger.warn(msg); - throw new CloudRuntimeException(msg); - } - /* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */ - _sNwIpRangeDao.remove(rangeId); - } finally { - if (range != null) { - _sNwIpRangeDao.releaseFromLockTable(rangeId); - } - } - txn.commit(); - } - - @Override + if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { + throw new CloudRuntimeException(getInUseIpAddress(rangeId)); + } + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + range = _sNwIpRangeDao.acquireInLockTable(rangeId); + if (range == null) { + String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; + s_logger.warn(msg); + throw new CloudRuntimeException(msg); + } + /* + * entries in op_dc_storage_network_ip_address will be deleted automatically due to + * fk_storage_ip_address__range_id constraint key + */ + _sNwIpRangeDao.remove(rangeId); + } finally { + if (range != null) { + _sNwIpRangeDao.releaseFromLockTable(rangeId); + } + } + txn.commit(); + } + + @Override public List listIpRange(ListStorageNetworkIpRangeCmd cmd) { - Long rangeId = cmd.getRangeId(); - Long podId = cmd.getPodId(); - Long zoneId = cmd.getZoneId(); - - List result = null; - if (rangeId != null) { - result = _sNwIpRangeDao.listByRangeId(rangeId); - } else if (podId != null) { - result = _sNwIpRangeDao.listByPodId(podId); - } else if (zoneId != null) { - result = _sNwIpRangeDao.listByDataCenterId(zoneId); - } else { - result = _sNwIpRangeDao.listAll(); - } - - return (List)result; - } + Long rangeId = cmd.getRangeId(); + Long podId = cmd.getPodId(); + Long zoneId = cmd.getZoneId(); - @Override - public void releaseIpAddress(String ip) { - _sNwIpDao.releaseIpAddress(ip); - } - - @Override + List result = null; + if (rangeId != null) { + result = _sNwIpRangeDao.listByRangeId(rangeId); + } else if (podId != null) { + result = _sNwIpRangeDao.listByPodId(podId); + } else if (zoneId != null) { + result = _sNwIpRangeDao.listByDataCenterId(zoneId); + } else { + result = _sNwIpRangeDao.listAll(); + } + + return result; + } + + @Override + public void releaseIpAddress(String ip) { + _sNwIpDao.releaseIpAddress(ip); + } + + @Override public StorageNetworkIpAddressVO acquireIpAddress(long podId) { - List ranges = _sNwIpRangeDao.listByPodId(podId); - for (StorageNetworkIpRangeVO r : ranges) { - try { - r = _sNwIpRangeDao.acquireInLockTable(r.getId()); - if (r == null) { - String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; - s_logger.warn(msg); - throw new CloudRuntimeException(msg); - } - - StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); - if (ip != null) { - return ip; - } - } finally { - if (r != null) { - _sNwIpRangeDao.releaseFromLockTable(r.getId()); - } - } - } - - return null; + List ranges = _sNwIpRangeDao.listByPodId(podId); + for (StorageNetworkIpRangeVO r : ranges) { + try { + r = _sNwIpRangeDao.acquireInLockTable(r.getId()); + if (r == null) { + String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; + s_logger.warn(msg); + throw new CloudRuntimeException(msg); + } + + StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); + if (ip != null) { + return ip; + } + } finally { + if (r != null) { + _sNwIpRangeDao.releaseFromLockTable(r.getId()); + } + } + } + + return null; } - @Override + @Override public boolean isStorageIpRangeAvailable(long zoneId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); - List entries = sc.list(); - return entries.size() > 0; + SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); + List entries = sc.list(); + return entries.size() > 0; } - @Override + @Override public List getSSVMWithNoStorageNetwork(long zoneId) { - List ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); - return ssvms; + List ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); + return ssvms; } - @Override + @Override public boolean isAnyStorageIpInUseInZone(long zoneId) { - List ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); - for (StorageNetworkIpRangeVO r : ranges) { - if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { - return true; - } - } - return false; + List ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); + for (StorageNetworkIpRangeVO r : ranges) { + if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { + return true; + } + } + return false; } } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index c6440c3efa2..c3559b6c67f 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -22,10 +22,11 @@ import java.util.Random; import javax.annotation.PostConstruct; import javax.ejb.Local; -import javax.inject.Inject; import javax.persistence.TableGenerator; import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.springframework.stereotype.Component; + import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; @@ -61,21 +62,21 @@ import com.cloud.utils.net.NetUtils; @Local(value = NetworkDao.class) @DB(txn = false) public class NetworkDaoImpl extends GenericDaoBase implements NetworkDao { - final SearchBuilder AllFieldsSearch; - final SearchBuilder AccountSearch; - final SearchBuilder RelatedConfigSearch; - final SearchBuilder AccountNetworkSearch; - final SearchBuilder ZoneBroadcastUriSearch; - final SearchBuilder ZoneSecurityGroupSearch; - final GenericSearchBuilder CountBy; - final SearchBuilder PhysicalNetworkSearch; - final SearchBuilder SecurityGroupSearch; - final GenericSearchBuilder NetworksRegularUserCanCreateSearch; - private final GenericSearchBuilder NetworksCount; - final SearchBuilder SourceNATSearch; - final GenericSearchBuilder CountByZoneAndURI; - final GenericSearchBuilder VpcNetworksCount; - final SearchBuilder OfferingAccountNetworkSearch; + SearchBuilder AllFieldsSearch; + SearchBuilder AccountSearch; + SearchBuilder RelatedConfigSearch; + SearchBuilder AccountNetworkSearch; + SearchBuilder ZoneBroadcastUriSearch; + SearchBuilder ZoneSecurityGroupSearch; + GenericSearchBuilder CountBy; + SearchBuilder PhysicalNetworkSearch; + SearchBuilder SecurityGroupSearch; + GenericSearchBuilder NetworksRegularUserCanCreateSearch; + GenericSearchBuilder NetworksCount; + SearchBuilder SourceNATSearch; + GenericSearchBuilder CountByZoneAndURI; + GenericSearchBuilder VpcNetworksCount; + SearchBuilder OfferingAccountNetworkSearch; ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); @@ -85,13 +86,13 @@ public class NetworkDaoImpl extends GenericDaoBase implements N NetworkOfferingDaoImpl _ntwkOffDao = ComponentLocator.inject(NetworkOfferingDaoImpl.class); - final TableGenerator _tgMacAddress; + TableGenerator _tgMacAddress; Random _rand = new Random(System.currentTimeMillis()); long _prefix = 0x2; public NetworkDaoImpl() { } - + @PostConstruct protected void init() { AllFieldsSearch = createSearchBuilder(); @@ -150,7 +151,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N CountByZoneAndURI.and("guestType", CountByZoneAndURI.entity().getGuestType(), Op.EQ); CountByZoneAndURI.done(); - + ZoneSecurityGroupSearch = createSearchBuilder(); ZoneSecurityGroupSearch.and("dataCenterId", ZoneSecurityGroupSearch.entity().getDataCenterId(), Op.EQ); SearchBuilder offJoin = _ntwkSvcMap.createSearchBuilder(); @@ -174,12 +175,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N join3.and("service", join3.entity().getService(), Op.EQ); SecurityGroupSearch.join("services", join3, SecurityGroupSearch.entity().getId(), join3.entity().getNetworkId(), JoinBuilder.JoinType.INNER); SecurityGroupSearch.done(); - + NetworksCount = createSearchBuilder(Integer.class); NetworksCount.select(null, Func.COUNT, NetworksCount.entity().getId()); NetworksCount.and("networkOfferingId", NetworksCount.entity().getNetworkOfferingId(), SearchCriteria.Op.EQ); NetworksCount.done(); - + NetworksRegularUserCanCreateSearch = createSearchBuilder(Long.class); NetworksRegularUserCanCreateSearch.and("aclType", NetworksRegularUserCanCreateSearch.entity().getAclType(), Op.EQ); NetworksRegularUserCanCreateSearch.select(null, Func.COUNT, NetworksRegularUserCanCreateSearch.entity().getId()); @@ -193,7 +194,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N NetworksRegularUserCanCreateSearch.done(); _tgMacAddress = _tgs.get("macAddress"); - + SourceNATSearch = createSearchBuilder(); SourceNATSearch.and("account", SourceNATSearch.entity().getAccountId(), Op.EQ); SourceNATSearch.and("datacenter", SourceNATSearch.entity().getDataCenterId(), Op.EQ); @@ -202,7 +203,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N join6.and("service", join6.entity().getService(), Op.EQ); SourceNATSearch.join("services", join6, SourceNATSearch.entity().getId(), join6.entity().getNetworkId(), JoinBuilder.JoinType.INNER); SourceNATSearch.done(); - + VpcNetworksCount = createSearchBuilder(Long.class); VpcNetworksCount.and("vpcId", VpcNetworksCount.entity().getVpcId(), Op.EQ); VpcNetworksCount.select(null, Func.COUNT, VpcNetworksCount.entity().getId()); @@ -229,11 +230,11 @@ public class NetworkDaoImpl extends GenericDaoBase implements N if (type != null) { sc.setParameters("guestType", type); } - + if (isSystem != null) { sc.setJoinParameters("offerings", "isSystem", isSystem); } - + return listBy(sc, null); } @@ -360,7 +361,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N SearchCriteria sc = CountByZoneAndURI.create(); sc.setParameters("dataCenterId", zoneId); sc.setParameters("broadcastUri", broadcastUri); - + return customSearch(sc, null).get(0); } @@ -409,7 +410,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N public void clearCheckForGc(long networkId) { _opDao.clearCheckForGc(networkId); } - + @Override public void setCheckForGc(long networkId) { _opDao.setCheckForGc(networkId); @@ -431,8 +432,8 @@ public class NetworkDaoImpl extends GenericDaoBase implements N NetworkDomainVO domain = new NetworkDomainVO(networkId, domainId, subdomainAccess); _domainsDao.persist(domain); } - - + + @Override public int getNetworkCountByVpcId(long vpcId) { SearchCriteria sc = CountBy.create(); @@ -440,7 +441,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N List results = customSearch(sc, null); return results.get(0); } - + @Override public List listSecurityGroupEnabledNetworks() { @@ -500,7 +501,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N return listBy(sc, null); } - + @Override public int getNetworkCountByNetworkOffId(long networkOfferingId) { SearchCriteria sc = NetworksCount.create(); @@ -508,7 +509,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N List count = customSearch(sc, null); return count.get(0); } - + @Override public long countNetworksUserCanCreate(long ownerId) { SearchCriteria sc = NetworksRegularUserCanCreateSearch.create(); @@ -517,8 +518,8 @@ public class NetworkDaoImpl extends GenericDaoBase implements N sc.setJoinParameters("ntwkOff", "specifyVlan", false); return customSearch(sc, null).get(0); } - - + + @Override public List listSourceNATEnabledNetworks(long accountId, long dataCenterId, Network.GuestType type) { SearchCriteria sc = SourceNATSearch.create(); @@ -528,7 +529,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N sc.setJoinParameters("services", "service", Service.SourceNat.getName()); return listBy(sc); } - + @Override public List listByVpc(long vpcId) { SearchCriteria sc = AllFieldsSearch.create(); @@ -549,6 +550,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N return findOneBy(sc); } + @Override @DB public boolean remove(Long id) { Transaction txn = Transaction.currentTxn(); @@ -585,7 +587,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N public List listRedundantNetworks() { SearchCriteria sc = AllFieldsSearch.create(); sc.setJoinParameters("offerings", "isRedundant", true); - + return listBy(sc, null); } } diff --git a/server/src/com/cloud/network/rules/FirewallRuleVO.java b/server/src/com/cloud/network/rules/FirewallRuleVO.java index 99140c3d6f6..8ef5067de33 100644 --- a/server/src/com/cloud/network/rules/FirewallRuleVO.java +++ b/server/src/com/cloud/network/rules/FirewallRuleVO.java @@ -35,18 +35,16 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.persistence.Transient; -import org.apache.cloudstack.api.Identity; -import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; +import com.cloud.network.dao.FirewallRulesCidrsDao; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.NetUtils; -import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="firewall_rules") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32) public class FirewallRuleVO implements FirewallRule { - protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); + @Inject protected FirewallRulesCidrsDao _firewallRulesCidrsDao; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index ab7b7b126cb..00b7716f19c 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -38,10 +38,10 @@ import javax.mail.URLName; import javax.mail.internet.InternetAddress; import javax.naming.ConfigurationException; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.api.query.dao.ProjectAccountJoinDao; import com.cloud.api.query.dao.ProjectInvitationJoinDao; import com.cloud.api.query.dao.ProjectJoinDao; @@ -73,7 +73,6 @@ import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; @@ -89,7 +88,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ public static final Logger s_logger = Logger.getLogger(ProjectManagerImpl.class); private String _name; private EmailInvite _emailInvite; - + @Inject private DomainDao _domainDao; @Inject @@ -118,24 +117,24 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ private ProjectInvitationJoinDao _projectInvitationJoinDao; @Inject protected ResourceTagDao _resourceTagDao; - + protected boolean _invitationRequired = false; protected long _invitationTimeOut = 86400000; protected boolean _allowUserToCreateProject = true; protected ScheduledExecutorService _executor; protected int _projectCleanupExpInvInterval = 60; //Interval defining how often project invitation cleanup thread is running - - + + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; - + Map configs = _configDao.getConfiguration(params); _invitationRequired = Boolean.valueOf(configs.get(Config.ProjectInviteRequired.key())); _invitationTimeOut = Long.valueOf(configs.get(Config.ProjectInvitationExpirationTime.key()))*1000; _allowUserToCreateProject = Boolean.valueOf(configs.get(Config.AllowUserToCreateProject.key())); - - + + // set up the email system for project invitations String smtpHost = configs.get("project.smtp.host"); @@ -153,13 +152,13 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _emailInvite = new EmailInvite(smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Project-ExpireInvitations")); - + return true; } - + @Override public boolean start() { - _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); + _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); return true; } @@ -172,98 +171,98 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ public String getName() { return _name; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", create=true) @DB public Project createProject(String name, String displayText, String accountName, Long domainId) throws ResourceAllocationException{ Account caller = UserContext.current().getCaller(); Account owner = caller; - + //check if the user authorized to create the project if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && !_allowUserToCreateProject) { - throw new PermissionDeniedException("Regular user is not permitted to create a project"); + throw new PermissionDeniedException("Regular user is not permitted to create a project"); } - + //Verify request parameters if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { throw new InvalidParameterValueException("Account name and domain id must be specified together"); } - + if (accountName != null) { owner = _accountMgr.finalizeOwner(caller, accountName, domainId, null); } - + //don't allow 2 projects with the same name inside the same domain if (_projectDao.findByNameAndDomain(name, owner.getDomainId()) != null) { throw new InvalidParameterValueException("Project with name " + name + " already exists in domain id=" + owner.getDomainId()); } - + //do resource limit check _resourceLimitMgr.checkResourceLimit(owner, ResourceType.project); - + Transaction txn = Transaction.currentTxn(); txn.start(); - + //Create an account associated with the project StringBuilder acctNm = new StringBuilder("PrjAcct-"); acctNm.append(name).append("-").append(owner.getDomainId()); - + Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, domainId, null, null); - + Project project = _projectDao.persist(new ProjectVO(name, displayText, owner.getDomainId(), projectAccount.getId())); - + //assign owner to the project assignAccountToProject(project, owner.getId(), ProjectAccount.Role.Admin); - + if (project != null) { UserContext.current().setEventDetails("Project id=" + project.getId()); } - + //Increment resource count _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.project); - + txn.commit(); - + return project; } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", async=true) @DB public Project enableProject(long projectId){ Account caller = UserContext.current().getCaller(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - + _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //at this point enabling project doesn't require anything, so just update the state project.setState(State.Active); _projectDao.update(projectId, project); - + return project; } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true) public boolean deleteProject(long projectId) { UserContext ctx = UserContext.current(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - + _accountMgr.checkAccess(ctx.getCaller(),AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + return deleteProject(ctx.getCaller(), ctx.getCallerUserId(), project); } @@ -281,9 +280,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (projectOwner != null) { _resourceLimitMgr.decrementResourceCount(projectOwner.getId(), ResourceType.project); } - + txn.commit(); - + if (updateResult) { //pass system caller when clenaup projects account if (!cleanupProject(project, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), User.UID_SYSTEM)) { @@ -297,31 +296,31 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + @DB private boolean cleanupProject(Project project, AccountVO caller, Long callerUserId) { boolean result=true; //Delete project's account AccountVO account = _accountDao.findById(project.getProjectAccountId()); s_logger.debug("Deleting projects " + project + " internal account id=" + account.getId() + " as a part of project cleanup..."); - + result = result && _accountMgr.deleteAccount(account, callerUserId, caller); - + if (result) { //Unassign all users from the project - + Transaction txn = Transaction.currentTxn(); txn.start(); - + s_logger.debug("Unassigning all accounts from project " + project + " as a part of project cleanup..."); List projectAccounts = _projectAccountDao.listByProjectId(project.getId()); for (ProjectAccount projectAccount : projectAccounts) { result = result && unassignAccountFromProject(projectAccount.getProjectId(), projectAccount.getAccountId()); } - + s_logger.debug("Removing all invitations for the project " + project + " as a part of project cleanup..."); - _projectInvitationDao.cleanupInvitations(project.getId()); - + _projectInvitationDao.cleanupInvitations(project.getId()); + txn.commit(); if (result) { s_logger.debug("Accounts are unassign successfully from project " + project + " as a part of project cleanup..."); @@ -329,10 +328,10 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { s_logger.warn("Failed to cleanup project's internal account"); } - + return result; } - + @Override public boolean unassignAccountFromProject(long projectId, long accountId) { ProjectAccountVO projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); @@ -340,7 +339,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ s_logger.debug("Account id=" + accountId + " is not assigned to project id=" + projectId + " so no need to unassign"); return true; } - + if ( _projectAccountDao.remove(projectAccount.getId())) { return true; } else { @@ -348,34 +347,34 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + @Override public ProjectVO getProject (long projectId) { return _projectDao.findById(projectId); } - - + + @Override public long getInvitationTimeout() { return _invitationTimeOut; - } - - + } + + @Override public ProjectAccount assignAccountToProject(Project project, long accountId, ProjectAccount.Role accountRole) { return _projectAccountDao.persist(new ProjectAccountVO(project, accountId, accountRole)); } - + @Override @DB public boolean deleteAccountFromProject(long projectId, long accountId) { boolean success = true; Transaction txn = Transaction.currentTxn(); txn.start(); - + //remove account ProjectAccountVO projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); success = _projectAccountDao.remove(projectAccount.getId()); - + //remove all invitations for account if (success) { s_logger.debug("Removed account " + accountId + " from project " + projectId + " , cleaning up old invitations for account/project..."); @@ -384,36 +383,36 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ success = success && _projectInvitationDao.remove(invite.getId()); } } - + txn.commit(); return success; } - + @Override public Account getProjectOwner(long projectId) { ProjectAccount prAcct = _projectAccountDao.getProjectOwner(projectId); if (prAcct != null) { return _accountMgr.getAccount(prAcct.getAccountId()); } - + return null; } - + @Override public ProjectVO findByProjectAccountId(long projectAccountId) { return _projectDao.findByProjectAccountId(projectAccountId); } - + @Override public ProjectVO findByProjectAccountIdIncludingRemoved(long projectAccountId) { return _projectDao.findByProjectAccountIdIncludingRemoved(projectAccountId); } - + @Override public Project findByNameAndDomainId(String name, long domainId) { return _projectDao.findByNameAndDomain(name, domainId); } - + @Override public boolean canAccessProjectAccount(Account caller, long accountId) { //ROOT admin always can access the project @@ -424,10 +423,11 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _accountMgr.checkAccess(caller, _domainDao.findById(owner.getDomainId())); return true; } - + return _projectAccountDao.canAccessProjectAccount(caller.getId(), accountId); } - + + @Override public boolean canModifyProjectAccount(Account caller, long accountId) { //ROOT admin always can access the project if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { @@ -439,29 +439,29 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return _projectAccountDao.canModifyProjectAccount(caller.getId(), accountId); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_UPDATE, eventDescription = "updating project", async=true) public Project updateProject(long projectId, String displayText, String newOwnerName) throws ResourceAllocationException{ Account caller = UserContext.current().getCaller(); - + //check that the project exists ProjectVO project = getProject(projectId); - + if (project == null) { throw new InvalidParameterValueException("Unable to find the project id=" + projectId); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + Transaction txn = Transaction.currentTxn(); txn.start(); if (displayText != null) { project.setDisplayText(displayText); _projectDao.update(projectId, project); } - + if (newOwnerName != null) { //check that the new owner exists Account futureOwnerAccount = _accountMgr.getActiveAccountByName(newOwnerName, project.getDomainId()); @@ -474,68 +474,68 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (futureOwner == null) { throw new InvalidParameterValueException("Account " + newOwnerName + " doesn't belong to the project. Add it to the project first and then change the project's ownership"); } - + //do resource limit check _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(futureOwnerAccount.getId()), ResourceType.project); - + //unset the role for the old owner ProjectAccountVO currentOwner = _projectAccountDao.findByProjectIdAccountId(projectId, currentOwnerAccount.getId()); currentOwner.setAccountRole(Role.Regular); _projectAccountDao.update(currentOwner.getId(), currentOwner); _resourceLimitMgr.decrementResourceCount(currentOwnerAccount.getId(), ResourceType.project); - + //set new owner futureOwner.setAccountRole(Role.Admin); _projectAccountDao.update(futureOwner.getId(), futureOwner); _resourceLimitMgr.incrementResourceCount(futureOwnerAccount.getId(), ResourceType.project); - + } else { s_logger.trace("Future owner " + newOwnerName + "is already the owner of the project id=" + projectId); } } - + txn.commit(); - + return _projectDao.findById(projectId); - + } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACCOUNT_ADD, eventDescription = "adding account to project", async=true) public boolean addAccountToProject(long projectId, String accountName, String email) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //User can be added to Active project only if (project.getState() != Project.State.Active) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't add account to the specified project id in state=" + project.getState() + " as it's no longer active"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Can't add account to the specified project id in state=" + project.getState() + " as it's no longer active"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //check that account-to-add exists Account account = null; if (accountName != null) { account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in specified domain id"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in specified domain id"); // We don't have a DomainVO object with us, so just pass the tablename "domain" manually. ex.addProxyObject("domain", project.getDomainId(), "domainId"); throw ex; } - + //verify permissions - only project owner can assign _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //Check if the account already added to the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); if (projectAccount != null) { @@ -543,7 +543,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return true; } } - + if (_invitationRequired) { return inviteAccountToProject(project, account, email); } else { @@ -558,7 +558,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } } - + private boolean inviteAccountToProject(Project project, Account account, String email) { if (account != null) { if (createAccountInvitation(project, account.getId()) != null) { @@ -568,94 +568,94 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + if (email != null) { //generate the token String token = generateToken(10); if (generateTokenBasedInvitation(project, email, token) != null) { return true; } else { - s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project); - return false; + s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project); + return false; } } - + return false; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE, eventDescription = "removing account from project", async=true) public boolean deleteAccountFromProject(long projectId, String accountName) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //check that account-to-remove exists Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); // Since we don't have a domainVO object, pass the table name manually. ex.addProxyObject("domain", project.getDomainId(), "domainId"); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //Check if the account exists in the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); if (projectAccount == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id"); - // Use the projectVO object and not the projectAccount object to inject the projectId. - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id"); + // Use the projectVO object and not the projectAccount object to inject the projectId. + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //can't remove the owner of the project if (projectAccount.getAccountRole() == Role.Admin) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to delete account " + accountName + " from the project with specified id as the account is the owner of the project"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to delete account " + accountName + " from the project with specified id as the account is the owner of the project"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + return deleteAccountFromProject(projectId, account.getId()); } - - - - + + + + public ProjectInvitation createAccountInvitation(Project project, Long accountId) { if (activeInviteExists(project, accountId, null)) { throw new InvalidParameterValueException("There is already a pending invitation for account id=" + accountId + " to the project id=" + project); } - + ProjectInvitation invitation= _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), accountId, project.getDomainId(), null, null)); - + return invitation; } @DB - public boolean activeInviteExists(Project project, Long accountId, String email) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - //verify if the invitation was already generated - ProjectInvitationVO invite = null; - if (accountId != null) { - invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId()); - } else if (email != null) { - invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); - } - + public boolean activeInviteExists(Project project, Long accountId, String email) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + //verify if the invitation was already generated + ProjectInvitationVO invite = null; + if (accountId != null) { + invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId()); + } else if (email != null) { + invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); + } + if (invite != null) { if (invite.getState() == ProjectInvitation.State.Completed || (invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) { - return true; + return true; } else { if (invite.getState() == ProjectInvitation.State.Pending) { expireInvitation(invite); @@ -664,7 +664,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (accountId != null) { s_logger.debug("Removing invitation in state " + invite.getState() + " for account id=" + accountId + " to project " + project); } else if (email != null) { - s_logger.debug("Removing invitation in state " + invite.getState() + " for email " + email + " to project " + project); + s_logger.debug("Removing invitation in state " + invite.getState() + " for email " + email + " to project " + project); } _projectInvitationDao.expunge(invite.getId()); @@ -672,14 +672,14 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } txn.commit(); return false; - } - + } + public ProjectInvitation generateTokenBasedInvitation(Project project, String email, String token) { //verify if the invitation was already generated - if (activeInviteExists(project, null, email)) { - throw new InvalidParameterValueException("There is already a pending invitation for email " + email + " to the project id=" + project); - } - + if (activeInviteExists(project, null, email)) { + throw new InvalidParameterValueException("There is already a pending invitation for email " + email + " to the project id=" + project); + } + ProjectInvitation projectInvitation = _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), null, project.getDomainId(), email, token)); try { _emailInvite.sendInvite(token, email, project.getId()); @@ -688,52 +688,52 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _projectInvitationDao.remove(projectInvitation.getId()); return null; } - + return projectInvitation; } - + private boolean expireInvitation(ProjectInvitationVO invite) { s_logger.debug("Expiring invitation id=" + invite.getId()); invite.setState(ProjectInvitation.State.Expired); return _projectInvitationDao.update(invite.getId(), invite); } - - + + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_UPDATE, eventDescription = "updating project invitation", async=true) public boolean updateInvitation(long projectId, String accountName, String token, boolean accept) { Account caller = UserContext.current().getCaller(); Long accountId = null; boolean result = true; - + //if accountname and token are null, default accountname to caller's account name if (accountName == null && token == null) { accountName = caller.getAccountName(); } - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { throw new InvalidParameterValueException("Unable to find the project id=" + projectId); } - + if (accountName != null) { //check that account-to-remove exists Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); } - + //verify permissions _accountMgr.checkAccess(caller, null, true, account); - + accountId = account.getId(); } else { accountId = caller.getId(); } - + //check that invitation exists ProjectInvitationVO invite = null; if (token == null) { @@ -741,7 +741,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { invite = _projectInvitationDao.findPendingByTokenAndProjectId(token, projectId, ProjectInvitation.State.Pending); } - + if (invite != null) { if (!_projectInvitationDao.isActive(invite.getId(), _invitationTimeOut) && accept) { expireInvitation(invite); @@ -749,116 +749,116 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { Transaction txn = Transaction.currentTxn(); txn.start(); - + ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined; - - //update invitation - s_logger.debug("Marking invitation " + invite + " with state " + newState); - invite.setState(newState); - result = _projectInvitationDao.update(invite.getId(), invite); - - if (result && accept) { - //check if account already exists for the project (was added before invitation got accepted) - ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); - if (projectAccount != null) { - s_logger.debug("Account " + accountName + " already added to the project id=" + projectId); - } else { - assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); - } - } else { - s_logger.warn("Failed to update project invitation " + invite + " with state " + newState); - } - - txn.commit(); + + //update invitation + s_logger.debug("Marking invitation " + invite + " with state " + newState); + invite.setState(newState); + result = _projectInvitationDao.update(invite.getId(), invite); + + if (result && accept) { + //check if account already exists for the project (was added before invitation got accepted) + ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); + if (projectAccount != null) { + s_logger.debug("Account " + accountName + " already added to the project id=" + projectId); + } else { + assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); + } + } else { + s_logger.warn("Failed to update project invitation " + invite + " with state " + newState); + } + + txn.commit(); } } else { throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId); } - + return result; } - + @Override public List listPermittedProjectAccounts(long accountId) { return _projectAccountDao.listPermittedAccountIds(accountId); } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACTIVATE, eventDescription = "activating project") @DB public Project activateProject(long projectId) { Account caller = UserContext.current().getCaller(); - + //check that the project exists ProjectVO project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //allow project activation only when it's in Suspended state Project.State currentState = project.getState(); - + if (currentState == State.Active) { s_logger.debug("The project id=" + projectId + " is already active, no need to activate it again"); return project; } - + if (currentState != State.Suspended) { throw new InvalidParameterValueException("Can't activate the project in " + currentState + " state"); } - + Transaction txn = Transaction.currentTxn(); txn.start(); - + project.setState(Project.State.Active); _projectDao.update(projectId, project); - + _accountMgr.enableAccount(project.getProjectAccountId()); - + txn.commit(); - + return _projectDao.findById(projectId); } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_SUSPEND, eventDescription = "suspending project", async = true) public Project suspendProject (long projectId) throws ConcurrentOperationException, ResourceUnavailableException { Account caller = UserContext.current().getCaller(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + if (suspendProject(project)) { s_logger.debug("Successfully suspended project id=" + projectId); return _projectDao.findById(projectId); } else { - CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + } - + private boolean suspendProject(ProjectVO project) throws ConcurrentOperationException, ResourceUnavailableException { - + s_logger.debug("Marking project " + project + " with state " + State.Suspended + " as a part of project suspend..."); project.setState(State.Suspended); boolean updateResult = _projectDao.update(project.getId(), project); - + if (updateResult) { long projectAccountId = project.getProjectAccountId(); if (!_accountMgr.disableAccount(projectAccountId)) { @@ -869,8 +869,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return true; } - - + + public static String generateToken(int length) { String charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random rand = new Random(System.currentTimeMillis()); @@ -881,7 +881,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return sb.toString(); } - + class EmailInvite { private Session _smtpSession; private final String _smtpHost; @@ -941,9 +941,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ s_logger.error("Exception creating address for: " + email, ex); } } - + String content = "You've been invited to join the CloudStack project id=" + projectId + ". Please use token " + token + " to complete registration"; - + SMTPMessage msg = new SMTPMessage(_smtpSession); msg.setSender(new InternetAddress(_emailSender, _emailSender)); msg.setFrom(new InternetAddress(_emailSender, _emailSender)); @@ -967,24 +967,24 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } } - - + + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_REMOVE, eventDescription = "removing project invitation", async=true) public boolean deleteProjectInvitation(long id) { Account caller = UserContext.current().getCaller(); - + ProjectInvitation invitation = _projectInvitationDao.findById(id); if (invitation == null) { throw new InvalidParameterValueException("Unable to find project invitation by id " + id); } - + //check that the project exists Project project = getProject(invitation.getProjectId()); - + //check permissions - only project owner can remove the invitations _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + if (_projectInvitationDao.remove(id)) { s_logger.debug("Project Invitation id=" + id + " is removed"); return true; @@ -993,35 +993,35 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + public class ExpiredInvitationsCleanup implements Runnable { - @Override - public void run() { - try { - TimeZone.getDefault(); - List invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut); - if (!invitationsToExpire.isEmpty()) { - s_logger.debug("Found " + invitationsToExpire.size() + " projects to expire"); - for (ProjectInvitationVO invitationToExpire : invitationsToExpire) { - invitationToExpire.setState(ProjectInvitation.State.Expired); - _projectInvitationDao.update(invitationToExpire.getId(), invitationToExpire); - s_logger.trace("Expired project invitation id=" + invitationToExpire.getId()); - } - } - } catch (Exception ex) { - s_logger.warn("Exception while running expired invitations cleanup", ex); - } - } + @Override + public void run() { + try { + TimeZone.getDefault(); + List invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut); + if (!invitationsToExpire.isEmpty()) { + s_logger.debug("Found " + invitationsToExpire.size() + " projects to expire"); + for (ProjectInvitationVO invitationToExpire : invitationsToExpire) { + invitationToExpire.setState(ProjectInvitation.State.Expired); + _projectInvitationDao.update(invitationToExpire.getId(), invitationToExpire); + s_logger.trace("Expired project invitation id=" + invitationToExpire.getId()); + } + } + } catch (Exception ex) { + s_logger.warn("Exception while running expired invitations cleanup", ex); + } + } } @Override - public boolean projectInviteRequired() { - return _invitationRequired; - } + public boolean projectInviteRequired() { + return _invitationRequired; + } @Override public boolean allowUserToCreateProject() { - return _allowUserToCreateProject; + return _allowUserToCreateProject; } - + } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 28f28cb4b60..4999ffefb0b 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -16,6 +16,35 @@ // under the License. package com.cloud.server; +import java.io.DataInputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.security.NoSuchAlgorithmException; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; +import java.util.regex.Pattern; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.inject.Inject; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.Resource; @@ -45,7 +74,11 @@ import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; -import com.cloud.network.guru.*; +import com.cloud.network.guru.ControlNetworkGuru; +import com.cloud.network.guru.DirectPodBasedNetworkGuru; +import com.cloud.network.guru.PodBasedNetworkGuru; +import com.cloud.network.guru.PublicNetworkGuru; +import com.cloud.network.guru.StorageNetworkGuru; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offerings.NetworkOfferingServiceMapVO; @@ -63,7 +96,6 @@ import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; @@ -71,20 +103,6 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; import com.cloud.uuididentity.dao.IdentityDao; -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.io.*; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.NoSuchAlgorithmException; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; -import java.util.regex.Pattern; @Component public class ConfigurationServerImpl implements ConfigurationServer { @@ -230,7 +248,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { // store the public and private keys in the database updateKeyPairs(); - + // generate a random password for system vm updateSystemvmPassword(); @@ -504,29 +522,29 @@ public class ConfigurationServerImpl implements ConfigurationServer { if (!userid.startsWith("cloud")) { return; } - + if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) { - return; + return; } - String already = _configDao.getValue("system.vm.password"); - if (already == null) { - Transaction txn = Transaction.currentTxn(); - try { - String rpassword = PasswordGenerator.generatePresharedKey(8); - String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " - + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword - + "','randmon password generated each management server starts for system vm')"; - PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); - stmt.executeUpdate(wSql); - s_logger.info("Updated systemvm password in database"); - } catch (SQLException e) { - s_logger.error("Cannot retrieve systemvm password", e); - } - } + String already = _configDao.getValue("system.vm.password"); + if (already == null) { + Transaction txn = Transaction.currentTxn(); + try { + String rpassword = PasswordGenerator.generatePresharedKey(8); + String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword + + "','randmon password generated each management server starts for system vm')"; + PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); + stmt.executeUpdate(wSql); + s_logger.info("Updated systemvm password in database"); + } catch (SQLException e) { + s_logger.error("Cannot retrieve systemvm password", e); + } + } + + } - } - @Override @DB public void updateKeyPairs() { @@ -541,10 +559,10 @@ public class ConfigurationServerImpl implements ConfigurationServer { String already = _configDao.getValue("ssh.privatekey"); String homeDir = null; homeDir = Script.runSimpleBashScript("echo ~" + username); - if (homeDir == null) { + if (homeDir == null) { throw new CloudRuntimeException("Cannot get home directory for account: " + username); } - + if (s_logger.isInfoEnabled()) { s_logger.info("Processing updateKeyPairs"); } @@ -622,11 +640,11 @@ public class ConfigurationServerImpl implements ConfigurationServer { } s_logger.info("Going to update systemvm iso with generated keypairs if needed"); try { - injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); + injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); } catch (CloudRuntimeException e) { - if (!devel) { - throw new CloudRuntimeException(e.getMessage()); - } + if (!devel) { + throw new CloudRuntimeException(e.getMessage()); + } } } @@ -892,7 +910,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedSGNetworkOffering); - + for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); @@ -967,7 +985,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } - + // Offering #6 NetworkOfferingVO defaultNetworkOfferingForVpcNetworks = new NetworkOfferingVO( NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, @@ -978,7 +996,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultNetworkOfferingForVpcNetworks.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworks = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworks); - + Map defaultVpcNetworkOfferingProviders = new HashMap(); defaultVpcNetworkOfferingProviders.put(Service.Dhcp, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Dns, Provider.VPCVirtualRouter); @@ -990,14 +1008,14 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultVpcNetworkOfferingProviders.put(Service.StaticNat, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.PortForwarding, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Vpn, Provider.VPCVirtualRouter); - + for (Service service : defaultVpcNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO (defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } - + // Offering #7 NetworkOfferingVO defaultNetworkOfferingForVpcNetworksNoLB = new NetworkOfferingVO( NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, @@ -1008,7 +1026,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultNetworkOfferingForVpcNetworksNoLB.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworksNoLB = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworksNoLB); - + Map defaultVpcNetworkOfferingProvidersNoLB = new HashMap(); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dhcp, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dns, Provider.VPCVirtualRouter); @@ -1019,16 +1037,16 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultVpcNetworkOfferingProvidersNoLB.put(Service.StaticNat, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.PortForwarding, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Vpn, Provider.VPCVirtualRouter); - + for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO (defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } - - - + + + txn.commit(); } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 5881cf14db7..e3ad2e196a7 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -26,7 +26,6 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Comparator; import java.util.Date; -import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -48,13 +47,24 @@ import javax.management.MBeanRegistrationException; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd; import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd; +import org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd; +import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.systemvm.DestroySystemVmCmd; +import org.apache.cloudstack.api.command.admin.systemvm.ListSystemVMsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.RebootSystemVmCmd; +import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; import org.apache.cloudstack.api.command.admin.systemvm.UpgradeSystemVMCmd; +import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd; import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd; import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; @@ -63,19 +73,21 @@ import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; -import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; +import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd; import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd; import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; +import org.apache.cloudstack.api.response.ExtractResponse; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; @@ -86,38 +98,19 @@ import com.cloud.alert.Alert; import com.cloud.alert.AlertManager; import com.cloud.alert.AlertVO; import com.cloud.alert.dao.AlertDao; -import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd; -import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; -import org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd; -import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd; -import org.apache.cloudstack.api.command.admin.systemvm.ListSystemVMsCmd; -import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; -import org.apache.cloudstack.api.command.admin.systemvm.RebootSystemVmCmd; -import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; -import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; -import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; -import com.cloud.api.query.dao.DomainRouterJoinDao; -import com.cloud.api.query.dao.InstanceGroupJoinDao; - -import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; -import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; -import org.apache.cloudstack.api.response.ExtractResponse; - import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; import com.cloud.async.AsyncJobVO; import com.cloud.async.BaseAsyncJobExecutor; -import com.cloud.async.dao.AsyncJobDao; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Config; -import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Configuration; +import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManagementState; @@ -146,7 +139,6 @@ import com.cloud.event.EventTypes; import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; -import com.cloud.event.dao.EventJoinDao; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -233,9 +225,7 @@ import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapter; -import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentContext; -import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -269,7 +259,6 @@ import com.cloud.vm.VirtualMachineProfileImpl; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupDao; -import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @@ -281,64 +270,107 @@ import edu.emory.mathcs.backport.java.util.Collections; 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 AlertManager _alertMgr; - private final IPAddressDao _publicIpAddressDao; - private final DomainRouterDao _routerDao; - private final DomainRouterJoinDao _routerJoinDao; - private final ConsoleProxyDao _consoleProxyDao; - private final ClusterDao _clusterDao; - private final SecondaryStorageVmDao _secStorageVmDao; - private final EventDao _eventDao; - private final EventJoinDao _eventJoinDao; - private final DataCenterDao _dcDao; - private final VlanDao _vlanDao; - private final AccountVlanMapDao _accountVlanMapDao; - private final PodVlanMapDao _podVlanMapDao; - private final HostDao _hostDao; - private final HostDetailsDao _detailsDao; - private final UserDao _userDao; - private final UserVmDao _userVmDao; - private final ConfigurationDao _configDao; - private final ConsoleProxyManager _consoleProxyMgr; - private final SecondaryStorageVmManager _secStorageVmMgr; - private final SwiftManager _swiftMgr; - private final S3Manager _s3Mgr; - private final ServiceOfferingDao _offeringsDao; - private final DiskOfferingDao _diskOfferingDao; - private final VMTemplateDao _templateDao; - private final DomainDao _domainDao; - private final AccountDao _accountDao; - private final AlertDao _alertDao; - private final CapacityDao _capacityDao; - private final GuestOSDao _guestOSDao; - private final GuestOSCategoryDao _guestOSCategoryDao; - private final StoragePoolDao _poolDao; - private final NicDao _nicDao; - private final NetworkDao _networkDao; - private final StorageManager _storageMgr; - private final VirtualMachineManager _itMgr; - private final HostPodDao _hostPodDao; - private final VMInstanceDao _vmInstanceDao; - private final VolumeDao _volumeDao; - private final AsyncJobDao _jobDao; - private final AsyncJobManager _asyncMgr; - private final int _purgeDelay; - private final InstanceGroupDao _vmGroupDao; - private final InstanceGroupJoinDao _vmGroupJoinDao; - private final UploadMonitor _uploadMonitor; - private final UploadDao _uploadDao; - private final SSHKeyPairDao _sshKeyPairDao; - private final LoadBalancerDao _loadbalancerDao; - private final HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; - private final Adapters _hostAllocators; - private final ConfigurationManager _configMgr; - private final ResourceTagDao _resourceTagDao; + @Inject + private AccountManager _accountMgr; + @Inject + private AgentManager _agentMgr; + @Inject + private AlertManager _alertMgr; + @Inject + private IPAddressDao _publicIpAddressDao; + @Inject + private DomainRouterDao _routerDao; + @Inject + private ConsoleProxyDao _consoleProxyDao; + @Inject + private ClusterDao _clusterDao; + @Inject + private SecondaryStorageVmDao _secStorageVmDao; + @Inject + private EventDao _eventDao; + @Inject + private DataCenterDao _dcDao; + @Inject + private VlanDao _vlanDao; + @Inject + private AccountVlanMapDao _accountVlanMapDao; + @Inject + private PodVlanMapDao _podVlanMapDao; + @Inject + private HostDao _hostDao; + @Inject + private HostDetailsDao _detailsDao; + @Inject + private UserDao _userDao; + @Inject + private UserVmDao _userVmDao; + @Inject + private ConfigurationDao _configDao; + @Inject + private ConsoleProxyManager _consoleProxyMgr; + @Inject + private SecondaryStorageVmManager _secStorageVmMgr; + @Inject + private SwiftManager _swiftMgr; + @Inject + private ServiceOfferingDao _offeringsDao; + @Inject + private DiskOfferingDao _diskOfferingDao; + @Inject + private VMTemplateDao _templateDao; + @Inject + private DomainDao _domainDao; + @Inject + private AccountDao _accountDao; + @Inject + private AlertDao _alertDao; + @Inject + private CapacityDao _capacityDao; + @Inject + private GuestOSDao _guestOSDao; + @Inject + private GuestOSCategoryDao _guestOSCategoryDao; + @Inject + private StoragePoolDao _poolDao; + @Inject + private NetworkDao _networkDao; + @Inject + private StorageManager _storageMgr; + @Inject + private VirtualMachineManager _itMgr; + @Inject + private HostPodDao _hostPodDao; + @Inject + private VMInstanceDao _vmInstanceDao; + @Inject + private VolumeDao _volumeDao; + @Inject + private AsyncJobManager _asyncMgr; + private int _purgeDelay; + @Inject + private InstanceGroupDao _vmGroupDao; + @Inject + private UploadMonitor _uploadMonitor; + @Inject + private UploadDao _uploadDao; + @Inject + private SSHKeyPairDao _sshKeyPairDao; + @Inject + private LoadBalancerDao _loadbalancerDao; + @Inject + private HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; + + @Inject + private List _hostAllocators; + @Inject + private ConfigurationManager _configMgr; + @Inject + private ResourceTagDao _resourceTagDao; @Inject ProjectManager _projectMgr; - private final ResourceManager _resourceMgr; + @Inject + ResourceManager _resourceMgr; @Inject SnapshotManager _snapshotMgr; @Inject @@ -346,94 +378,33 @@ public class ManagementServerImpl implements ManagementServer { @Inject HostTagsDao _hostTagsDao; - private final KeystoreManager _ksMgr; + @Inject + S3Manager _s3Mgr; + + @Inject + ComponentContext _placeholder; private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); + private KeystoreManager _ksMgr; - private final Map _configs; + private Map _configs; - private final StatsCollector _statsCollector; + private Map _availableIdsMap; - private final Map _availableIdsMap; - - private Adapters _userAuthenticators; + @Inject List _userAuthenticators; private String _hashKey = null; - protected ManagementServerImpl() { - ComponentLocator locator = ComponentLocator.getLocator(Name); - _configDao = locator.getDao(ConfigurationDao.class); - _routerDao = locator.getDao(DomainRouterDao.class); - _routerJoinDao = locator.getDao(DomainRouterJoinDao.class); - _eventDao = locator.getDao(EventDao.class); - _eventJoinDao = locator.getDao(EventJoinDao.class); - _dcDao = locator.getDao(DataCenterDao.class); - _vlanDao = locator.getDao(VlanDao.class); - _accountVlanMapDao = locator.getDao(AccountVlanMapDao.class); - _podVlanMapDao = locator.getDao(PodVlanMapDao.class); - _hostDao = locator.getDao(HostDao.class); - _detailsDao = locator.getDao(HostDetailsDao.class); - _hostPodDao = locator.getDao(HostPodDao.class); - _jobDao = locator.getDao(AsyncJobDao.class); - _clusterDao = locator.getDao(ClusterDao.class); - _nicDao = locator.getDao(NicDao.class); - _networkDao = locator.getDao(NetworkDao.class); - _loadbalancerDao = locator.getDao(LoadBalancerDao.class); - - _accountMgr = locator.getManager(AccountManager.class); - _agentMgr = locator.getManager(AgentManager.class); - _alertMgr = locator.getManager(AlertManager.class); - _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class); - _secStorageVmMgr = locator.getManager(SecondaryStorageVmManager.class); - _swiftMgr = locator.getManager(SwiftManager.class); - _s3Mgr = locator.getManager(S3Manager.class); - _storageMgr = locator.getManager(StorageManager.class); - _publicIpAddressDao = locator.getDao(IPAddressDao.class); - _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); - _secStorageVmDao = locator.getDao(SecondaryStorageVmDao.class); - _userDao = locator.getDao(UserDao.class); - _userVmDao = locator.getDao(UserVmDao.class); - _offeringsDao = locator.getDao(ServiceOfferingDao.class); - _diskOfferingDao = locator.getDao(DiskOfferingDao.class); - _templateDao = locator.getDao(VMTemplateDao.class); - _domainDao = locator.getDao(DomainDao.class); - _accountDao = locator.getDao(AccountDao.class); - _alertDao = locator.getDao(AlertDao.class); - _capacityDao = locator.getDao(CapacityDao.class); - _guestOSDao = locator.getDao(GuestOSDao.class); - _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); - _poolDao = locator.getDao(StoragePoolDao.class); - _vmGroupDao = locator.getDao(InstanceGroupDao.class); - _vmGroupJoinDao = locator.getDao(InstanceGroupJoinDao.class); - _uploadDao = locator.getDao(UploadDao.class); - _configs = _configDao.getConfiguration(); - _vmInstanceDao = locator.getDao(VMInstanceDao.class); - _volumeDao = locator.getDao(VolumeDao.class); - _asyncMgr = locator.getManager(AsyncJobManager.class); - _uploadMonitor = locator.getManager(UploadMonitor.class); - _sshKeyPairDao = locator.getDao(SSHKeyPairDao.class); - _itMgr = locator.getManager(VirtualMachineManager.class); - _ksMgr = locator.getManager(KeystoreManager.class); - _resourceMgr = locator.getManager(ResourceManager.class); - _configMgr = locator.getManager(ConfigurationManager.class); - _resourceTagDao = locator.getDao(ResourceTagDao.class); - - _hypervisorCapabilitiesDao = locator.getDao(HypervisorCapabilitiesDao.class); - - _hostAllocators = locator.getAdapters(HostAllocator.class); - if (_hostAllocators == null || !_hostAllocators.isSet()) { - s_logger.error("Unable to find HostAllocators"); + public ManagementServerImpl() { } - + @PostConstruct void init() { - _configs = _configDao.getConfiguration(); - + _configs = _configDao.getConfiguration(); + String value = _configs.get("event.purge.interval"); int cleanup = NumbersUtil.parseInt(value, 60 * 60 * 24); // 1 day. - _statsCollector = StatsCollector.getInstance(_configs); - _purgeDelay = NumbersUtil.parseInt(_configs.get("event.purge.delay"), 0); if (_purgeDelay != 0) { _eventExecutor.scheduleAtFixedRate(new EventPurgeTask(), cleanup, cleanup, TimeUnit.SECONDS); @@ -444,117 +415,113 @@ public class ManagementServerImpl implements ManagementServer { for (String id : availableIds) { _availableIdsMap.put(id, true); } + } - _userAuthenticators = locator.getAdapters(UserAuthenticator.class); - if (_userAuthenticators == null || !_userAuthenticators.isSet()) { - s_logger.error("Unable to find an user authenticator."); - } - } - + @Override public void startup() { - s_logger.info("Startup CloudStack management server..."); - initCloudStackComponents(); + s_logger.info("Startup CloudStack management server..."); + initCloudStackComponents(); } - - private void initCloudStackComponents() { + + private void initCloudStackComponents() { runCheckers(); - startDaos(); // daos should not be using managers and adapters. + startDaos(); // daos should not be using managers and adapters. startManagers(); startAdapters(); - } - + } + private void runCheckers() { - Map checkers = ComponentContext.getApplicationContext().getBeansOfType( - SystemIntegrityChecker.class); - - for(SystemIntegrityChecker checker : checkers.values()) { - try { - checker.check(); - } catch (Exception e) { + Map checkers = ComponentContext.getApplicationContext().getBeansOfType( + SystemIntegrityChecker.class); + + for (SystemIntegrityChecker checker : checkers.values()) { + try { + checker.check(); + } catch (Exception e) { s_logger.error("Problems with running checker:" + ComponentContext.getTargetClass(checker).getName(), e); System.exit(1); - } - } + } + } } - + private void startDaos() { - @SuppressWarnings("rawtypes") - Map daos = ComponentContext.getApplicationContext().getBeansOfType( - GenericDaoBase.class); - - for(GenericDaoBase dao : daos.values()) { - try { - s_logger.info("Starting dao " + ComponentContext.getTargetClass(dao).getName()); - - // TODO - // dao.configure(dao.getClass().getSimpleName(), params); - } catch (Exception e) { + @SuppressWarnings("rawtypes") + Map daos = ComponentContext.getApplicationContext().getBeansOfType( + GenericDaoBase.class); + + for (GenericDaoBase dao : daos.values()) { + try { + s_logger.info("Starting dao " + ComponentContext.getTargetClass(dao).getName()); + + // TODO + // dao.configure(dao.getClass().getSimpleName(), params); + } catch (Exception e) { s_logger.error("Problems with running checker:" + ComponentContext.getTargetClass(dao).getName(), e); System.exit(1); - } - } + } + } } - + private void startManagers() { - @SuppressWarnings("rawtypes") - Map managers = ComponentContext.getApplicationContext().getBeansOfType( - Manager.class); - - Map params = new HashMap(); - for(Manager manager : managers.values()) { - s_logger.info("Start manager: " + ComponentContext.getTargetClass(manager).getName() + "..."); - try { - if(!ComponentContext.isPrimary(manager, Manager.class)) { - s_logger.error("Skip manager:" + ComponentContext.getTargetClass(manager).getName() + " as there are multiple matches"); - continue; - } - - if(!manager.configure(manager.getClass().getSimpleName(), params)) { + @SuppressWarnings("rawtypes") + Map managers = ComponentContext.getApplicationContext().getBeansOfType( + Manager.class); + + Map params = new HashMap(); + for (Manager manager : managers.values()) { + s_logger.info("Start manager: " + ComponentContext.getTargetClass(manager).getName() + "..."); + try { + if (!ComponentContext.isPrimary(manager, Manager.class)) { + s_logger.error("Skip manager:" + ComponentContext.getTargetClass(manager).getName() + " as there are multiple matches"); + continue; + } + + if (!manager.configure(manager.getClass().getSimpleName(), params)) { throw new CloudRuntimeException("Failed to start manager: " + ComponentContext.getTargetClass(manager).getName()); - } - + } + if (!manager.start()) { throw new CloudRuntimeException("Failed to start manager: " + ComponentContext.getTargetClass(manager).getName()); } - + if (manager instanceof ManagementBean) { - registerMBean((ManagementBean)manager); + registerMBean((ManagementBean) manager); } - } catch (Exception e) { + } catch (Exception e) { s_logger.error("Problems to start manager:" + ComponentContext.getTargetClass(manager).getName(), e); System.exit(1); - } - } + } + } } - + private void startAdapters() { - @SuppressWarnings("rawtypes") - Map adapters = ComponentContext.getApplicationContext().getBeansOfType( - Adapter.class); - - Map params = new HashMap(); - for(Adapter adapter : adapters.values()) { - try { - if(!ComponentContext.isPrimary(adapter, Adapter.class)) - continue; - - if(!adapter.configure(adapter.getClass().getSimpleName(), params)) { + @SuppressWarnings("rawtypes") + Map adapters = ComponentContext.getApplicationContext().getBeansOfType( + Adapter.class); + + Map params = new HashMap(); + for (Adapter adapter : adapters.values()) { + try { + if (!ComponentContext.isPrimary(adapter, Adapter.class)) + continue; + + if (!adapter.configure(adapter.getClass().getSimpleName(), params)) { throw new CloudRuntimeException("Failed to start adapter: " + ComponentContext.getTargetClass(adapter).getName()); - } + } if (!adapter.start()) { throw new CloudRuntimeException("Failed to start adapter: " + ComponentContext.getTargetClass(adapter).getName()); } - + if (adapter instanceof ManagementBean) { - registerMBean((ManagementBean)adapter); + registerMBean((ManagementBean) adapter); } - } catch (Exception e) { + } catch (Exception e) { s_logger.error("Problems to start manager:" + ComponentContext.getTargetClass(adapter).getName(), e); System.exit(1); - } - } + } + } } - + protected void registerMBean(ManagementBean mbean) { try { JmxUtil.registerMBean(mbean); @@ -569,7 +536,7 @@ public class ManagementServerImpl implements ManagementServer { } s_logger.info("Registered MBean: " + mbean.getName()); } - + protected Map getConfigs() { return _configs; } @@ -592,7 +559,7 @@ public class ManagementServerImpl implements ManagementServer { // right now, we made the decision to only list zones associated // with this domain dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private - // zones + // zones } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { if (keyword != null) { dcs = _dcDao.findByKeyword(keyword); @@ -861,8 +828,8 @@ public class ManagementServerImpl implements ManagementServer { } else if (vmId != null) { UserVmVO vmInstance = _userVmDao.findById(vmId); if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(vmInstance, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); + ex.addProxyObject(vmInstance, vmId, "vmId"); throw ex; } @@ -937,11 +904,11 @@ public class ManagementServerImpl implements ManagementServer { } else if (vmId != null) { UserVmVO vmInstance = _userVmDao.findById(vmId); if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); - ex.addProxyObject(vmInstance, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + ex.addProxyObject(vmInstance, vmId, "vmId"); throw ex; } - + _accountMgr.checkAccess(caller, null, false, vmInstance); ServiceOfferingVO offering = _offeringsDao.findById(vmInstance.getServiceOfferingId()); @@ -984,20 +951,20 @@ public class ManagementServerImpl implements ManagementServer { return sol; } - + @Override public List searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) { - Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); - SearchCriteria sc = _clusterDao.createSearchCriteria(); - - zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); + Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); + SearchCriteria sc = _clusterDao.createSearchCriteria(); - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); - sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); - - return _clusterDao.search(sc, searchFilter); + zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); + + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); + sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); + + return _clusterDao.search(sc, searchFilter); } - + @Override public Pair, Integer> searchForClusters(ListClustersCmd cmd) { Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -1053,7 +1020,6 @@ public class ManagementServerImpl implements ManagementServer { return new Pair, Integer>(result.first(), result.second()); } - @Override public Pair, List> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) { // access check - only root admin can migrate VM @@ -1067,8 +1033,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id"); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id"); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } // business logic @@ -1104,7 +1070,7 @@ public class ManagementServerImpl implements ManagementServer { } InvalidParameterValueException ex = new InvalidParameterValueException( "Unable to find the host (with specified id) of VM with specified id"); - ex.addProxyObject(srcHost, srcHostId, "hostId"); + ex.addProxyObject(srcHost, srcHostId, "hostId"); ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -1134,8 +1100,8 @@ public class ManagementServerImpl implements ManagementServer { DataCenterDeployment plan = new DataCenterDeployment(srcHost.getDataCenterId(), srcHost.getPodId(), srcHost.getClusterId(), null, null, null); ExcludeList excludes = new ExcludeList(); excludes.addHost(srcHostId); - - for(HostAllocator allocator : _hostAllocators) { + + for (HostAllocator allocator : _hostAllocators) { suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, HostAllocator.RETURN_UPTO_ALL, false); if (suitableHosts != null && !suitableHosts.isEmpty()) { break; @@ -1156,7 +1122,7 @@ public class ManagementServerImpl implements ManagementServer { private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword, Object resourceState, Object haHosts) { Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize); - + SearchBuilder sb = _hostDao.createSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); @@ -1166,7 +1132,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ); - + String haTag = _haMgr.getHaTag(); SearchBuilder hostTagSearch = null; if (haHosts != null && haTag != null && !haTag.isEmpty()) { @@ -1179,9 +1145,9 @@ public class ManagementServerImpl implements ManagementServer { } hostTagSearch.cp(); - sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); + sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); } - + SearchCriteria sc = sb.create(); if (keyword != null) { @@ -1219,7 +1185,7 @@ public class ManagementServerImpl implements ManagementServer { if (resourceState != null) { sc.setParameters("resourceState", resourceState); } - + if (haHosts != null && haTag != null && !haTag.isEmpty()) { sc.setJoinParameters("hostTagSearch", "tag", haTag); } @@ -1310,8 +1276,8 @@ public class ManagementServerImpl implements ManagementServer { if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } accountId = project.getProjectAccountId(); @@ -1551,14 +1517,14 @@ public class ManagementServerImpl implements ManagementServer { } } else if (_s3Mgr.isS3Enabled()) { if (template == null) { - templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, + templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, tags); Set> templateZonePairSet2 = new HashSet>(); - templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, + templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); - + for (Pair tmpltPair : templateZonePairSet2) { if (!templateZonePairSet.contains(new Pair(tmpltPair.first(), -1L))) { templateZonePairSet.add(tmpltPair); @@ -1613,15 +1579,15 @@ public class ManagementServerImpl implements ManagementServer { // verify that template exists VMTemplateVO template = _templateDao.findById(id); if (template == null || template.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id"); - ex.addProxyObject(template, id, "templateId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id"); + ex.addProxyObject(template, id, "templateId"); throw ex; } // Don't allow to modify system template if (id == Long.valueOf(1)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); - ex.addProxyObject(template, id, "templateId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); + ex.addProxyObject(template, id, "templateId"); throw ex; } @@ -1683,9 +1649,6 @@ public class ManagementServerImpl implements ManagementServer { return _templateDao.findById(id); } - - - @Override public Pair, Integer> searchForIPAddresses(ListPublicIpAddressesCmd cmd) { Object keyword = cmd.getKeyword(); @@ -1723,8 +1686,8 @@ public class ManagementServerImpl implements ManagementServer { domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - } + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + } sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); sb.and("address", sb.entity().getAddress(), SearchCriteria.Op.EQ); @@ -1736,7 +1699,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("isStaticNat", sb.entity().isOneToOneNat(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); - if (forLoadBalancing != null && (Boolean) forLoadBalancing) { + if (forLoadBalancing != null && forLoadBalancing) { SearchBuilder lbSearch = _loadbalancerDao.createSearchBuilder(); sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER); sb.groupBy(sb.entity().getId()); @@ -1770,14 +1733,14 @@ public class ManagementServerImpl implements ManagementServer { VlanType vlanType = null; if (forVirtualNetwork != null) { - vlanType = (Boolean) forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; + vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; } else { vlanType = VlanType.VirtualNetwork; } SearchCriteria sc = sb.create(); if (isAllocated) { - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); } sc.setJoinParameters("vlanSearch", "vlanType", vlanType); @@ -1799,7 +1762,7 @@ public class ManagementServerImpl implements ManagementServer { if (vpcId != null) { sc.setParameters("vpcId", vpcId); } - + if (ipId != null) { sc.setParameters("id", ipId); } @@ -1853,11 +1816,11 @@ public class ManagementServerImpl implements ManagementServer { if (osCategoryId != null) { sc.addAnd("categoryId", SearchCriteria.Op.EQ, osCategoryId); } - + if (description != null) { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + description + "%"); } - + if (keyword != null) { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } @@ -1878,11 +1841,11 @@ public class ManagementServerImpl implements ManagementServer { if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } - + if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - + if (keyword != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } @@ -1903,7 +1866,7 @@ public class ManagementServerImpl implements ManagementServer { @ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true) private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, - ConcurrentOperationException { + ConcurrentOperationException { User caller = _userDao.findById(UserContext.current().getCallerUserId()); @@ -1971,8 +1934,8 @@ public class ManagementServerImpl implements ManagementServer { // check if domain exists in the system DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id"); - ex.addProxyObject(domain, domainId, "domainId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id"); + ex.addProxyObject(domain, domainId, "domainId"); throw ex; } else if (domain.getParent() == null && domainName != null) { // check if domain is ROOT domain - and deny to edit it with the new @@ -1995,8 +1958,8 @@ public class ManagementServerImpl implements ManagementServer { if (!domains.isEmpty() && !sameDomain) { InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system"); - ex.addProxyObject(domain, domainId, "domainId"); - throw ex; + ex.addProxyObject(domain, domainId, "domainId"); + throw ex; } } @@ -2235,10 +2198,10 @@ public class ManagementServerImpl implements ManagementServer { dcList.add(ApiDBUtils.findZoneById(zoneId)); } else { if (clusterId != null) { - zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); + zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); } else { - zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); - } + zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); + } if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) { capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId)); } @@ -2366,7 +2329,7 @@ public class ManagementServerImpl implements ManagementServer { if (domainId != null) { if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { return _diskOfferingDao.listByDomainId(domainId);// no perm - // check + // check } else { // check if the user's domain == do's domain || user's domain is // a child of so's domain @@ -2540,8 +2503,7 @@ public class ManagementServerImpl implements ManagementServer { } return _poolDao.searchAndCount(sc, searchFilter); - } - + } @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true) public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { @@ -2550,7 +2512,7 @@ public class ManagementServerImpl implements ManagementServer { @ActionEvent(eventType = EventTypes.EVENT_SSVM_STOP, eventDescription = "stopping secondary storage Vm", async = true) private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, - OperationTimedoutException, ConcurrentOperationException { + OperationTimedoutException, ConcurrentOperationException { User caller = _userDao.findById(UserContext.current().getCallerUserId()); @@ -2598,7 +2560,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); sb.and("nulltype", sb.entity().getType(), SearchCriteria.Op.IN); - + if (storageId != null) { SearchBuilder volumeSearch = _volumeDao.createSearchBuilder(); volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ); @@ -2611,9 +2573,9 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria ssc = _vmInstanceDao.createSearchCriteria(); ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - + sc.addAnd("hostName", SearchCriteria.Op.SC, ssc); - } + } if (id != null) { sc.setParameters("id", id); @@ -2640,7 +2602,7 @@ public class ManagementServerImpl implements ManagementServer { } else { sc.setParameters("nulltype", VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.ConsoleProxy); } - + if (storageId != null) { sc.setJoinParameters("volumeSearch", "poolId", storageId); } @@ -2653,8 +2615,8 @@ public class ManagementServerImpl implements ManagementServer { public VirtualMachine.Type findSystemVMTypeById(long instanceId) { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId"); - ex.addProxyObject(systemVm, instanceId, "instanceId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId"); + ex.addProxyObject(systemVm, instanceId, "instanceId"); throw ex; } return systemVm.getType(); @@ -2665,8 +2627,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, vmId, "vmId"); throw ex; } @@ -2675,8 +2637,8 @@ public class ManagementServerImpl implements ManagementServer { } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) { return startSecondaryStorageVm(vmId); } else { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, vmId, "vmId"); throw ex; } } @@ -2688,8 +2650,8 @@ public class ManagementServerImpl implements ManagementServer { // verify parameters VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, id, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, id, "vmId"); throw ex; } @@ -2710,8 +2672,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, cmd.getId(), "vmId"); throw ex; } @@ -2727,8 +2689,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, cmd.getId(), "vmId"); throw ex; } @@ -2765,8 +2727,8 @@ public class ManagementServerImpl implements ManagementServer { // verify that user exists User user = _accountMgr.getUserIncludingRemoved(userId); if ((user == null) || (user.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id"); - ex.addProxyObject(user, userId, "userId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id"); + ex.addProxyObject(user, userId, "userId"); throw ex; } @@ -2814,20 +2776,20 @@ public class ManagementServerImpl implements ManagementServer { supportELB = networkType; } } - + long diskOffMaxSize = Long.valueOf(_configDao.getValue(Config.CustomDiskOfferingMaxSize.key())); String userPublicTemplateEnabled = _configs.get(Config.AllowPublicUserTemplates.key()); capabilities.put("securityGroupsEnabled", securityGroupsEnabled); capabilities - .put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); + .put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); capabilities.put("cloudStackVersion", getVersion()); capabilities.put("supportELB", supportELB); capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired()); capabilities.put("allowusercreateprojects", _projectMgr.allowUserToCreateProject()); capabilities.put("customDiskOffMaxSize", diskOffMaxSize); - + return capabilities; } @@ -2852,8 +2814,8 @@ public class ManagementServerImpl implements ManagementServer { VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId"); - ex.addProxyObject(volume, volumeId, "volumeId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId"); + ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } @@ -2878,19 +2840,19 @@ public class ManagementServerImpl implements ManagementServer { } if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont - // have any - // template - // dependence. + // have any + // template + // dependence. VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); if (template != null) { // For ISO based volumes template = null and - // we allow extraction of all ISO based - // volumes + // we allow extraction of all ISO based + // volumes boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global - // admins are always allowed to extract - PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); - ex.addProxyObject(volume, volumeId, "volumeId"); + // admins are always allowed to extract + PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); + ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } } @@ -2939,7 +2901,7 @@ public class ManagementServerImpl implements ManagementServer { if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) { return extractURLList.get(0).getId(); // If download url already - // exists then return + // exists then return } else { UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, url, extractMode); @@ -2997,12 +2959,12 @@ public class ManagementServerImpl implements ManagementServer { _uploadDao.update(uploadJob.getId(), uploadJob); if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is - // copied perform the actual - // uploading + // 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. + // create a URL. _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId()); return uploadJob.getId(); } @@ -3034,8 +2996,8 @@ public class ManagementServerImpl implements ManagementServer { // Verify input parameters InstanceGroupVO group = _vmGroupDao.findById(groupId.longValue()); if (group == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId"); - ex.addProxyObject(group, groupId, "groupId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId"); + ex.addProxyObject(group, groupId, "groupId"); throw ex; } @@ -3055,8 +3017,6 @@ public class ManagementServerImpl implements ManagementServer { return _vmGroupDao.findById(groupId); } - - @Override public String getVersion() { final Class c = ManagementServer.class; @@ -3192,7 +3152,7 @@ public class ManagementServerImpl implements ManagementServer { if (s == null) { InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id"); - ex.addProxyObject(owner, owner.getDomainId(), "domainId"); + ex.addProxyObject(owner, owner.getDomainId(), "domainId"); throw ex; } @@ -3277,8 +3237,8 @@ public class ManagementServerImpl implements ManagementServer { UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); - ex.addProxyObject(vm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); + ex.addProxyObject(vm, cmd.getId(), "vmId"); throw ex; } @@ -3288,8 +3248,8 @@ public class ManagementServerImpl implements ManagementServer { _userVmDao.loadDetails(vm); String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { - InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found."); - ex.addProxyObject(vm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found."); + ex.addProxyObject(vm, cmd.getId(), "vmId"); throw ex; } @@ -3398,8 +3358,8 @@ public class ManagementServerImpl implements ManagementServer { HypervisorCapabilitiesVO hpvCapabilities = _hypervisorCapabilitiesDao.findById(id, true); if (hpvCapabilities == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id"); - ex.addProxyObject(hpvCapabilities, id, "Id"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id"); + ex.addProxyObject(hpvCapabilities, id, "Id"); throw ex; } @@ -3426,7 +3386,7 @@ public class ManagementServerImpl implements ManagementServer { return null; } } - + @Override public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { Long systemVmId = cmd.getId(); @@ -3439,12 +3399,12 @@ public class ManagementServerImpl implements ManagementServer { } _accountMgr.checkAccess(caller, null, true, systemVm); - + // Check that the specified service offering ID is valid _itMgr.checkIfCanUpgrade(systemVm, serviceOfferingId); boolean result = _itMgr.upgradeVmDb(systemVmId, serviceOfferingId); - + if (result) { return _vmInstanceDao.findById(systemVmId); } else { @@ -3453,6 +3413,7 @@ public class ManagementServerImpl implements ManagementServer { } + @Override public void enableAdminUser(String password) { String encodedPassword = null; @@ -3461,8 +3422,8 @@ public class ManagementServerImpl implements ManagementServer { // This means its a new account, set the password using the // authenticator - for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { - UserAuthenticator authenticator = en.nextElement(); + for (Iterator en = _userAuthenticators.iterator(); en.hasNext();) { + UserAuthenticator authenticator = en.next(); encodedPassword = authenticator.encode(password); if (encodedPassword != null) { break; diff --git a/server/src/com/cloud/servlet/CloudStartupServlet.java b/server/src/com/cloud/servlet/CloudStartupServlet.java index 4466ca86460..de133abb16e 100755 --- a/server/src/com/cloud/servlet/CloudStartupServlet.java +++ b/server/src/com/cloud/servlet/CloudStartupServlet.java @@ -36,46 +36,47 @@ import com.cloud.utils.SerialVersionUID; import com.cloud.utils.component.ComponentContext; public class CloudStartupServlet extends HttpServlet implements ServletContextListener { - public static final Logger s_logger = Logger.getLogger(CloudStartupServlet.class.getName()); - - static final long serialVersionUID = SerialVersionUID.CloudStartupServlet; - - @Override - public void init() throws ServletException { - initLog4j(); + public static final Logger s_logger = Logger.getLogger(CloudStartupServlet.class.getName()); - // Save Configuration Values - ConfigurationServer c = (ConfigurationServer)ComponentContext.getCompanent(ConfigurationServer.class); - try { - c.persistDefaultValues(); - s_locator = ComponentLocator.getLocator(ManagementServer.Name); - ManagementServer ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name); - ms.enableAdminUser("password"); - ApiServer.initApiServer(ms.getPropertiesFiles()); - } catch (InvalidParameterValueException ipve) { - s_logger.error("Exception starting management server ", ipve); - throw new ServletException (ipve.getMessage()); - } catch (Exception e) { - s_logger.error("Exception starting management server ", e); - throw new ServletException (e.getMessage()); - } - } - - @Override - public void contextInitialized(ServletContextEvent sce) { - try { - init(); - } catch (ServletException e) { - s_logger.error("Exception starting management server ", e); - throw new RuntimeException(e); - } - } - - @Override - public void contextDestroyed(ServletContextEvent sce) { - } - - private void initLog4j() { + static final long serialVersionUID = SerialVersionUID.CloudStartupServlet; + + @Override + public void init() throws ServletException { + initLog4j(); + + // Save Configuration Values + ConfigurationServer c = ComponentContext.getCompanent(ConfigurationServer.class); + try { + c.persistDefaultValues(); + + ManagementServer ms = ComponentContext.getCompanent(ManagementServer.class); + ms.startup(); + ms.enableAdminUser("password"); + ApiServer.initApiServer(ms.getPropertiesFiles()); + } catch (InvalidParameterValueException ipve) { + s_logger.error("Exception starting management server ", ipve); + throw new ServletException (ipve.getMessage()); + } catch (Exception e) { + s_logger.error("Exception starting management server ", e); + throw new ServletException (e.getMessage()); + } + } + + @Override + public void contextInitialized(ServletContextEvent sce) { + try { + init(); + } catch (ServletException e) { + s_logger.error("Exception starting management server ", e); + throw new RuntimeException(e); + } + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + } + + private void initLog4j() { File file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); if (file != null) { s_logger.info("log4j configuration found at " + file.getAbsolutePath()); @@ -87,5 +88,5 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi PropertyConfigurator.configureAndWatch(file.getAbsolutePath()); } } - } + } } diff --git a/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java b/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java index ca14bd7467f..57f2153f10b 100755 --- a/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java @@ -20,6 +20,8 @@ import java.util.List; import javax.ejb.Local; +import org.springframework.stereotype.Component; + import com.cloud.storage.VolumeHostVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; @@ -29,85 +31,85 @@ import com.cloud.utils.db.SearchCriteria; @Local(value={VolumeHostDao.class}) public class VolumeHostDaoImpl extends GenericDaoBase implements VolumeHostDao { - protected final SearchBuilder HostVolumeSearch; - protected final SearchBuilder ZoneVolumeSearch; - protected final SearchBuilder VolumeSearch; - protected final SearchBuilder HostSearch; - protected final SearchBuilder HostDestroyedSearch; - - VolumeHostDaoImpl(){ - HostVolumeSearch = createSearchBuilder(); - HostVolumeSearch.and("host_id", HostVolumeSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostVolumeSearch.and("volume_id", HostVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - HostVolumeSearch.and("destroyed", HostVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - HostVolumeSearch.done(); - - ZoneVolumeSearch = createSearchBuilder(); - ZoneVolumeSearch.and("zone_id", ZoneVolumeSearch.entity().getZoneId(), SearchCriteria.Op.EQ); - ZoneVolumeSearch.and("volume_id", ZoneVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - ZoneVolumeSearch.and("destroyed", ZoneVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - ZoneVolumeSearch.done(); - - HostSearch = createSearchBuilder(); - HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostSearch.and("destroyed", HostSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - HostSearch.done(); - - VolumeSearch = createSearchBuilder(); - VolumeSearch.and("volume_id", VolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - VolumeSearch.and("destroyed", VolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - VolumeSearch.done(); - - HostDestroyedSearch = createSearchBuilder(); - HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - HostDestroyedSearch.done(); - } - - - - @Override - public VolumeHostVO findByHostVolume(long hostId, long volumeId) { - SearchCriteria sc = HostVolumeSearch.create(); - sc.setParameters("host_id", hostId); - sc.setParameters("volume_id", volumeId); + protected final SearchBuilder HostVolumeSearch; + protected final SearchBuilder ZoneVolumeSearch; + protected final SearchBuilder VolumeSearch; + protected final SearchBuilder HostSearch; + protected final SearchBuilder HostDestroyedSearch; + + VolumeHostDaoImpl(){ + HostVolumeSearch = createSearchBuilder(); + HostVolumeSearch.and("host_id", HostVolumeSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostVolumeSearch.and("volume_id", HostVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); + HostVolumeSearch.and("destroyed", HostVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + HostVolumeSearch.done(); + + ZoneVolumeSearch = createSearchBuilder(); + ZoneVolumeSearch.and("zone_id", ZoneVolumeSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + ZoneVolumeSearch.and("volume_id", ZoneVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); + ZoneVolumeSearch.and("destroyed", ZoneVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + ZoneVolumeSearch.done(); + + HostSearch = createSearchBuilder(); + HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostSearch.and("destroyed", HostSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + HostSearch.done(); + + VolumeSearch = createSearchBuilder(); + VolumeSearch.and("volume_id", VolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); + VolumeSearch.and("destroyed", VolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + VolumeSearch.done(); + + HostDestroyedSearch = createSearchBuilder(); + HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + HostDestroyedSearch.done(); + } + + + + @Override + public VolumeHostVO findByHostVolume(long hostId, long volumeId) { + SearchCriteria sc = HostVolumeSearch.create(); + sc.setParameters("host_id", hostId); + sc.setParameters("volume_id", volumeId); sc.setParameters("destroyed", false); return findOneIncludingRemovedBy(sc); - } - - @Override - public VolumeHostVO findVolumeByZone(long volumeId, long zoneId) { - SearchCriteria sc = ZoneVolumeSearch.create(); - sc.setParameters("zone_id", zoneId); - sc.setParameters("volume_id", volumeId); + } + + @Override + public VolumeHostVO findVolumeByZone(long volumeId, long zoneId) { + SearchCriteria sc = ZoneVolumeSearch.create(); + sc.setParameters("zone_id", zoneId); + sc.setParameters("volume_id", volumeId); sc.setParameters("destroyed", false); return findOneIncludingRemovedBy(sc); - } - - @Override - public VolumeHostVO findByVolumeId(long volumeId) { - SearchCriteria sc = VolumeSearch.create(); - sc.setParameters("volume_id", volumeId); - sc.setParameters("destroyed", false); - return findOneBy(sc); - } + } + + @Override + public VolumeHostVO findByVolumeId(long volumeId) { + SearchCriteria sc = VolumeSearch.create(); + sc.setParameters("volume_id", volumeId); + sc.setParameters("destroyed", false); + return findOneBy(sc); + } - @Override - public List listBySecStorage(long ssHostId) { - SearchCriteria sc = HostSearch.create(); - sc.setParameters("host_id", ssHostId); - sc.setParameters("destroyed", false); - return listAll(); - } - - @Override - public List listDestroyed(long hostId){ - SearchCriteria sc = HostDestroyedSearch.create(); - sc.setParameters("host_id", hostId); - sc.setParameters("destroyed", true); - return listIncludingRemovedBy(sc); - } + @Override + public List listBySecStorage(long ssHostId) { + SearchCriteria sc = HostSearch.create(); + sc.setParameters("host_id", ssHostId); + sc.setParameters("destroyed", false); + return listAll(); + } + + @Override + public List listDestroyed(long hostId){ + SearchCriteria sc = HostDestroyedSearch.create(); + sc.setParameters("host_id", hostId); + sc.setParameters("destroyed", true); + return listIncludingRemovedBy(sc); + } } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 47b47470fe6..c238efb1953 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -20,8 +20,8 @@ import java.net.URLEncoder; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; -import java.util.Enumeration; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; @@ -39,20 +39,18 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; import org.apache.cloudstack.api.command.admin.user.RegisterCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.dao.UserAccountJoinDao; import com.cloud.api.query.vo.ControlledViewEntity; - - -import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; -import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceLimit; @@ -115,7 +113,6 @@ import com.cloud.user.dao.UserDao; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; -import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -232,7 +229,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserVO _systemUser; AccountVO _systemAccount; - + @Inject List _securityCheckers; int _cleanupInterval; @@ -285,6 +282,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return true; } + @Override public AccountVO getSystemAccount() { if (_systemAccount == null) { _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); @@ -382,7 +380,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (!granted) { assert false : "How can all of the security checkers pass on checking this check: " + entity; - throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); + throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); } } @@ -444,7 +442,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag user.setState(State.disabled.toString()); } _userAccountDao.update(id, user); - txn.commit(); + txn.commit(); } catch (Exception e) { s_logger.error("Failed to update login attempts for user with id " + id ); } @@ -492,7 +490,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); - + //delete the account record if (!_accountDao.remove(accountId)) { s_logger.error("Unable to delete account " + accountId); @@ -510,7 +508,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); boolean accountCleanupNeeded = false; - + try { //cleanup the users from the account List users = _userDao.listByAccount(accountId); @@ -520,10 +518,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag accountCleanupNeeded = true; } } - + //delete the account from project accounts _projectAccountDao.removeAccountFromProjects(accountId); - + // delete all vm groups belonging to accont List groups = _vmGroupDao.listByAccountId(accountId); for (InstanceGroupVO group : groups) { @@ -601,7 +599,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex); accountCleanupNeeded = true; } - + // Cleanup security groups int numRemoved = _securityGroupDao.removeByAccountId(accountId); s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId); @@ -624,7 +622,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } } - + //Delete all VPCs boolean vpcsDeleted = true; s_logger.debug("Deleting vpcs for account " + account.getId()); @@ -646,8 +644,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag for (IpAddress ip : ipsToRelease) { s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { - s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); - accountCleanupNeeded = true; + s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); + accountCleanupNeeded = true; } } } @@ -776,7 +774,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (userName.isEmpty()) { throw new InvalidParameterValueException("Username is empty"); } - + if (firstName.isEmpty()) { throw new InvalidParameterValueException("Firstname is empty"); } @@ -905,21 +903,21 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (firstName.isEmpty()) { throw new InvalidParameterValueException("Firstname is empty"); } - + user.setFirstname(firstName); } if (lastName != null) { if (lastName.isEmpty()) { throw new InvalidParameterValueException("Lastname is empty"); } - + user.setLastname(lastName); } if (userName != null) { if (userName.isEmpty()) { throw new InvalidParameterValueException("Username is empty"); } - + // don't allow to have same user names in the same domain List duplicatedUsers = _userDao.findUsersByName(userName); for (UserVO duplicatedUser : duplicatedUsers) { @@ -933,18 +931,18 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag user.setUsername(userName); } - + if (password != null) { String encodedPassword = null; - for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { - UserAuthenticator authenticator = en.nextElement(); + for (Iterator en = _userAuthenticators.iterator(); en.hasNext();) { + UserAuthenticator authenticator = en.next(); encodedPassword = authenticator.encode(password); if (encodedPassword != null) { break; } } if (encodedPassword == null) { - throw new CloudRuntimeException("Failed to encode password"); + throw new CloudRuntimeException("Failed to encode password"); } user.setPassword(encodedPassword); } @@ -1293,11 +1291,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // check if the given account name is unique in this domain for updating Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId); if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow - // same - // account - // to - // update - // itself + // same + // account + // to + // update + // itself throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:" + duplicateAcccount.getId()); } @@ -1697,15 +1695,15 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } String encodedPassword = null; - for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { - UserAuthenticator authenticator = en.nextElement(); + for (Iterator en = _userAuthenticators.iterator(); en.hasNext();) { + UserAuthenticator authenticator = en.next(); encodedPassword = authenticator.encode(password); if (encodedPassword != null) { break; } } if (encodedPassword == null) { - throw new CloudRuntimeException("Failed to encode password"); + throw new CloudRuntimeException("Failed to encode password"); } UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone)); @@ -2088,7 +2086,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, - boolean listAll, boolean forProjectInvitation) { + boolean listAll, boolean forProjectInvitation) { Long domainId = domainIdRecursiveListProject.first(); if (domainId != null) { @@ -2166,7 +2164,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } - @Override + @Override public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { @@ -2210,7 +2208,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @Override - public UserAccount getUserByApiKey(String apiKey) { - return _userAccountDao.getUserByApiKey(apiKey); - } + public UserAccount getUserByApiKey(String apiKey) { + return _userAccountDao.getUserByApiKey(apiKey); + } } diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 15b8a114ae0..f7d39ee52d5 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -50,7 +50,6 @@ import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.user.dao.AccountDao; import com.cloud.utils.Pair; -import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; diff --git a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java b/server/src/com/cloud/uuididentity/IdentityServiceImpl.java index a6edda2706d..2a93627d503 100644 --- a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java +++ b/server/src/com/cloud/uuididentity/IdentityServiceImpl.java @@ -23,7 +23,8 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.cloudstack.api.IdentityService; -import com.cloud.utils.component.Inject; +import org.springframework.stereotype.Component; + import com.cloud.utils.component.Manager; import com.cloud.uuididentity.dao.IdentityDao; @@ -31,37 +32,39 @@ import com.cloud.uuididentity.dao.IdentityDao; @Local(value = { IdentityService.class }) public class IdentityServiceImpl implements Manager, IdentityService { private String _name; - - @Inject private IdentityDao _identityDao; - + + @Inject private IdentityDao _identityDao; + + @Override public Long getIdentityId(String tableName, String identityString) { - return _identityDao.getIdentityId(tableName, identityString); + return _identityDao.getIdentityId(tableName, identityString); } - - public String getIdentityUuid(String tableName, String identityString) { - return _identityDao.getIdentityUuid(tableName, identityString); - } - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - _name = name; - - return true; - } + @Override + public String getIdentityUuid(String tableName, String identityString) { + return _identityDao.getIdentityUuid(tableName, identityString); + } - @Override - public String getName() { - return _name; - } + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + _name = name; - @Override - public boolean start() { - return true; - } + return true; + } - @Override - public boolean stop() { - return true; - } + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 0317643b65f..61526a69baa 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -32,20 +32,45 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; -import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; +import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; +import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; +import org.apache.cloudstack.api.command.user.vm.StartVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; +import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity; +import org.apache.cloudstack.engine.service.api.OrchestrationService; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.acl.ControlledEntity.ACLType; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; -import com.cloud.agent.api.*; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.AttachIsoCommand; +import com.cloud.agent.api.AttachVolumeAnswer; +import com.cloud.agent.api.AttachVolumeCommand; +import com.cloud.agent.api.ComputeChecksumCommand; +import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; +import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; +import com.cloud.agent.api.GetVmStatsAnswer; +import com.cloud.agent.api.GetVmStatsCommand; +import com.cloud.agent.api.SnapshotCommand; +import com.cloud.agent.api.StartAnswer; +import com.cloud.agent.api.StopAnswer; +import com.cloud.agent.api.UpgradeSnapshotCommand; +import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; @@ -55,17 +80,6 @@ import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.dao.UserVmJoinDao; import com.cloud.api.query.vo.UserVmJoinVO; - -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; -import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; -import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; -import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; -import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; -import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; -import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; -import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd; -import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -90,18 +104,37 @@ import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.event.dao.UsageEventDao; -import com.cloud.exception.*; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ManagementServerException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.StorageUnavailableException; +import com.cloud.exception.VirtualMachineMigrationException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao; -import com.cloud.network.*; +import com.cloud.network.IPAddressVO; +import com.cloud.network.LoadBalancerVMMapVO; +import com.cloud.network.Network; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.NetworkManager; +import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.*; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.rules.FirewallManager; @@ -129,18 +162,51 @@ import com.cloud.resource.ResourceState; import com.cloud.server.Criteria; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.*; +import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.GuestOSCategoryVO; +import com.cloud.storage.GuestOSVO; +import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.TemplateType; +import com.cloud.storage.StorageManager; +import com.cloud.storage.StoragePool; +import com.cloud.storage.StoragePoolStatus; +import com.cloud.storage.StoragePoolVO; +import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VMTemplateZoneVO; +import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; -import com.cloud.storage.dao.*; +import com.cloud.storage.VolumeHostVO; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.DiskOfferingDao; +import com.cloud.storage.dao.GuestOSCategoryDao; +import com.cloud.storage.dao.GuestOSDao; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.StoragePoolDao; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.dao.VMTemplateDetailsDao; +import com.cloud.storage.dao.VMTemplateHostDao; +import com.cloud.storage.dao.VMTemplateZoneDao; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.dao.VolumeHostDao; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.VirtualMachineTemplate; import com.cloud.template.VirtualMachineTemplate.BootloaderType; -import com.cloud.user.*; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.AccountService; +import com.cloud.user.AccountVO; +import com.cloud.user.ResourceLimitService; +import com.cloud.user.SSHKeyPair; +import com.cloud.user.User; +import com.cloud.user.UserContext; +import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; @@ -157,1968 +223,1973 @@ import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.dao.*; +import com.cloud.vm.dao.InstanceGroupDao; +import com.cloud.vm.dao.InstanceGroupVMMapDao; +import com.cloud.vm.dao.NicDao; +import com.cloud.vm.dao.UserVmDao; +import com.cloud.vm.dao.UserVmDetailsDao; +import com.cloud.vm.dao.VMInstanceDao; @Component @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 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 ServiceOfferingDao _offeringDao = null; - @Inject - protected DiskOfferingDao _diskOfferingDao = null; - @Inject - protected VMTemplateDao _templateDao = null; - @Inject - protected VMTemplateDetailsDao _templateDetailsDao = null; - @Inject - protected VMTemplateHostDao _templateHostDao = null; - @Inject - protected VMTemplateZoneDao _templateZoneDao = null; - @Inject - protected DomainDao _domainDao = null; - @Inject - protected UserVmDao _vmDao = null; - @Inject + @Inject + protected HostDao _hostDao = null; + @Inject + protected ServiceOfferingDao _offeringDao = null; + @Inject + protected DiskOfferingDao _diskOfferingDao = null; + @Inject + protected VMTemplateDao _templateDao = null; + @Inject + protected VMTemplateDetailsDao _templateDetailsDao = null; + @Inject + protected VMTemplateHostDao _templateHostDao = null; + @Inject + protected VMTemplateZoneDao _templateZoneDao = null; + @Inject + protected DomainDao _domainDao = null; + @Inject + protected UserVmDao _vmDao = null; + @Inject protected UserVmJoinDao _vmJoinDao = null; @Inject - protected VolumeDao _volsDao = null; - @Inject - protected DataCenterDao _dcDao = null; - @Inject - protected FirewallRulesDao _rulesDao = null; - @Inject - protected LoadBalancerVMMapDao _loadBalancerVMMapDao = null; - @Inject - protected PortForwardingRulesDao _portForwardingDao; - @Inject - protected IPAddressDao _ipAddressDao = null; - @Inject - protected HostPodDao _podDao = 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 HighAvailabilityManager _haMgr = null; - @Inject - protected AlertManager _alertMgr = null; - @Inject - protected AccountManager _accountMgr; - @Inject - protected AccountService _accountService; - @Inject - protected AsyncJobManager _asyncMgr; - @Inject - protected ClusterDao _clusterDao; - @Inject - protected StoragePoolDao _storagePoolDao; - @Inject - protected SecurityGroupManager _securityGroupMgr; - @Inject - protected ServiceOfferingDao _serviceOfferingDao; - @Inject - protected NetworkOfferingDao _networkOfferingDao; - @Inject - protected InstanceGroupDao _vmGroupDao; - @Inject - protected InstanceGroupVMMapDao _groupVMMapDao; - @Inject - protected VirtualMachineManager _itMgr; - @Inject - protected NetworkDao _networkDao; - @Inject - protected NicDao _nicDao; - @Inject - protected VpcDao _vpcDao; - @Inject - protected RulesManager _rulesMgr; - @Inject - protected LoadBalancingRulesManager _lbMgr; - @Inject - protected UsageEventDao _usageEventDao; - @Inject - protected SSHKeyPairDao _sshKeyPairDao; - @Inject - protected UserVmDetailsDao _vmDetailsDao; - @Inject - protected HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; - @Inject - protected SecurityGroupDao _securityGroupDao; - @Inject - protected CapacityManager _capacityMgr;; - @Inject - protected VMInstanceDao _vmInstanceDao; - @Inject - protected ResourceLimitService _resourceLimitMgr; - @Inject - protected FirewallManager _firewallMgr; - @Inject - protected ProjectManager _projectMgr; - @Inject - protected ResourceManager _resourceMgr; - @Inject - protected NetworkServiceMapDao _ntwkSrvcDao; - @Inject - SecurityGroupVMMapDao _securityGroupVMMapDao; - @Inject - protected ItWorkDao _workDao; - @Inject - protected VolumeHostDao _volumeHostDao; - @Inject - ResourceTagDao _resourceTagDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - VpcManager _vpcMgr; - @Inject - protected GuestOSCategoryDao _guestOSCategoryDao; - - protected ScheduledExecutorService _executor = null; - protected int _expungeInterval; - protected int _expungeDelay; - - protected String _name; - protected String _instance; - protected String _zone; - - private ConfigurationDao _configDao; - private int _createprivatetemplatefromvolumewait; - private int _createprivatetemplatefromsnapshotwait; - - @Inject - protected OrchestrationService _orchSrvc; - - @Override - public UserVmVO getVirtualMachine(long vmId) { - return _vmDao.findById(vmId); - } - - @Override - public List getVirtualMachines(long hostId) { - 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 { - Account caller = UserContext.current().getCaller(); - Long vmId = cmd.getId(); - UserVmVO userVm = _vmDao.findById(cmd.getId()); - _vmDao.loadDetails(userVm); - - // 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"); - } - - _accountMgr.checkAccess(caller, null, true, userVm); - - boolean result = resetVMPasswordInternal(cmd, password); - - if (result) { - userVm.setPassword(password); - // update the password in vm_details table too - // Check if an SSH key pair was selected for the instance and if so - // use it to encrypt & save the vm password - String sshPublicKey = userVm.getDetail("SSH.PublicKey"); - 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"); - } - - userVm.setDetail("Encrypted.Password", encryptedPasswd); - _vmDao.saveDetails(userVm); - } - } else { - throw new CloudRuntimeException( - "Failed to reset password for the virtual machine "); - } - - return userVm; - } - - private boolean resetVMPasswordInternal(ResetVMPasswordCmd cmd, - String password) throws ResourceUnavailableException, - InsufficientCapacityException { - Long vmId = cmd.getId(); - Long userId = UserContext.current().getCallerUserId(); - VMInstanceVO vmInstance = _vmDao.findById(vmId); - - if (password == null || password.equals("")) { - return false; - } - - VMTemplateVO template = _templateDao - .findByIdIncludingRemoved(vmInstance.getTemplateId()); - if (template.getEnablePassword()) { - Nic defaultNic = _networkMgr.getDefaultNic(vmId); - if (defaultNic == null) { - 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, - _networkMgr - .isSecurityGroupSupportedInNetwork(defaultNetwork), - _networkMgr.getNetworkTag(template.getHypervisorType(), - defaultNetwork)); - VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl( - vmInstance); - vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, - password); - - UserDataServiceProvider element = _networkMgr - .getPasswordResetProvider(defaultNetwork); - if (element == null) { - throw new CloudRuntimeException( - "Can't find network element for " - + Service.UserData.getName() - + " provider needed for password reset"); - } - - boolean result = element.savePassword(defaultNetwork, - defaultNicProfile, vmProfile); - - // 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"); - return false; - } else { - if (vmInstance.getState() == State.Stopped) { - s_logger.debug("Vm " - + vmInstance - + " is stopped, not rebooting it as a part of password reset"); - return true; - } - - if (rebootVirtualMachine(userId, vmId) == null) { - s_logger.warn("Failed to reboot the vm " + vmInstance); - return false; - } else { - s_logger.debug("Vm " - + vmInstance - + " is rebooted successfully as a part of password reset"); - return true; - } - } - } else { - 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); - 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) { - return status; - } else { - return status; - } - } - - private int getMaxDataVolumesSupported(UserVmVO vm) { - Long hostId = vm.getHostId(); - if (hostId == null) { - hostId = vm.getLastHostId(); - } - HostVO host = _hostDao.findById(hostId); - Integer maxDataVolumesSupported = null; - if (host != null) { - _hostDao.loadDetails(host); - maxDataVolumesSupported = _hypervisorCapabilitiesDao - .getMaxDataVolumesLimit(host.getHypervisorType(), - host.getDetail("product_version")); - } - if (maxDataVolumesSupported == null) { - maxDataVolumesSupported = 6; // 6 data disks by default if nothing - // is specified in - // 'hypervisor_capabilities' table - } - - return maxDataVolumesSupported.intValue(); - } - - @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 caller = 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."); - } - - // 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."); - } - - // Check that the volume is not destroyed - if (volume.getState() == Volume.State.Destroy) { - 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) { - 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."); - } - - // 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"); - } - } - - // Check that the number of data volumes attached to VM is less than - // that supported by hypervisor - List existingDataVolumes = _volsDao.findByInstanceAndType( - vmId, Volume.Type.DATADISK); - int maxDataVolumesSupported = getMaxDataVolumesSupported(vm); - if (existingDataVolumes.size() >= maxDataVolumesSupported) { - throw new InvalidParameterValueException( - "The specified VM already has the maximum number of data disks (" - + maxDataVolumesSupported - + "). Please specify another VM."); - } - - // Check that the VM and the volume are in the same zone - if (vm.getDataCenterIdToDeployIn() != volume.getDataCenterId()) { - throw new InvalidParameterValueException( - "Please specify a VM that is in the same zone as the volume."); - } - - // If local storage is disabled then attaching a volume with local disk - // offering not allowed - DataCenterVO dataCenter = _dcDao.findById(volume.getDataCenterId()); - if (!dataCenter.isLocalStorageEnabled()) { - DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume - .getDiskOfferingId()); - if (diskOffering.getUseLocalStorage()) { - throw new InvalidParameterValueException( - "Zone is not configured to use local storage but volume's disk offering " - + diskOffering.getName() + " uses it"); - } - } - - // permission check - _accountMgr.checkAccess(caller, null, true, volume, vm); - - // Check if volume is stored on secondary Storage. - boolean isVolumeOnSec = false; - VolumeHostVO volHostVO = _volumeHostDao.findByVolumeId(volume.getId()); - if (volHostVO != null) { - isVolumeOnSec = true; - if (!(volHostVO.getDownloadState() == Status.DOWNLOADED)) { - throw new InvalidParameterValueException( - "Volume is not uploaded yet. Please try this operation once the volume is uploaded"); - } - } - - if (!(Volume.State.Allocated.equals(volume.getState()) - || Volume.State.Ready.equals(volume.getState()) || Volume.State.UploadOp - .equals(volume.getState()))) { - throw new InvalidParameterValueException( - "Volume state must be in Allocated, Ready or in Uploaded state"); - } - - VolumeVO rootVolumeOfVm = null; - List rootVolumesOfVm = _volsDao.findByInstanceAndType(vmId, - Volume.Type.ROOT); - if (rootVolumesOfVm.size() != 1) { - throw new CloudRuntimeException( - "The VM " - + vm.getHostName() - + " has more than one ROOT volume and is in an invalid state."); - } else { - rootVolumeOfVm = rootVolumesOfVm.get(0); - } - - HypervisorType rootDiskHyperType = vm.getHypervisorType(); - - HypervisorType dataDiskHyperType = _volsDao.getHypervisorType(volume - .getId()); - if (dataDiskHyperType != HypervisorType.None - && rootDiskHyperType != dataDiskHyperType) { - throw new InvalidParameterValueException( - "Can't attach a volume created by: " + dataDiskHyperType - + " to a " + rootDiskHyperType + " vm"); - } - - // allocate deviceId - List vols = _volsDao.findByInstance(vmId); - 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.getHostName()); - } - } - } else { - // allocate deviceId here - List devIds = new ArrayList(); - 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()); - } - - boolean createVolumeOnBackend = true; - if (rootVolumeOfVm.getState() == Volume.State.Allocated) { - createVolumeOnBackend = false; - if (isVolumeOnSec) { - throw new CloudRuntimeException( - "Cant attach uploaded volume to the vm which is not created. Please start it and then retry"); - } - } - - // create volume on the backend only when vm's root volume is allocated - if (createVolumeOnBackend) { - if (volume.getState().equals(Volume.State.Allocated) - || isVolumeOnSec) { - /* Need to create the volume */ - VMTemplateVO rootDiskTmplt = _templateDao.findById(vm - .getTemplateId()); - DataCenterVO dcVO = _dcDao.findById(vm - .getDataCenterIdToDeployIn()); - HostPodVO pod = _podDao.findById(vm.getPodIdToDeployIn()); - StoragePoolVO rootDiskPool = _storagePoolDao - .findById(rootVolumeOfVm.getPoolId()); - ServiceOfferingVO svo = _serviceOfferingDao.findById(vm - .getServiceOfferingId()); - DiskOfferingVO diskVO = _diskOfferingDao.findById(volume - .getDiskOfferingId()); - Long clusterId = (rootDiskPool == null ? null : rootDiskPool - .getClusterId()); - - if (!isVolumeOnSec) { - volume = _storageMgr.createVolume(volume, vm, - rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, - new ArrayList(), volume.getSize(), - rootDiskHyperType); - } else { - try { - // Format of data disk should be the same as root disk - if (!volHostVO - .getFormat() - .getFileExtension() - .equals(_storageMgr - .getSupportedImageFormatForCluster(rootDiskPool - .getClusterId()))) { - throw new InvalidParameterValueException( - "Failed to attach volume to VM since volumes format " - + volHostVO.getFormat() - .getFileExtension() - + " is not compatible with the vm hypervisor type"); - } - - // Check that there is some shared storage. - StoragePoolVO vmRootVolumePool = _storagePoolDao - .findById(rootVolumeOfVm.getPoolId()); - List sharedVMPools = _storagePoolDao - .findPoolsByTags( - vmRootVolumePool.getDataCenterId(), - vmRootVolumePool.getPodId(), - vmRootVolumePool.getClusterId(), null, - true); - if (sharedVMPools.size() == 0) { - throw new CloudRuntimeException( - "Cannot attach volume since there are no shared storage pools in the VM's cluster to copy the uploaded volume to."); - } - - volume = _storageMgr.copyVolumeFromSecToPrimary(volume, - vm, rootDiskTmplt, dcVO, pod, - rootDiskPool.getClusterId(), svo, diskVO, - new ArrayList(), - volume.getSize(), rootDiskHyperType); - } catch (NoTransitionException e) { - throw new CloudRuntimeException( - "Unable to transition the volume ", e); - } - } - - if (volume == null) { - throw new CloudRuntimeException( - "Failed to create volume when attaching it to VM: " - + vm.getHostName()); - } - } - - StoragePoolVO vmRootVolumePool = _storagePoolDao - .findById(rootVolumeOfVm.getPoolId()); - DiskOfferingVO volumeDiskOffering = _diskOfferingDao - .findById(volume.getDiskOfferingId()); - String[] volumeTags = volumeDiskOffering.getTagsArray(); - - boolean isVolumeOnSharedPool = !volumeDiskOffering - .getUseLocalStorage(); - StoragePoolVO sourcePool = _storagePoolDao.findById(volume - .getPoolId()); - List matchingVMPools = _storagePoolDao - .findPoolsByTags(vmRootVolumePool.getDataCenterId(), - vmRootVolumePool.getPodId(), - vmRootVolumePool.getClusterId(), volumeTags, - isVolumeOnSharedPool); - boolean moveVolumeNeeded = true; - if (matchingVMPools.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 sourcePoolId = sourcePool.getId(); - Long sourcePoolDcId = sourcePool.getDataCenterId(); - Long sourcePoolPodId = sourcePool.getPodId(); - Long sourcePoolClusterId = sourcePool.getClusterId(); - for (StoragePoolVO vmPool : matchingVMPools) { - long vmPoolId = vmPool.getId(); - Long vmPoolDcId = vmPool.getDataCenterId(); - Long vmPoolPodId = vmPool.getPodId(); - Long vmPoolClusterId = vmPool.getClusterId(); - - // Moving a volume is not required if storage pools belongs - // to same cluster in case of shared volume or - // identical storage pool in case of local - if (sourcePoolDcId == vmPoolDcId - && sourcePoolPodId == vmPoolPodId - && sourcePoolClusterId == vmPoolClusterId - && (isVolumeOnSharedPool || sourcePoolId == vmPoolId)) { - moveVolumeNeeded = false; - break; - } - } - } - - if (moveVolumeNeeded) { - if (isVolumeOnSharedPool) { - // Move the volume to a storage pool in the VM's zone, pod, - // or cluster - try { - volume = _storageMgr.moveVolume(volume, - vmRootVolumePool.getDataCenterId(), - vmRootVolumePool.getPodId(), - vmRootVolumePool.getClusterId(), - dataDiskHyperType); - } catch (ConcurrentOperationException e) { - throw new CloudRuntimeException(e.toString()); - } - } else { - throw new CloudRuntimeException( - "Failed to attach local data volume " - + volume.getName() - + " to VM " - + vm.getDisplayName() - + " as migration of local data volume is not allowed"); - } - } - } - - 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.getHostName(); - 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 || (answer != null && answer.getResult())) { - // 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()) { - errorMsg += "; " + details; - } - } - throw new CloudRuntimeException(errorMsg); - } - } - - @Override - @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true) - public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) { - Account caller = 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); - } - - Long vmId = null; - - if (cmmd.getVirtualMachineId() == null) { - vmId = volume.getInstanceId(); - } else { - vmId = cmmd.getVirtualMachineId(); - } - - // Check that the volume ID is valid - if (volume == null) { - throw new InvalidParameterValueException( - "Unable to find volume with ID: " + volumeId); - } - - // Permissions check - _accountMgr.checkAccess(caller, null, true, volume); - - // Check that the volume is a data volume - if (volume.getVolumeType() != Volume.Type.DATADISK) { - throw new InvalidParameterValueException( - "Please specify a data volume."); - } - - // Check that the volume is currently attached to a VM - if (vmId == null) { - throw new InvalidParameterValueException( - "The specified volume is not attached to a VM."); - } - - // 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."); - } - - 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 detach volume: " + volume.getName() - + " from VM: " + vm.getHostName(); - 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); - } - - return _volsDao.findById(volumeId); - } else { - - if (answer != null) { - String details = answer.getDetails(); - if (details != null && !details.isEmpty()) { - errorMsg += "; " + details; - } - } - - throw new CloudRuntimeException(errorMsg); - } - } - - @Override - public boolean attachISOToVM(long vmId, long isoId, boolean attach) { - UserVmVO vm = _vmDao.findById(vmId); - - if (vm == null) { - return false; - } 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"); - return false; - } - // Get the path of the ISO - Pair isoPathPair = null; - if (tmplt.getTemplateType() == TemplateType.PERHOST) { - isoPath = tmplt.getName(); - } else { - isoPathPair = _storageMgr.getAbsoluteIsoPath(isoId, - vm.getDataCenterIdToDeployIn()); - if (isoPathPair == null) { - s_logger.warn("Couldn't get absolute iso path"); - return false; - } else { - isoPath = isoPathPair.first(); - } - } - - String vmName = vm.getInstanceName(); - - 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 && a.getResult()); - } - - 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()); - - if (vm == null || vm.getState() == State.Destroyed - || vm.getState() == State.Expunging || vm.getRemoved() != null) { - s_logger.warn("Vm id=" + vmId + " doesn't exist"); - return null; - } - - if (vm.getState() == State.Running && vm.getHostId() != null) { - 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") - /* - * TODO: cleanup eventually - Refactored API call - */ - public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) { - Long vmId = cmd.getId(); - Long svcOffId = cmd.getServiceOfferingId(); - Account caller = UserContext.current().getCaller(); - - // Verify input parameters - UserVmVO vmInstance = _vmDao.findById(vmId); - if (vmInstance == null) { - throw new InvalidParameterValueException( - "unable to find a virtual machine with id " + vmId); - } - - _accountMgr.checkAccess(caller, null, true, vmInstance); - - // Check that the specified service offering ID is valid - _itMgr.checkIfCanUpgrade(vmInstance, svcOffId); - - _itMgr.upgradeVmDb(vmId, svcOffId); - - return _vmDao.findById(vmInstance.getId()); - } - - @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(); - - 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 - public UserVm recoverVirtualMachine(RecoverVMCmd cmd) - throws ResourceAllocationException, CloudRuntimeException { - - Long vmId = cmd.getId(); - Account caller = UserContext.current().getCaller(); - - // Verify input parameters - UserVmVO vm = _vmDao.findById(vmId.longValue()); - - if (vm == null) { - throw new InvalidParameterValueException( - "unable to find a virtual machine with id " + vmId); - } - - // check permissions - _accountMgr.checkAccess(caller, null, true, vm); - - if (vm.getRemoved() != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unable to find vm or vm is removed: " + vmId); - } - 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); - } - throw new InvalidParameterValueException("Vm with id " + vmId - + " is not in the right state"); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Recovering vm " + vmId); - } - - Transaction txn = Transaction.currentTxn(); - AccountVO account = null; - txn.start(); - - account = _accountDao.lockRow(vm.getAccountId(), true); - - // 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 - _resourceLimitMgr.checkResourceLimit(account, ResourceType.user_vm); - - _haMgr.cancelDestroy(vm, vm.getHostId()); - - try { - if (!_itMgr.stateTransitTo(vm, - VirtualMachine.Event.RecoveryRequested, null)) { - 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); - } - } catch (NoTransitionException e) { - 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) { - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - // Create an event - Long templateId = volume.getTemplateId(); - Long diskOfferingId = volume.getDiskOfferingId(); - Long offeringId = null; - if (diskOfferingId != null) { - DiskOfferingVO offering = _diskOfferingDao - .findById(diskOfferingId); - 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()); - _usageEventDao.persist(usageEvent); - } - } - - _resourceLimitMgr.incrementResourceCount(account.getId(), - ResourceType.volume, new Long(volumes.size())); - - _resourceLimitMgr.incrementResourceCount(account.getId(), - ResourceType.user_vm); - - txn.commit(); - - return _vmDao.findById(vmId); - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - _name = name; - - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - _configDao = locator.getDao(ConfigurationDao.class); - if (_configDao == null) { - throw new ConfigurationException( - "Unable to get the configuration dao."); - } - - Map configs = _configDao.getConfiguration( - "AgentManager", params); - - _instance = configs.get("instance.name"); - if (_instance == null) { - _instance = "DEFAULT"; - } - - String value = _configDao - .getValue(Config.CreatePrivateTemplateFromVolumeWait.toString()); - _createprivatetemplatefromvolumewait = NumbersUtil.parseInt(value, - Integer.parseInt(Config.CreatePrivateTemplateFromVolumeWait - .getDefaultValue())); - - value = _configDao - .getValue(Config.CreatePrivateTemplateFromSnapshotWait - .toString()); - _createprivatetemplatefromsnapshotwait = NumbersUtil.parseInt(value, - Integer.parseInt(Config.CreatePrivateTemplateFromSnapshotWait - .getDefaultValue())); - - String workers = configs.get("expunge.workers"); - int wrks = NumbersUtil.parseInt(workers, 10); - - String time = configs.get("expunge.interval"); - _expungeInterval = NumbersUtil.parseInt(time, 86400); - if (_expungeInterval < 600) { - _expungeInterval = 600; - } - time = configs.get("expunge.delay"); - _expungeDelay = NumbersUtil.parseInt(time, _expungeInterval); - if (_expungeDelay < 600) { - _expungeDelay = 600; - } - _executor = Executors.newScheduledThreadPool(wrks, - new NamedThreadFactory("UserVm-Scavenger")); - - _itMgr.registerGuru(VirtualMachine.Type.User, this); - - VirtualMachine.State.getStateMachine().registerListener( - new UserVmStateListener(_usageEventDao, _networkDao, _nicDao)); - - s_logger.info("User VM Manager is configured."); - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - _executor.scheduleWithFixedDelay(new ExpungeTask(), _expungeInterval, - _expungeInterval, TimeUnit.SECONDS); - return true; - } - - @Override - public boolean stop() { - _executor.shutdown(); - return true; - } - - protected UserVmManagerImpl() { - } - - public String getRandomPrivateTemplateName() { - return UUID.randomUUID().toString(); - } - - @Override - public Long convertToId(String vmName) { - if (!VirtualMachineName.isValidVmName(vmName, _instance)) { - return null; - } - return VirtualMachineName.getVmId(vmName); - } - - @Override - public boolean expunge(UserVmVO vm, long callerUserId, Account caller) { - UserContext ctx = UserContext.current(); - ctx.setAccountId(vm.getAccountId()); - - try { - // expunge the vm - 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); - } - - return true; - - } catch (ResourceUnavailableException e) { - s_logger.warn("Unable to expunge " + vm, e); - return false; - } catch (OperationTimedoutException e) { - s_logger.warn("Operation time out on expunging " + vm, e); - return false; - } catch (ConcurrentOperationException e) { - s_logger.warn("Concurrent operations on expunging " + vm, e); - return false; - } - } - - private boolean cleanupVmResources(long vmId) { - boolean success = true; - // Remove vm from security groups - _securityGroupMgr.removeInstanceFromGroups(vmId); - - // Remove vm from instance group - removeInstanceFromInstanceGroup(vmId); - - // cleanup firewall rules - if (_firewallMgr.revokeFirewallRulesForVm(vmId)) { - s_logger.debug("Firewall rules are removed successfully as a part of vm id=" - + vmId + " expunge"); - } else { - success = false; - s_logger.warn("Fail to remove firewall rules as a part of vm id=" - + vmId + " expunge"); - } - - // 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 - 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 and disassociate ip if elasticIP is enabled - IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(vmId); - try { - if (ip != null) { - if (_rulesMgr.disableStaticNat(ip.getId(), - _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM), - User.UID_SYSTEM, true)) { - s_logger.debug("Disabled 1-1 nat for ip address " + ip - + " as a part of vm id=" + vmId + " expunge"); - } else { - s_logger.warn("Failed to disable static nat for ip address " - + ip + " as a part of vm id=" + vmId + " expunge"); - success = false; - } - } - } catch (ResourceUnavailableException e) { - success = false; - s_logger.warn("Failed to disable static nat for ip address " + ip - + " as a part of vm id=" + vmId - + " expunge because resource is unavailable", e); - } - - return success; - } - - @Override - public void deletePrivateTemplateRecord(Long templateId) { - if (templateId != null) { - _templateDao.remove(templateId); - } - } - - @Override - @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true) - public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd, - Account templateOwner) throws ResourceAllocationException { - Long userId = UserContext.current().getCallerUserId(); - - Account caller = UserContext.current().getCaller(); - boolean isAdmin = (isAdmin(caller.getType())); - - _accountMgr.checkAccess(caller, null, true, templateOwner); - - 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"); - } - - if (cmd.getTemplateTag() != null) { - if (!_accountService.isRootAdmin(caller.getType())) { - throw new PermissionDeniedException( - "Parameter templatetag can only be specified by a Root Admin, permission denied"); - } - } - - // do some parameter defaulting - Integer bits = cmd.getBits(); - Boolean requiresHvm = cmd.getRequiresHvm(); - Boolean passwordEnabled = cmd.isPasswordEnabled(); - Boolean isPublic = cmd.isPublic(); - Boolean featured = cmd.isFeatured(); - int bitsValue = ((bits == null) ? 64 : bits.intValue()); - boolean requiresHvmValue = ((requiresHvm == null) ? true : requiresHvm - .booleanValue()); - boolean passwordEnabledValue = ((passwordEnabled == null) ? false - : passwordEnabled.booleanValue()); - if (isPublic == null) { - isPublic = Boolean.FALSE; - } - 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)) { - throw new InvalidParameterValueException( - "Failed to create private template record, neither volume ID nor snapshot ID were specified."); - } - 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 - + ")"); - } - - HypervisorType hyperType; - VolumeVO volume = null; - VMTemplateVO privateTemplate = 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); - } - // check permissions - _accountMgr.checkAccess(caller, null, true, volume); - - // 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"; - if (s_logger.isInfoEnabled()) { - s_logger.info(msg); - } - throw new CloudRuntimeException(msg); - } - 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); - } - - volume = _volsDao.findById(snapshot.getVolumeId()); - VolumeVO snapshotVolume = _volsDao - .findByIdIncludingRemoved(snapshot.getVolumeId()); - - // check permissions - _accountMgr.checkAccess(caller, null, true, snapshot); - - if (snapshot.getStatus() != Snapshot.Status.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" - + snapshotId + " is not in " + Snapshot.Status.BackedUp - + " state yet and can't be used for template creation"); - } - - /* - * // bug #11428. Operation not supported if vmware and snapshots - * parent volume = ROOT if(snapshot.getHypervisorType() == - * HypervisorType.VMware && snapshotVolume.getVolumeType() == - * Type.DATADISK){ throw new UnsupportedServiceException( - * "operation not supported, snapshot with id " + snapshotId + - * " is created from Data Disk"); } - */ - - hyperType = snapshot.getHypervisorType(); - } - - _resourceLimitMgr.checkResourceLimit(templateOwner, - ResourceType.template); - - 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; - Long sourceTemplateId = null; - if (volume != null) { - VMTemplateVO template = ApiDBUtils.findTemplateById(volume - .getTemplateId()); - isExtractable = template != null - && template.isExtractable() - && template.getTemplateType() != Storage.TemplateType.SYSTEM; - if (template != null) { - sourceTemplateId = template.getId(); - } else if (volume.getVolumeType() == Type.ROOT) { // vm created out - // of blank - // template - UserVm userVm = ApiDBUtils.findUserVmById(volume - .getInstanceId()); - sourceTemplateId = userVm.getIsoId(); - } - } - String templateTag = cmd.getTemplateTag(); - if (templateTag != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Adding template tag: " + templateTag); - } - } - privateTemplate = new VMTemplateVO(nextTemplateId, uniqueName, name, - ImageFormat.RAW, isPublic, featured, isExtractable, - TemplateType.USER, null, null, requiresHvmValue, bitsValue, - templateOwner.getId(), null, description, passwordEnabledValue, - guestOS.getId(), true, hyperType, templateTag, cmd.getDetails()); - if (sourceTemplateId != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("This template is getting created from other template, setting source template Id to: " - + sourceTemplateId); - } - } - privateTemplate.setSourceTemplateId(sourceTemplateId); - - VMTemplateVO template = _templateDao.persist(privateTemplate); - // Increment the number of templates - if (template != null) { - if (cmd.getDetails() != null) { - _templateDetailsDao.persist(template.getId(), cmd.getDetails()); - } - - _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), - ResourceType.template); - } - - if (template != null) { - return template; - } else { - throw new CloudRuntimeException("Failed to create a template"); - } - - } - - @Override - @DB - @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true) - public VMTemplateVO createPrivateTemplate(CreateTemplateCmd command) - throws CloudRuntimeException { - Long userId = UserContext.current().getCallerUserId(); - if (userId == null) { - userId = User.UID_SYSTEM; - } - long templateId = command.getEntityId(); - Long volumeId = command.getVolumeId(); - Long snapshotId = command.getSnapshotId(); - SnapshotCommand cmd = null; - VMTemplateVO privateTemplate = null; - - String uniqueName = getRandomPrivateTemplateName(); - - StoragePoolVO pool = null; - HostVO secondaryStorageHost = null; - Long zoneId = null; - Long accountId = null; - SnapshotVO snapshot = null; - String secondaryStorageURL = null; - try { - if (snapshotId != null) { // create template from snapshot - snapshot = _snapshotDao.findById(snapshotId); - if (snapshot == null) { - throw new CloudRuntimeException( - "Unable to find Snapshot for Id " + snapshotId); - } - zoneId = snapshot.getDataCenterId(); - secondaryStorageHost = _snapshotMgr - .getSecondaryStorageHost(snapshot); - secondaryStorageURL = _snapshotMgr - .getSecondaryStorageURL(snapshot); - String name = command.getTemplateName(); - String backupSnapshotUUID = snapshot.getBackupSnapshotId(); - 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 pools = _storageMgr - .ListByDataCenterHypervisor(zoneId, - snapshot.getHypervisorType()); - if (pools == null || pools.size() == 0) { - throw new CloudRuntimeException( - "Unable to find storage pools in zone " + zoneId); - } - pool = pools.get(0); - if (snapshot.getVersion() != null - && snapshot.getVersion().equalsIgnoreCase("2.1")) { - VolumeVO volume = _volsDao - .findByIdIncludingRemoved(volumeId); - if (volume == null) { - throw new CloudRuntimeException( - "failed to upgrade snapshot " - + snapshotId - + " due to unable to find orignal volume:" - + volumeId + ", try it later "); - } - if (volume.getTemplateId() == null) { - _snapshotDao.updateSnapshotVersion(volumeId, "2.1", - "2.2"); - } else { - VMTemplateVO template = _templateDao - .findByIdIncludingRemoved(volume - .getTemplateId()); - 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)) { - 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)) { - throw new CloudRuntimeException( - "Creating template failed due to volume:" - + volumeId - + " is being used, try it later "); - } - Answer answer = null; - try { - answer = _storageMgr.sendToPool(pool, cmd); - cmd = null; - } catch (StorageUnavailableException e) { - } finally { - _volsDao.unlockFromLockTable(volumeId.toString()); - } - if ((answer != null) && answer.getResult()) { - _snapshotDao.updateSnapshotVersion(volumeId, "2.1", - "2.2"); - } else { - throw new CloudRuntimeException( - "Unable to upgrade snapshot"); - } - } - } - if (snapshot.getSwiftId() != null && snapshot.getSwiftId() != 0) { - _snapshotMgr.downloadSnapshotsFromSwift(snapshot); - } + protected VolumeDao _volsDao = null; + @Inject + protected DataCenterDao _dcDao = null; + @Inject + protected FirewallRulesDao _rulesDao = null; + @Inject + protected LoadBalancerVMMapDao _loadBalancerVMMapDao = null; + @Inject + protected PortForwardingRulesDao _portForwardingDao; + @Inject + protected IPAddressDao _ipAddressDao = null; + @Inject + protected HostPodDao _podDao = 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 HighAvailabilityManager _haMgr = null; + @Inject + protected AlertManager _alertMgr = null; + @Inject + protected AccountManager _accountMgr; + @Inject + protected AccountService _accountService; + @Inject + protected AsyncJobManager _asyncMgr; + @Inject + protected ClusterDao _clusterDao; + @Inject + protected StoragePoolDao _storagePoolDao; + @Inject + protected SecurityGroupManager _securityGroupMgr; + @Inject + protected ServiceOfferingDao _serviceOfferingDao; + @Inject + protected NetworkOfferingDao _networkOfferingDao; + @Inject + protected InstanceGroupDao _vmGroupDao; + @Inject + protected InstanceGroupVMMapDao _groupVMMapDao; + @Inject + protected VirtualMachineManager _itMgr; + @Inject + protected NetworkDao _networkDao; + @Inject + protected NicDao _nicDao; + @Inject + protected VpcDao _vpcDao; + @Inject + protected RulesManager _rulesMgr; + @Inject + protected LoadBalancingRulesManager _lbMgr; + @Inject + protected UsageEventDao _usageEventDao; + @Inject + protected SSHKeyPairDao _sshKeyPairDao; + @Inject + protected UserVmDetailsDao _vmDetailsDao; + @Inject + protected HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; + @Inject + protected SecurityGroupDao _securityGroupDao; + @Inject + protected CapacityManager _capacityMgr;; + @Inject + protected VMInstanceDao _vmInstanceDao; + @Inject + protected ResourceLimitService _resourceLimitMgr; + @Inject + protected FirewallManager _firewallMgr; + @Inject + protected ProjectManager _projectMgr; + @Inject + protected ResourceManager _resourceMgr; + @Inject + protected NetworkServiceMapDao _ntwkSrvcDao; + @Inject + SecurityGroupVMMapDao _securityGroupVMMapDao; + @Inject + protected ItWorkDao _workDao; + @Inject + protected VolumeHostDao _volumeHostDao; + @Inject + ResourceTagDao _resourceTagDao; + @Inject + PhysicalNetworkDao _physicalNetworkDao; + @Inject + VpcManager _vpcMgr; + @Inject + protected GuestOSCategoryDao _guestOSCategoryDao; + + protected ScheduledExecutorService _executor = null; + protected int _expungeInterval; + protected int _expungeDelay; + + protected String _name; + protected String _instance; + protected String _zone; + + private ConfigurationDao _configDao; + private int _createprivatetemplatefromvolumewait; + private int _createprivatetemplatefromsnapshotwait; + + @Inject + protected OrchestrationService _orchSrvc; + + @Override + public UserVmVO getVirtualMachine(long vmId) { + return _vmDao.findById(vmId); + } + + @Override + public List getVirtualMachines(long hostId) { + 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 { + Account caller = UserContext.current().getCaller(); + Long vmId = cmd.getId(); + UserVmVO userVm = _vmDao.findById(cmd.getId()); + _vmDao.loadDetails(userVm); + + // 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"); + } + + _accountMgr.checkAccess(caller, null, true, userVm); + + boolean result = resetVMPasswordInternal(cmd, password); + + if (result) { + userVm.setPassword(password); + // update the password in vm_details table too + // Check if an SSH key pair was selected for the instance and if so + // use it to encrypt & save the vm password + String sshPublicKey = userVm.getDetail("SSH.PublicKey"); + 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"); + } + + userVm.setDetail("Encrypted.Password", encryptedPasswd); + _vmDao.saveDetails(userVm); + } + } else { + throw new CloudRuntimeException( + "Failed to reset password for the virtual machine "); + } + + return userVm; + } + + private boolean resetVMPasswordInternal(ResetVMPasswordCmd cmd, + String password) throws ResourceUnavailableException, + InsufficientCapacityException { + Long vmId = cmd.getId(); + Long userId = UserContext.current().getCallerUserId(); + VMInstanceVO vmInstance = _vmDao.findById(vmId); + + if (password == null || password.equals("")) { + return false; + } + + VMTemplateVO template = _templateDao + .findByIdIncludingRemoved(vmInstance.getTemplateId()); + if (template.getEnablePassword()) { + Nic defaultNic = _networkMgr.getDefaultNic(vmId); + if (defaultNic == null) { + 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, + _networkMgr + .isSecurityGroupSupportedInNetwork(defaultNetwork), + _networkMgr.getNetworkTag(template.getHypervisorType(), + defaultNetwork)); + VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl( + vmInstance); + vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, + password); + + UserDataServiceProvider element = _networkMgr + .getPasswordResetProvider(defaultNetwork); + if (element == null) { + throw new CloudRuntimeException( + "Can't find network element for " + + Service.UserData.getName() + + " provider needed for password reset"); + } + + boolean result = element.savePassword(defaultNetwork, + defaultNicProfile, vmProfile); + + // 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"); + return false; + } else { + if (vmInstance.getState() == State.Stopped) { + s_logger.debug("Vm " + + vmInstance + + " is stopped, not rebooting it as a part of password reset"); + return true; + } + + if (rebootVirtualMachine(userId, vmId) == null) { + s_logger.warn("Failed to reboot the vm " + vmInstance); + return false; + } else { + s_logger.debug("Vm " + + vmInstance + + " is rebooted successfully as a part of password reset"); + return true; + } + } + } else { + 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); + 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) { + return status; + } else { + return status; + } + } + + private int getMaxDataVolumesSupported(UserVmVO vm) { + Long hostId = vm.getHostId(); + if (hostId == null) { + hostId = vm.getLastHostId(); + } + HostVO host = _hostDao.findById(hostId); + Integer maxDataVolumesSupported = null; + if (host != null) { + _hostDao.loadDetails(host); + maxDataVolumesSupported = _hypervisorCapabilitiesDao + .getMaxDataVolumesLimit(host.getHypervisorType(), + host.getDetail("product_version")); + } + if (maxDataVolumesSupported == null) { + maxDataVolumesSupported = 6; // 6 data disks by default if nothing + // is specified in + // 'hypervisor_capabilities' table + } + + return maxDataVolumesSupported.intValue(); + } + + @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 caller = 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."); + } + + // 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."); + } + + // Check that the volume is not destroyed + if (volume.getState() == Volume.State.Destroy) { + 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) { + 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."); + } + + // 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"); + } + } + + // Check that the number of data volumes attached to VM is less than + // that supported by hypervisor + List existingDataVolumes = _volsDao.findByInstanceAndType( + vmId, Volume.Type.DATADISK); + int maxDataVolumesSupported = getMaxDataVolumesSupported(vm); + if (existingDataVolumes.size() >= maxDataVolumesSupported) { + throw new InvalidParameterValueException( + "The specified VM already has the maximum number of data disks (" + + maxDataVolumesSupported + + "). Please specify another VM."); + } + + // Check that the VM and the volume are in the same zone + if (vm.getDataCenterIdToDeployIn() != volume.getDataCenterId()) { + throw new InvalidParameterValueException( + "Please specify a VM that is in the same zone as the volume."); + } + + // If local storage is disabled then attaching a volume with local disk + // offering not allowed + DataCenterVO dataCenter = _dcDao.findById(volume.getDataCenterId()); + if (!dataCenter.isLocalStorageEnabled()) { + DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume + .getDiskOfferingId()); + if (diskOffering.getUseLocalStorage()) { + throw new InvalidParameterValueException( + "Zone is not configured to use local storage but volume's disk offering " + + diskOffering.getName() + " uses it"); + } + } + + // permission check + _accountMgr.checkAccess(caller, null, true, volume, vm); + + // Check if volume is stored on secondary Storage. + boolean isVolumeOnSec = false; + VolumeHostVO volHostVO = _volumeHostDao.findByVolumeId(volume.getId()); + if (volHostVO != null) { + isVolumeOnSec = true; + if (!(volHostVO.getDownloadState() == Status.DOWNLOADED)) { + throw new InvalidParameterValueException( + "Volume is not uploaded yet. Please try this operation once the volume is uploaded"); + } + } + + if (!(Volume.State.Allocated.equals(volume.getState()) + || Volume.State.Ready.equals(volume.getState()) || Volume.State.UploadOp + .equals(volume.getState()))) { + throw new InvalidParameterValueException( + "Volume state must be in Allocated, Ready or in Uploaded state"); + } + + VolumeVO rootVolumeOfVm = null; + List rootVolumesOfVm = _volsDao.findByInstanceAndType(vmId, + Volume.Type.ROOT); + if (rootVolumesOfVm.size() != 1) { + throw new CloudRuntimeException( + "The VM " + + vm.getHostName() + + " has more than one ROOT volume and is in an invalid state."); + } else { + rootVolumeOfVm = rootVolumesOfVm.get(0); + } + + HypervisorType rootDiskHyperType = vm.getHypervisorType(); + + HypervisorType dataDiskHyperType = _volsDao.getHypervisorType(volume + .getId()); + if (dataDiskHyperType != HypervisorType.None + && rootDiskHyperType != dataDiskHyperType) { + throw new InvalidParameterValueException( + "Can't attach a volume created by: " + dataDiskHyperType + + " to a " + rootDiskHyperType + " vm"); + } + + // allocate deviceId + List vols = _volsDao.findByInstance(vmId); + 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.getHostName()); + } + } + } else { + // allocate deviceId here + List devIds = new ArrayList(); + 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()); + } + + boolean createVolumeOnBackend = true; + if (rootVolumeOfVm.getState() == Volume.State.Allocated) { + createVolumeOnBackend = false; + if (isVolumeOnSec) { + throw new CloudRuntimeException( + "Cant attach uploaded volume to the vm which is not created. Please start it and then retry"); + } + } + + // create volume on the backend only when vm's root volume is allocated + if (createVolumeOnBackend) { + if (volume.getState().equals(Volume.State.Allocated) + || isVolumeOnSec) { + /* Need to create the volume */ + VMTemplateVO rootDiskTmplt = _templateDao.findById(vm + .getTemplateId()); + DataCenterVO dcVO = _dcDao.findById(vm + .getDataCenterIdToDeployIn()); + HostPodVO pod = _podDao.findById(vm.getPodIdToDeployIn()); + StoragePoolVO rootDiskPool = _storagePoolDao + .findById(rootVolumeOfVm.getPoolId()); + ServiceOfferingVO svo = _serviceOfferingDao.findById(vm + .getServiceOfferingId()); + DiskOfferingVO diskVO = _diskOfferingDao.findById(volume + .getDiskOfferingId()); + Long clusterId = (rootDiskPool == null ? null : rootDiskPool + .getClusterId()); + + if (!isVolumeOnSec) { + volume = _storageMgr.createVolume(volume, vm, + rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, + new ArrayList(), volume.getSize(), + rootDiskHyperType); + } else { + try { + // Format of data disk should be the same as root disk + if (!volHostVO + .getFormat() + .getFileExtension() + .equals(_storageMgr + .getSupportedImageFormatForCluster(rootDiskPool + .getClusterId()))) { + throw new InvalidParameterValueException( + "Failed to attach volume to VM since volumes format " + + volHostVO.getFormat() + .getFileExtension() + + " is not compatible with the vm hypervisor type"); + } + + // Check that there is some shared storage. + StoragePoolVO vmRootVolumePool = _storagePoolDao + .findById(rootVolumeOfVm.getPoolId()); + List sharedVMPools = _storagePoolDao + .findPoolsByTags( + vmRootVolumePool.getDataCenterId(), + vmRootVolumePool.getPodId(), + vmRootVolumePool.getClusterId(), null, + true); + if (sharedVMPools.size() == 0) { + throw new CloudRuntimeException( + "Cannot attach volume since there are no shared storage pools in the VM's cluster to copy the uploaded volume to."); + } + + volume = _storageMgr.copyVolumeFromSecToPrimary(volume, + vm, rootDiskTmplt, dcVO, pod, + rootDiskPool.getClusterId(), svo, diskVO, + new ArrayList(), + volume.getSize(), rootDiskHyperType); + } catch (NoTransitionException e) { + throw new CloudRuntimeException( + "Unable to transition the volume ", e); + } + } + + if (volume == null) { + throw new CloudRuntimeException( + "Failed to create volume when attaching it to VM: " + + vm.getHostName()); + } + } + + StoragePoolVO vmRootVolumePool = _storagePoolDao + .findById(rootVolumeOfVm.getPoolId()); + DiskOfferingVO volumeDiskOffering = _diskOfferingDao + .findById(volume.getDiskOfferingId()); + String[] volumeTags = volumeDiskOffering.getTagsArray(); + + boolean isVolumeOnSharedPool = !volumeDiskOffering + .getUseLocalStorage(); + StoragePoolVO sourcePool = _storagePoolDao.findById(volume + .getPoolId()); + List matchingVMPools = _storagePoolDao + .findPoolsByTags(vmRootVolumePool.getDataCenterId(), + vmRootVolumePool.getPodId(), + vmRootVolumePool.getClusterId(), volumeTags, + isVolumeOnSharedPool); + boolean moveVolumeNeeded = true; + if (matchingVMPools.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 sourcePoolId = sourcePool.getId(); + Long sourcePoolDcId = sourcePool.getDataCenterId(); + Long sourcePoolPodId = sourcePool.getPodId(); + Long sourcePoolClusterId = sourcePool.getClusterId(); + for (StoragePoolVO vmPool : matchingVMPools) { + long vmPoolId = vmPool.getId(); + Long vmPoolDcId = vmPool.getDataCenterId(); + Long vmPoolPodId = vmPool.getPodId(); + Long vmPoolClusterId = vmPool.getClusterId(); + + // Moving a volume is not required if storage pools belongs + // to same cluster in case of shared volume or + // identical storage pool in case of local + if (sourcePoolDcId == vmPoolDcId + && sourcePoolPodId == vmPoolPodId + && sourcePoolClusterId == vmPoolClusterId + && (isVolumeOnSharedPool || sourcePoolId == vmPoolId)) { + moveVolumeNeeded = false; + break; + } + } + } + + if (moveVolumeNeeded) { + if (isVolumeOnSharedPool) { + // Move the volume to a storage pool in the VM's zone, pod, + // or cluster + try { + volume = _storageMgr.moveVolume(volume, + vmRootVolumePool.getDataCenterId(), + vmRootVolumePool.getPodId(), + vmRootVolumePool.getClusterId(), + dataDiskHyperType); + } catch (ConcurrentOperationException e) { + throw new CloudRuntimeException(e.toString()); + } + } else { + throw new CloudRuntimeException( + "Failed to attach local data volume " + + volume.getName() + + " to VM " + + vm.getDisplayName() + + " as migration of local data volume is not allowed"); + } + } + } + + 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.getHostName(); + 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 || (answer != null && answer.getResult())) { + // 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()) { + errorMsg += "; " + details; + } + } + throw new CloudRuntimeException(errorMsg); + } + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true) + public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) { + Account caller = 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); + } + + Long vmId = null; + + if (cmmd.getVirtualMachineId() == null) { + vmId = volume.getInstanceId(); + } else { + vmId = cmmd.getVirtualMachineId(); + } + + // Check that the volume ID is valid + if (volume == null) { + throw new InvalidParameterValueException( + "Unable to find volume with ID: " + volumeId); + } + + // Permissions check + _accountMgr.checkAccess(caller, null, true, volume); + + // Check that the volume is a data volume + if (volume.getVolumeType() != Volume.Type.DATADISK) { + throw new InvalidParameterValueException( + "Please specify a data volume."); + } + + // Check that the volume is currently attached to a VM + if (vmId == null) { + throw new InvalidParameterValueException( + "The specified volume is not attached to a VM."); + } + + // 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."); + } + + 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 detach volume: " + volume.getName() + + " from VM: " + vm.getHostName(); + 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); + } + + return _volsDao.findById(volumeId); + } else { + + if (answer != null) { + String details = answer.getDetails(); + if (details != null && !details.isEmpty()) { + errorMsg += "; " + details; + } + } + + throw new CloudRuntimeException(errorMsg); + } + } + + @Override + public boolean attachISOToVM(long vmId, long isoId, boolean attach) { + UserVmVO vm = _vmDao.findById(vmId); + + if (vm == null) { + return false; + } 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"); + return false; + } + // Get the path of the ISO + Pair isoPathPair = null; + if (tmplt.getTemplateType() == TemplateType.PERHOST) { + isoPath = tmplt.getName(); + } else { + isoPathPair = _storageMgr.getAbsoluteIsoPath(isoId, + vm.getDataCenterIdToDeployIn()); + if (isoPathPair == null) { + s_logger.warn("Couldn't get absolute iso path"); + return false; + } else { + isoPath = isoPathPair.first(); + } + } + + String vmName = vm.getInstanceName(); + + 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 && a.getResult()); + } + + 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()); + + if (vm == null || vm.getState() == State.Destroyed + || vm.getState() == State.Expunging || vm.getRemoved() != null) { + s_logger.warn("Vm id=" + vmId + " doesn't exist"); + return null; + } + + if (vm.getState() == State.Running && vm.getHostId() != null) { + 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") + /* + * TODO: cleanup eventually - Refactored API call + */ + public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) { + Long vmId = cmd.getId(); + Long svcOffId = cmd.getServiceOfferingId(); + Account caller = UserContext.current().getCaller(); + + // Verify input parameters + UserVmVO vmInstance = _vmDao.findById(vmId); + if (vmInstance == null) { + throw new InvalidParameterValueException( + "unable to find a virtual machine with id " + vmId); + } + + _accountMgr.checkAccess(caller, null, true, vmInstance); + + // Check that the specified service offering ID is valid + _itMgr.checkIfCanUpgrade(vmInstance, svcOffId); + + _itMgr.upgradeVmDb(vmId, svcOffId); + + return _vmDao.findById(vmInstance.getId()); + } + + @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(); + + 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 + public UserVm recoverVirtualMachine(RecoverVMCmd cmd) + throws ResourceAllocationException, CloudRuntimeException { + + Long vmId = cmd.getId(); + Account caller = UserContext.current().getCaller(); + + // Verify input parameters + UserVmVO vm = _vmDao.findById(vmId.longValue()); + + if (vm == null) { + throw new InvalidParameterValueException( + "unable to find a virtual machine with id " + vmId); + } + + // check permissions + _accountMgr.checkAccess(caller, null, true, vm); + + if (vm.getRemoved() != null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unable to find vm or vm is removed: " + vmId); + } + 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); + } + throw new InvalidParameterValueException("Vm with id " + vmId + + " is not in the right state"); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Recovering vm " + vmId); + } + + Transaction txn = Transaction.currentTxn(); + AccountVO account = null; + txn.start(); + + account = _accountDao.lockRow(vm.getAccountId(), true); + + // 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 + _resourceLimitMgr.checkResourceLimit(account, ResourceType.user_vm); + + _haMgr.cancelDestroy(vm, vm.getHostId()); + + try { + if (!_itMgr.stateTransitTo(vm, + VirtualMachine.Event.RecoveryRequested, null)) { + 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); + } + } catch (NoTransitionException e) { + 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) { + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + // Create an event + Long templateId = volume.getTemplateId(); + Long diskOfferingId = volume.getDiskOfferingId(); + Long offeringId = null; + if (diskOfferingId != null) { + DiskOfferingVO offering = _diskOfferingDao + .findById(diskOfferingId); + 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()); + _usageEventDao.persist(usageEvent); + } + } + + _resourceLimitMgr.incrementResourceCount(account.getId(), + ResourceType.volume, new Long(volumes.size())); + + _resourceLimitMgr.incrementResourceCount(account.getId(), + ResourceType.user_vm); + + txn.commit(); + + return _vmDao.findById(vmId); + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + _name = name; + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + _configDao = locator.getDao(ConfigurationDao.class); + if (_configDao == null) { + throw new ConfigurationException( + "Unable to get the configuration dao."); + } + + Map configs = _configDao.getConfiguration( + "AgentManager", params); + + _instance = configs.get("instance.name"); + if (_instance == null) { + _instance = "DEFAULT"; + } + + String value = _configDao + .getValue(Config.CreatePrivateTemplateFromVolumeWait.toString()); + _createprivatetemplatefromvolumewait = NumbersUtil.parseInt(value, + Integer.parseInt(Config.CreatePrivateTemplateFromVolumeWait + .getDefaultValue())); + + value = _configDao + .getValue(Config.CreatePrivateTemplateFromSnapshotWait + .toString()); + _createprivatetemplatefromsnapshotwait = NumbersUtil.parseInt(value, + Integer.parseInt(Config.CreatePrivateTemplateFromSnapshotWait + .getDefaultValue())); + + String workers = configs.get("expunge.workers"); + int wrks = NumbersUtil.parseInt(workers, 10); + + String time = configs.get("expunge.interval"); + _expungeInterval = NumbersUtil.parseInt(time, 86400); + if (_expungeInterval < 600) { + _expungeInterval = 600; + } + time = configs.get("expunge.delay"); + _expungeDelay = NumbersUtil.parseInt(time, _expungeInterval); + if (_expungeDelay < 600) { + _expungeDelay = 600; + } + _executor = Executors.newScheduledThreadPool(wrks, + new NamedThreadFactory("UserVm-Scavenger")); + + _itMgr.registerGuru(VirtualMachine.Type.User, this); + + VirtualMachine.State.getStateMachine().registerListener( + new UserVmStateListener(_usageEventDao, _networkDao, _nicDao)); + + s_logger.info("User VM Manager is configured."); + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + _executor.scheduleWithFixedDelay(new ExpungeTask(), _expungeInterval, + _expungeInterval, TimeUnit.SECONDS); + return true; + } + + @Override + public boolean stop() { + _executor.shutdown(); + return true; + } + + protected UserVmManagerImpl() { + } + + public String getRandomPrivateTemplateName() { + return UUID.randomUUID().toString(); + } + + @Override + public Long convertToId(String vmName) { + if (!VirtualMachineName.isValidVmName(vmName, _instance)) { + return null; + } + return VirtualMachineName.getVmId(vmName); + } + + @Override + public boolean expunge(UserVmVO vm, long callerUserId, Account caller) { + UserContext ctx = UserContext.current(); + ctx.setAccountId(vm.getAccountId()); + + try { + // expunge the vm + 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); + } + + return true; + + } catch (ResourceUnavailableException e) { + s_logger.warn("Unable to expunge " + vm, e); + return false; + } catch (OperationTimedoutException e) { + s_logger.warn("Operation time out on expunging " + vm, e); + return false; + } catch (ConcurrentOperationException e) { + s_logger.warn("Concurrent operations on expunging " + vm, e); + return false; + } + } + + private boolean cleanupVmResources(long vmId) { + boolean success = true; + // Remove vm from security groups + _securityGroupMgr.removeInstanceFromGroups(vmId); + + // Remove vm from instance group + removeInstanceFromInstanceGroup(vmId); + + // cleanup firewall rules + if (_firewallMgr.revokeFirewallRulesForVm(vmId)) { + s_logger.debug("Firewall rules are removed successfully as a part of vm id=" + + vmId + " expunge"); + } else { + success = false; + s_logger.warn("Fail to remove firewall rules as a part of vm id=" + + vmId + " expunge"); + } + + // 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 + 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 and disassociate ip if elasticIP is enabled + IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(vmId); + try { + if (ip != null) { + if (_rulesMgr.disableStaticNat(ip.getId(), + _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM), + User.UID_SYSTEM, true)) { + s_logger.debug("Disabled 1-1 nat for ip address " + ip + + " as a part of vm id=" + vmId + " expunge"); + } else { + s_logger.warn("Failed to disable static nat for ip address " + + ip + " as a part of vm id=" + vmId + " expunge"); + success = false; + } + } + } catch (ResourceUnavailableException e) { + success = false; + s_logger.warn("Failed to disable static nat for ip address " + ip + + " as a part of vm id=" + vmId + + " expunge because resource is unavailable", e); + } + + return success; + } + + @Override + public void deletePrivateTemplateRecord(Long templateId) { + if (templateId != null) { + _templateDao.remove(templateId); + } + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true) + public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd, + Account templateOwner) throws ResourceAllocationException { + Long userId = UserContext.current().getCallerUserId(); + + Account caller = UserContext.current().getCaller(); + boolean isAdmin = (isAdmin(caller.getType())); + + _accountMgr.checkAccess(caller, null, true, templateOwner); + + 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"); + } + + if (cmd.getTemplateTag() != null) { + if (!_accountService.isRootAdmin(caller.getType())) { + throw new PermissionDeniedException( + "Parameter templatetag can only be specified by a Root Admin, permission denied"); + } + } + + // do some parameter defaulting + Integer bits = cmd.getBits(); + Boolean requiresHvm = cmd.getRequiresHvm(); + Boolean passwordEnabled = cmd.isPasswordEnabled(); + Boolean isPublic = cmd.isPublic(); + Boolean featured = cmd.isFeatured(); + int bitsValue = ((bits == null) ? 64 : bits.intValue()); + boolean requiresHvmValue = ((requiresHvm == null) ? true : requiresHvm + .booleanValue()); + boolean passwordEnabledValue = ((passwordEnabled == null) ? false + : passwordEnabled.booleanValue()); + if (isPublic == null) { + isPublic = Boolean.FALSE; + } + 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)) { + throw new InvalidParameterValueException( + "Failed to create private template record, neither volume ID nor snapshot ID were specified."); + } + 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 + + ")"); + } + + HypervisorType hyperType; + VolumeVO volume = null; + VMTemplateVO privateTemplate = 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); + } + // check permissions + _accountMgr.checkAccess(caller, null, true, volume); + + // 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"; + if (s_logger.isInfoEnabled()) { + s_logger.info(msg); + } + throw new CloudRuntimeException(msg); + } + 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); + } + + volume = _volsDao.findById(snapshot.getVolumeId()); + VolumeVO snapshotVolume = _volsDao + .findByIdIncludingRemoved(snapshot.getVolumeId()); + + // check permissions + _accountMgr.checkAccess(caller, null, true, snapshot); + + if (snapshot.getStatus() != Snapshot.Status.BackedUp) { + throw new InvalidParameterValueException("Snapshot id=" + + snapshotId + " is not in " + Snapshot.Status.BackedUp + + " state yet and can't be used for template creation"); + } + + /* + * // bug #11428. Operation not supported if vmware and snapshots + * parent volume = ROOT if(snapshot.getHypervisorType() == + * HypervisorType.VMware && snapshotVolume.getVolumeType() == + * Type.DATADISK){ throw new UnsupportedServiceException( + * "operation not supported, snapshot with id " + snapshotId + + * " is created from Data Disk"); } + */ + + hyperType = snapshot.getHypervisorType(); + } + + _resourceLimitMgr.checkResourceLimit(templateOwner, + ResourceType.template); + + 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; + Long sourceTemplateId = null; + if (volume != null) { + VMTemplateVO template = ApiDBUtils.findTemplateById(volume + .getTemplateId()); + isExtractable = template != null + && template.isExtractable() + && template.getTemplateType() != Storage.TemplateType.SYSTEM; + if (template != null) { + sourceTemplateId = template.getId(); + } else if (volume.getVolumeType() == Type.ROOT) { // vm created out + // of blank + // template + UserVm userVm = ApiDBUtils.findUserVmById(volume + .getInstanceId()); + sourceTemplateId = userVm.getIsoId(); + } + } + String templateTag = cmd.getTemplateTag(); + if (templateTag != null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Adding template tag: " + templateTag); + } + } + privateTemplate = new VMTemplateVO(nextTemplateId, uniqueName, name, + ImageFormat.RAW, isPublic, featured, isExtractable, + TemplateType.USER, null, null, requiresHvmValue, bitsValue, + templateOwner.getId(), null, description, passwordEnabledValue, + guestOS.getId(), true, hyperType, templateTag, cmd.getDetails()); + if (sourceTemplateId != null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("This template is getting created from other template, setting source template Id to: " + + sourceTemplateId); + } + } + privateTemplate.setSourceTemplateId(sourceTemplateId); + + VMTemplateVO template = _templateDao.persist(privateTemplate); + // Increment the number of templates + if (template != null) { + if (cmd.getDetails() != null) { + _templateDetailsDao.persist(template.getId(), cmd.getDetails()); + } + + _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), + ResourceType.template); + } + + if (template != null) { + return template; + } else { + throw new CloudRuntimeException("Failed to create a template"); + } + + } + + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true) + public VMTemplateVO createPrivateTemplate(CreateTemplateCmd command) + throws CloudRuntimeException { + Long userId = UserContext.current().getCallerUserId(); + if (userId == null) { + userId = User.UID_SYSTEM; + } + long templateId = command.getEntityId(); + Long volumeId = command.getVolumeId(); + Long snapshotId = command.getSnapshotId(); + SnapshotCommand cmd = null; + VMTemplateVO privateTemplate = null; + + String uniqueName = getRandomPrivateTemplateName(); + + StoragePoolVO pool = null; + HostVO secondaryStorageHost = null; + Long zoneId = null; + Long accountId = null; + SnapshotVO snapshot = null; + String secondaryStorageURL = null; + try { + if (snapshotId != null) { // create template from snapshot + snapshot = _snapshotDao.findById(snapshotId); + if (snapshot == null) { + throw new CloudRuntimeException( + "Unable to find Snapshot for Id " + snapshotId); + } + zoneId = snapshot.getDataCenterId(); + secondaryStorageHost = _snapshotMgr + .getSecondaryStorageHost(snapshot); + secondaryStorageURL = _snapshotMgr + .getSecondaryStorageURL(snapshot); + String name = command.getTemplateName(); + String backupSnapshotUUID = snapshot.getBackupSnapshotId(); + 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 pools = _storageMgr + .ListByDataCenterHypervisor(zoneId, + snapshot.getHypervisorType()); + if (pools == null || pools.size() == 0) { + throw new CloudRuntimeException( + "Unable to find storage pools in zone " + zoneId); + } + pool = pools.get(0); + if (snapshot.getVersion() != null + && snapshot.getVersion().equalsIgnoreCase("2.1")) { + VolumeVO volume = _volsDao + .findByIdIncludingRemoved(volumeId); + if (volume == null) { + throw new CloudRuntimeException( + "failed to upgrade snapshot " + + snapshotId + + " due to unable to find orignal volume:" + + volumeId + ", try it later "); + } + if (volume.getTemplateId() == null) { + _snapshotDao.updateSnapshotVersion(volumeId, "2.1", + "2.2"); + } else { + VMTemplateVO template = _templateDao + .findByIdIncludingRemoved(volume + .getTemplateId()); + 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)) { + 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)) { + throw new CloudRuntimeException( + "Creating template failed due to volume:" + + volumeId + + " is being used, try it later "); + } + Answer answer = null; + try { + answer = _storageMgr.sendToPool(pool, cmd); + cmd = null; + } catch (StorageUnavailableException e) { + } finally { + _volsDao.unlockFromLockTable(volumeId.toString()); + } + if ((answer != null) && answer.getResult()) { + _snapshotDao.updateSnapshotVersion(volumeId, "2.1", + "2.2"); + } else { + throw new CloudRuntimeException( + "Unable to upgrade snapshot"); + } + } + } + if (snapshot.getSwiftId() != null && snapshot.getSwiftId() != 0) { + _snapshotMgr.downloadSnapshotsFromSwift(snapshot); + } cmd = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStorageURL, dcId, accountId, snapshot.getVolumeId(), backupSnapshotUUID, snapshot.getName(), origTemplateInstallPath, templateId, name, _createprivatetemplatefromsnapshotwait); - } else if (volumeId != null) { - VolumeVO volume = _volsDao.findById(volumeId); - if (volume == null) { - throw new CloudRuntimeException( - "Unable to find volume for Id " + volumeId); - } - accountId = volume.getAccountId(); + } else if (volumeId != null) { + VolumeVO volume = _volsDao.findById(volumeId); + if (volume == null) { + throw new CloudRuntimeException( + "Unable to find volume for Id " + volumeId); + } + accountId = volume.getAccountId(); - 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(); - secondaryStorageHost = _storageMgr - .getSecondaryStorageHost(zoneId); - if (secondaryStorageHost == null) { - throw new CloudRuntimeException( - "Can not find the secondary storage for zoneId " - + zoneId); - } - secondaryStorageURL = secondaryStorageHost.getStorageUrl(); + 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(); + secondaryStorageHost = _storageMgr + .getSecondaryStorageHost(zoneId); + if (secondaryStorageHost == null) { + throw new CloudRuntimeException( + "Can not find the secondary storage for zoneId " + + zoneId); + } + secondaryStorageURL = secondaryStorageHost.getStorageUrl(); - pool = _storagePoolDao.findById(volume.getPoolId()); + pool = _storagePoolDao.findById(volume.getPoolId()); cmd = new CreatePrivateTemplateFromVolumeCommand(pool, secondaryStorageURL, templateId, accountId, command.getTemplateName(), uniqueName, volume.getPath(), vmName, _createprivatetemplatefromvolumewait); - } else { - throw new CloudRuntimeException( - "Creating private Template need to specify snapshotId or volumeId"); - } - // FIXME: before sending the command, check if there's enough - // capacity - // on the storage server to create the template + } else { + throw new CloudRuntimeException( + "Creating private Template need to specify snapshotId or volumeId"); + } + // FIXME: before sending the command, check if there's enough + // capacity + // on the storage server to create the template - // This can be sent to a KVM host too. - CreatePrivateTemplateAnswer answer = null; - if (snapshotId != null) { - if (!_snapshotDao.lockInLockTable(snapshotId.toString(), 10)) { - throw new CloudRuntimeException( - "Creating template from snapshot failed due to snapshot:" - + snapshotId - + " is being used, try it later "); - } - } else { - if (!_volsDao.lockInLockTable(volumeId.toString(), 10)) { - throw new CloudRuntimeException( - "Creating template from volume failed due to volume:" - + volumeId - + " is being used, try it later "); - } - } - try { - answer = (CreatePrivateTemplateAnswer) _storageMgr.sendToPool( - pool, cmd); - } catch (StorageUnavailableException e) { - } finally { - if (snapshotId != null) { - _snapshotDao.unlockFromLockTable(snapshotId.toString()); - } else { - _volsDao.unlockFromLockTable(volumeId.toString()); - } - } - if ((answer != null) && answer.getResult()) { - privateTemplate = _templateDao.findById(templateId); - String answerUniqueName = answer.getUniqueName(); - if (answerUniqueName != null) { - privateTemplate.setUniqueName(answerUniqueName); - } else { - privateTemplate.setUniqueName(uniqueName); - } - ImageFormat format = answer.getImageFormat(); - if (format != null) { - privateTemplate.setFormat(format); - } else { - // This never occurs. - // Specify RAW format makes it unusable for snapshots. - privateTemplate.setFormat(ImageFormat.RAW); - } + // This can be sent to a KVM host too. + CreatePrivateTemplateAnswer answer = null; + if (snapshotId != null) { + if (!_snapshotDao.lockInLockTable(snapshotId.toString(), 10)) { + throw new CloudRuntimeException( + "Creating template from snapshot failed due to snapshot:" + + snapshotId + + " is being used, try it later "); + } + } else { + if (!_volsDao.lockInLockTable(volumeId.toString(), 10)) { + throw new CloudRuntimeException( + "Creating template from volume failed due to volume:" + + volumeId + + " is being used, try it later "); + } + } + try { + answer = (CreatePrivateTemplateAnswer) _storageMgr.sendToPool( + pool, cmd); + } catch (StorageUnavailableException e) { + } finally { + if (snapshotId != null) { + _snapshotDao.unlockFromLockTable(snapshotId.toString()); + } else { + _volsDao.unlockFromLockTable(volumeId.toString()); + } + } + if ((answer != null) && answer.getResult()) { + privateTemplate = _templateDao.findById(templateId); + String answerUniqueName = answer.getUniqueName(); + if (answerUniqueName != null) { + privateTemplate.setUniqueName(answerUniqueName); + } else { + privateTemplate.setUniqueName(uniqueName); + } + ImageFormat format = answer.getImageFormat(); + if (format != null) { + privateTemplate.setFormat(format); + } else { + // This never occurs. + // Specify RAW format makes it unusable for snapshots. + privateTemplate.setFormat(ImageFormat.RAW); + } - String checkSum = getChecksum(secondaryStorageHost.getId(), - answer.getPath()); + String checkSum = getChecksum(secondaryStorageHost.getId(), + answer.getPath()); - Transaction txn = Transaction.currentTxn(); + Transaction txn = Transaction.currentTxn(); - txn.start(); + txn.start(); - privateTemplate.setChecksum(checkSum); - _templateDao.update(templateId, privateTemplate); + privateTemplate.setChecksum(checkSum); + _templateDao.update(templateId, privateTemplate); - // add template zone ref for this template - _templateDao.addTemplateToZone(privateTemplate, zoneId); - VMTemplateHostVO templateHostVO = new VMTemplateHostVO( - secondaryStorageHost.getId(), templateId); - templateHostVO.setDownloadPercent(100); - templateHostVO.setDownloadState(Status.DOWNLOADED); - templateHostVO.setInstallPath(answer.getPath()); - templateHostVO.setLastUpdated(new Date()); - templateHostVO.setSize(answer.getVirtualSize()); - templateHostVO.setPhysicalSize(answer.getphysicalSize()); - _templateHostDao.persist(templateHostVO); + // add template zone ref for this template + _templateDao.addTemplateToZone(privateTemplate, zoneId); + VMTemplateHostVO templateHostVO = new VMTemplateHostVO( + secondaryStorageHost.getId(), templateId); + templateHostVO.setDownloadPercent(100); + templateHostVO.setDownloadState(Status.DOWNLOADED); + templateHostVO.setInstallPath(answer.getPath()); + templateHostVO.setLastUpdated(new Date()); + templateHostVO.setSize(answer.getVirtualSize()); + templateHostVO.setPhysicalSize(answer.getphysicalSize()); + _templateHostDao.persist(templateHostVO); - UsageEventVO usageEvent = new UsageEventVO( - EventTypes.EVENT_TEMPLATE_CREATE, - privateTemplate.getAccountId(), - secondaryStorageHost.getDataCenterId(), - privateTemplate.getId(), privateTemplate.getName(), - null, privateTemplate.getSourceTemplateId(), - templateHostVO.getSize()); - _usageEventDao.persist(usageEvent); - txn.commit(); - } - } finally { - if (snapshot != null && snapshot.getSwiftId() != null - && secondaryStorageURL != null && zoneId != null - && accountId != null && volumeId != null) { - _snapshotMgr.deleteSnapshotsForVolume(secondaryStorageURL, - zoneId, accountId, volumeId); - } - if (privateTemplate == null) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - // Remove the template record - _templateDao.expunge(templateId); + UsageEventVO usageEvent = new UsageEventVO( + EventTypes.EVENT_TEMPLATE_CREATE, + privateTemplate.getAccountId(), + secondaryStorageHost.getDataCenterId(), + privateTemplate.getId(), privateTemplate.getName(), + null, privateTemplate.getSourceTemplateId(), + templateHostVO.getSize()); + _usageEventDao.persist(usageEvent); + txn.commit(); + } + } finally { + if (snapshot != null && snapshot.getSwiftId() != null + && secondaryStorageURL != null && zoneId != null + && accountId != null && volumeId != null) { + _snapshotMgr.deleteSnapshotsForVolume(secondaryStorageURL, + zoneId, accountId, volumeId); + } + if (privateTemplate == null) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + // Remove the template record + _templateDao.expunge(templateId); - // decrement resource count - if (accountId != null) { - _resourceLimitMgr.decrementResourceCount(accountId, - ResourceType.template); - } - txn.commit(); - } - } + // decrement resource count + if (accountId != null) { + _resourceLimitMgr.decrementResourceCount(accountId, + ResourceType.template); + } + txn.commit(); + } + } - if (privateTemplate != null) { - return privateTemplate; - } else { - throw new CloudRuntimeException("Failed to create a template"); - } - } + if (privateTemplate != null) { + return privateTemplate; + } else { + throw new CloudRuntimeException("Failed to create a template"); + } + } - @Override - public String getChecksum(Long hostId, String templatePath) { - HostVO ssHost = _hostDao.findById(hostId); - Host.Type type = ssHost.getType(); - if (type != Host.Type.SecondaryStorage - && type != Host.Type.LocalSecondaryStorage) { - return null; - } - String secUrl = ssHost.getStorageUrl(); - Answer answer; - answer = _agentMgr.sendToSecStorage(ssHost, new ComputeChecksumCommand( - secUrl, templatePath)); - if (answer != null && answer.getResult()) { - return answer.getDetails(); - } - return null; - } + @Override + public String getChecksum(Long hostId, String templatePath) { + HostVO ssHost = _hostDao.findById(hostId); + Host.Type type = ssHost.getType(); + if (type != Host.Type.SecondaryStorage + && type != Host.Type.LocalSecondaryStorage) { + return null; + } + String secUrl = ssHost.getStorageUrl(); + Answer answer; + answer = _agentMgr.sendToSecStorage(ssHost, new ComputeChecksumCommand( + secUrl, templatePath)); + if (answer != null && answer.getResult()) { + return answer.getDetails(); + } + return null; + } - // used for vm transitioning to error state - private void updateVmStateForFailedVmCreation(Long vmId) { + // used for vm transitioning to error state + private void updateVmStateForFailedVmCreation(Long vmId) { - UserVmVO vm = _vmDao.findById(vmId); + UserVmVO vm = _vmDao.findById(vmId); - if (vm != null) { - if (vm.getState().equals(State.Stopped)) { - s_logger.debug("Destroying vm " + vm - + " as it failed to create"); - try { - _itMgr.stateTransitTo(vm, - VirtualMachine.Event.OperationFailedToError, null); - } catch (NoTransitionException e1) { - s_logger.warn(e1.getMessage()); - } - // destroy associated volumes for vm in error state - // get all volumes in non destroyed state - List volumesForThisVm = _volsDao - .findUsableVolumesForInstance(vm.getId()); - for (VolumeVO volume : volumesForThisVm) { - try { - if (volume.getState() != Volume.State.Destroy) { - _storageMgr.destroyVolume(volume); - } - } catch (ConcurrentOperationException e) { - s_logger.warn("Unable to delete volume:" - + volume.getId() + " for vm:" + vmId - + " whilst transitioning to error state"); - } - } - String msg = "Failed to deploy Vm with Id: " + vmId; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_USERVM, - vm.getDataCenterIdToDeployIn(), - vm.getPodIdToDeployIn(), msg, msg); + if (vm != null) { + if (vm.getState().equals(State.Stopped)) { + s_logger.debug("Destroying vm " + vm + + " as it failed to create"); + try { + _itMgr.stateTransitTo(vm, + VirtualMachine.Event.OperationFailedToError, null); + } catch (NoTransitionException e1) { + s_logger.warn(e1.getMessage()); + } + // destroy associated volumes for vm in error state + // get all volumes in non destroyed state + List volumesForThisVm = _volsDao + .findUsableVolumesForInstance(vm.getId()); + for (VolumeVO volume : volumesForThisVm) { + try { + if (volume.getState() != Volume.State.Destroy) { + _storageMgr.destroyVolume(volume); + } + } catch (ConcurrentOperationException e) { + s_logger.warn("Unable to delete volume:" + + volume.getId() + " for vm:" + vmId + + " whilst transitioning to error state"); + } + } + String msg = "Failed to deploy Vm with Id: " + vmId; + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_USERVM, + vm.getDataCenterIdToDeployIn(), + vm.getPodIdToDeployIn(), msg, msg); - _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), - ResourceType.user_vm); - } - } - } + _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), + ResourceType.user_vm); + } + } + } - protected class ExpungeTask implements Runnable { - public ExpungeTask() { - } + 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(); - } - } - } + @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)); - } + 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") + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_UPDATE, eventDescription = "updating Vm") public UserVm updateVirtualMachine(UpdateVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException { - String displayName = cmd.getDisplayName(); - String group = cmd.getGroup(); - Boolean ha = cmd.getHaEnable(); - Long id = cmd.getId(); - Long osTypeId = cmd.getOsTypeId(); - String userData = cmd.getUserData(); + String displayName = cmd.getDisplayName(); + String group = cmd.getGroup(); + Boolean ha = cmd.getHaEnable(); + Long id = cmd.getId(); + Long osTypeId = cmd.getOsTypeId(); + String userData = cmd.getUserData(); - // Input validation - UserVmVO vmInstance = null; + // Input validation + UserVmVO vmInstance = null; - // Verify input parameters - vmInstance = _vmDao.findById(id.longValue()); + // Verify input parameters + vmInstance = _vmDao.findById(id.longValue()); - if (vmInstance == null) { - throw new InvalidParameterValueException( - "unable to find virtual machine with id " + id); - } + if (vmInstance == null) { + throw new InvalidParameterValueException( + "unable to find virtual machine with id " + id); + } - ServiceOffering offering = _serviceOfferingDao.findById(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"); - } + ServiceOffering offering = _serviceOfferingDao.findById(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"); + } - _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, - vmInstance); + _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, + vmInstance); - if (displayName == null) { - displayName = vmInstance.getDisplayName(); - } + 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); - } + 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 (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"); + } boolean updateUserdata = false; - if (userData != null) { + if (userData != null) { // check and replace newlines userData = userData.replace("\\n", ""); - validateUserData(userData); - // update userData on domain router. + validateUserData(userData); + // update userData on domain router. updateUserdata = true; - } else { - userData = vmInstance.getUserData(); - } + } else { + userData = vmInstance.getUserData(); + } - String description = ""; + 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) { - description += "Enabled HA. "; - } else { - description += "Disabled HA. "; - } - } - if (osTypeId == null) { - osTypeId = vmInstance.getGuestOSId(); - } else { - description += "Changed Guest OS Type to " + osTypeId + ". "; - } + if (ha != vmInstance.isHaEnabled()) { + if (ha) { + description += "Enabled HA. "; + } else { + description += "Disabled HA. "; + } + } + if (osTypeId == null) { + osTypeId = vmInstance.getGuestOSId(); + } else { + description += "Changed Guest OS Type to " + osTypeId + ". "; + } - if (group != null) { - if (addInstanceToGroup(id, group)) { - description += "Added to group: " + group + "."; - } - } + if (group != null) { + if (addInstanceToGroup(id, group)) { + description += "Added to group: " + group + "."; + } + } - _vmDao.updateVM(id, displayName, ha, osTypeId, userData); + _vmDao.updateVM(id, displayName, ha, osTypeId, userData); if (updateUserdata) { boolean result = updateUserDataInternal(_vmDao.findById(id)); @@ -2129,8 +2200,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } - return _vmDao.findById(id); - } + return _vmDao.findById(id); + } private boolean updateUserDataInternal(UserVm vm) throws ResourceUnavailableException, InsufficientCapacityException { @@ -2157,395 +2228,395 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return true; } - @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(), cmd.getHostId(), null).first(); - } + @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(), cmd.getHostId(), null).first(); + } - @Override - @ActionEvent(eventType = EventTypes.EVENT_VM_REBOOT, eventDescription = "rebooting Vm", async = true) - public UserVm rebootVirtualMachine(RebootVMCmd cmd) - throws InsufficientCapacityException, ResourceUnavailableException { - Account caller = UserContext.current().getCaller(); - Long vmId = cmd.getId(); + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_REBOOT, eventDescription = "rebooting Vm", async = true) + public UserVm rebootVirtualMachine(RebootVMCmd cmd) + throws InsufficientCapacityException, ResourceUnavailableException { + Account caller = UserContext.current().getCaller(); + Long vmId = cmd.getId(); - // Verify input parameters - UserVmVO vmInstance = _vmDao.findById(vmId.longValue()); - if (vmInstance == null) { - throw new InvalidParameterValueException( - "unable to find a virtual machine with id " + vmId); - } + // Verify input parameters + UserVmVO vmInstance = _vmDao.findById(vmId.longValue()); + if (vmInstance == null) { + throw new InvalidParameterValueException( + "unable to find a virtual machine with id " + vmId); + } - _accountMgr.checkAccess(caller, null, true, vmInstance); + _accountMgr.checkAccess(caller, null, true, vmInstance); - return rebootVirtualMachine(UserContext.current().getCallerUserId(), - vmId); - } + return rebootVirtualMachine(UserContext.current().getCallerUserId(), + 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) { - Account caller = UserContext.current().getCaller(); - Long domainId = cmd.getDomainId(); - String accountName = cmd.getAccountName(); - String groupName = cmd.getGroupName(); - Long projectId = cmd.getProjectId(); + @Override + @DB + public InstanceGroupVO createVmGroup(CreateVMGroupCmd cmd) { + Account caller = UserContext.current().getCaller(); + Long domainId = cmd.getDomainId(); + String accountName = cmd.getAccountName(); + String groupName = cmd.getGroupName(); + Long projectId = cmd.getProjectId(); - Account owner = _accountMgr.finalizeOwner(caller, accountName, - domainId, projectId); - long accountId = owner.getId(); + Account owner = _accountMgr.finalizeOwner(caller, accountName, + domainId, projectId); + long accountId = owner.getId(); - // Check if name is already in use by this account - boolean isNameInUse = _vmGroupDao.isNameInUse(accountId, groupName); + // Check if name is already in use by this account + boolean isNameInUse = _vmGroupDao.isNameInUse(accountId, groupName); - if (isNameInUse) { - throw new InvalidParameterValueException( - "Unable to create vm group, a group with name " + groupName - + " already exisits for account " + accountId); - } + if (isNameInUse) { + throw new InvalidParameterValueException( + "Unable to create vm group, a group with name " + groupName + + " already exisits for account " + accountId); + } - return createVmGroup(groupName, accountId); - } + return createVmGroup(groupName, accountId); + } - @DB - protected 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(); - } - } + @DB + protected 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(); + } + } - @Override - public boolean deleteVmGroup(DeleteVMGroupCmd cmd) { - Account caller = UserContext.current().getCaller(); - Long groupId = cmd.getId(); + @Override + public boolean deleteVmGroup(DeleteVMGroupCmd cmd) { + Account caller = UserContext.current().getCaller(); + Long groupId = cmd.getId(); - // Verify input parameters - InstanceGroupVO group = _vmGroupDao.findById(groupId); - if ((group == null) || (group.getRemoved() != null)) { - throw new InvalidParameterValueException( - "unable to find a vm group with id " + groupId); - } + // Verify input parameters + InstanceGroupVO group = _vmGroupDao.findById(groupId); + if ((group == null) || (group.getRemoved() != null)) { + throw new InvalidParameterValueException( + "unable to find a vm group with id " + groupId); + } - _accountMgr.checkAccess(caller, null, true, group); + _accountMgr.checkAccess(caller, null, true, group); - return deleteVmGroup(groupId); - } + return deleteVmGroup(groupId); + } - @Override - 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); - } + @Override + 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); + } - 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 - if (group == null) { - group = createVmGroup(groupName, vm.getAccountId()); - } + InstanceGroupVO group = _vmGroupDao.findByAccountAndName( + vm.getAccountId(), groupName); + // Create vm group if the group doesn't exist for this account + if (group == null) { + 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; - } + 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); + // 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; - } + 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); + @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; - } - } + 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); - } - } + @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; - } - for (int i = 0; i < password.length(); i++) { - if (password.charAt(i) == ' ') { - return false; - } - } - return true; - } + protected boolean validPassword(String password) { + if (password == null || password.length() == 0) { + return false; + } + for (int i = 0; i < password.length(); i++) { + if (password.charAt(i) == ' ') { + return false; + } + } + 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, Map requestedIps, - String defaultIp, String keyboard) - throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException, StorageUnavailableException, - ResourceAllocationException { + @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, Map requestedIps, + String defaultIp, String keyboard) + throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException, StorageUnavailableException, + ResourceAllocationException { - Account caller = UserContext.current().getCaller(); - List networkList = new ArrayList(); + Account caller = UserContext.current().getCaller(); + List networkList = new ArrayList(); - // Verify that caller can perform actions in behalf of vm owner - _accountMgr.checkAccess(caller, null, true, owner); + // Verify that caller can perform actions in behalf of vm owner + _accountMgr.checkAccess(caller, null, true, owner); - // Get default guest network in Basic zone - Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone - .getId()); + // Get default guest network in Basic zone + Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone + .getId()); - if (defaultNetwork == null) { - throw new InvalidParameterValueException( - "Unable to find a default network to start a vm"); - } else { - networkList.add(_networkDao.findById(defaultNetwork.getId())); - } + if (defaultNetwork == null) { + throw new InvalidParameterValueException( + "Unable to find a default network to start a vm"); + } else { + networkList.add(_networkDao.findById(defaultNetwork.getId())); + } - boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); + boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); - if (securityGroupIdList != null && isVmWare) { - throw new InvalidParameterValueException( - "Security group feature is not supported for vmWare hypervisor"); - } else if (!isVmWare - && _networkMgr - .isSecurityGroupSupportedInNetwork(defaultNetwork) - && _networkMgr.canAddDefaultSecurityGroup()) { - // add the default securityGroup only if no security group is - // specified - if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { - if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList(); - } - SecurityGroup defaultGroup = _securityGroupMgr - .getDefaultSecurityGroup(owner.getId()); - if (defaultGroup != null) { - securityGroupIdList.add(defaultGroup.getId()); - } else { - // create default security group for the account - if (s_logger.isDebugEnabled()) { - s_logger.debug("Couldn't find default security group for the account " - + owner + " so creating a new one"); - } - defaultGroup = _securityGroupMgr.createSecurityGroup( - SecurityGroupManager.DEFAULT_GROUP_NAME, - SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, - owner.getDomainId(), owner.getId(), - owner.getAccountName()); - securityGroupIdList.add(defaultGroup.getId()); - } - } - } + if (securityGroupIdList != null && isVmWare) { + throw new InvalidParameterValueException( + "Security group feature is not supported for vmWare hypervisor"); + } else if (!isVmWare + && _networkMgr + .isSecurityGroupSupportedInNetwork(defaultNetwork) + && _networkMgr.canAddDefaultSecurityGroup()) { + // add the default securityGroup only if no security group is + // specified + if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { + if (securityGroupIdList == null) { + securityGroupIdList = new ArrayList(); + } + SecurityGroup defaultGroup = _securityGroupMgr + .getDefaultSecurityGroup(owner.getId()); + if (defaultGroup != null) { + securityGroupIdList.add(defaultGroup.getId()); + } else { + // create default security group for the account + if (s_logger.isDebugEnabled()) { + s_logger.debug("Couldn't find default security group for the account " + + owner + " so creating a new one"); + } + defaultGroup = _securityGroupMgr.createSecurityGroup( + SecurityGroupManager.DEFAULT_GROUP_NAME, + SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, + owner.getDomainId(), owner.getId(), + owner.getAccountName()); + securityGroupIdList.add(defaultGroup.getId()); + } + } + } - return createVirtualMachine(zone, serviceOffering, template, hostName, - displayName, owner, diskOfferingId, diskSize, networkList, - securityGroupIdList, group, userData, sshKeyPair, hypervisor, - caller, requestedIps, defaultIp, keyboard); - } + return createVirtualMachine(zone, serviceOffering, template, hostName, + displayName, owner, diskOfferingId, diskSize, networkList, + securityGroupIdList, group, userData, sshKeyPair, hypervisor, + caller, requestedIps, defaultIp, keyboard); + } - @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, - Map requestedIps, String defaultIp, String keyboard) - throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException, StorageUnavailableException, - ResourceAllocationException { + @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, + Map requestedIps, String defaultIp, String keyboard) + throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException, StorageUnavailableException, + ResourceAllocationException { - Account caller = UserContext.current().getCaller(); - List networkList = new ArrayList(); - boolean isSecurityGroupEnabledNetworkUsed = false; - boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); + Account caller = UserContext.current().getCaller(); + List networkList = new ArrayList(); + boolean isSecurityGroupEnabledNetworkUsed = false; + boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); - // Verify that caller can perform actions in behalf of vm owner - _accountMgr.checkAccess(caller, null, true, owner); + // Verify that caller can perform actions in behalf of vm owner + _accountMgr.checkAccess(caller, null, true, owner); - // 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()); - } + // 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); - isSecurityGroupEnabledNetworkUsed = true; + networkList.add(networkWithSecurityGroup); + isSecurityGroupEnabledNetworkUsed = true; - } else if (securityGroupIdList != null - && !securityGroupIdList.isEmpty()) { - if (isVmWare) { - throw new InvalidParameterValueException( - "Security group feature is not supported for vmWare hypervisor"); - } - // 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"); - } + } else if (securityGroupIdList != null + && !securityGroupIdList.isEmpty()) { + if (isVmWare) { + throw new InvalidParameterValueException( + "Security group feature is not supported for vmWare hypervisor"); + } + // 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()); + 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 == null) { + throw new InvalidParameterValueException( + "Unable to find network by id " + + networkIdList.get(0).longValue()); + } - if (!_networkMgr.isSecurityGroupSupportedInNetwork(network)) { - throw new InvalidParameterValueException( - "Network is not security group enabled: " - + network.getId()); - } + if (!_networkMgr.isSecurityGroupSupportedInNetwork(network)) { + throw new InvalidParameterValueException( + "Network is not security group enabled: " + + network.getId()); + } - networkList.add(network); - isSecurityGroupEnabledNetworkUsed = true; + networkList.add(network); + isSecurityGroupEnabledNetworkUsed = true; - } else { + } else { // Verify that all the networks are Shared/Guest; can't create combination of SG enabled and disabled networks - for (Long networkId : networkIdList) { - NetworkVO network = _networkDao.findById(networkId); + 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 == null) { + throw new InvalidParameterValueException( + "Unable to find network by id " + + networkIdList.get(0).longValue()); + } boolean isSecurityGroupEnabled = _networkMgr.isSecurityGroupSupportedInNetwork(network); if (isSecurityGroupEnabled) { if (networkIdList.size() > 1) { throw new InvalidParameterValueException("Can't create a vm with multiple networks one of" + - " which is Security Group enabled"); + " which is Security Group enabled"); } isSecurityGroupEnabledNetworkUsed = true; @@ -2553,1029 +2624,1029 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (!(network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Shared)) { throw new InvalidParameterValueException("Can specify only Shared Guest networks when" + - " deploy vm in Advance Security Group enabled zone"); - } + " deploy vm in Advance Security Group enabled zone"); + } // Perform account permission check if (network.getAclType() == ACLType.Account) { _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); } - networkList.add(network); - } - } + networkList.add(network); + } + } - // if network is security group enabled, and no security group is - // specified, then add the default security group automatically - if (isSecurityGroupEnabledNetworkUsed && !isVmWare - && _networkMgr.canAddDefaultSecurityGroup()) { + // if network is security group enabled, and no security group is + // specified, then add the default security group automatically + if (isSecurityGroupEnabledNetworkUsed && !isVmWare + && _networkMgr.canAddDefaultSecurityGroup()) { - // add the default securityGroup only if no security group is - // specified - if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { - if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList(); - } + // add the default securityGroup only if no security group is + // specified + if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { + if (securityGroupIdList == null) { + securityGroupIdList = new ArrayList(); + } - SecurityGroup defaultGroup = _securityGroupMgr - .getDefaultSecurityGroup(owner.getId()); - if (defaultGroup != null) { - securityGroupIdList.add(defaultGroup.getId()); - } else { - // create default security group for the account - if (s_logger.isDebugEnabled()) { - s_logger.debug("Couldn't find default security group for the account " - + owner + " so creating a new one"); - } - defaultGroup = _securityGroupMgr.createSecurityGroup( - SecurityGroupManager.DEFAULT_GROUP_NAME, - SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, - owner.getDomainId(), owner.getId(), - owner.getAccountName()); - securityGroupIdList.add(defaultGroup.getId()); - } - } - } + SecurityGroup defaultGroup = _securityGroupMgr + .getDefaultSecurityGroup(owner.getId()); + if (defaultGroup != null) { + securityGroupIdList.add(defaultGroup.getId()); + } else { + // create default security group for the account + if (s_logger.isDebugEnabled()) { + s_logger.debug("Couldn't find default security group for the account " + + owner + " so creating a new one"); + } + defaultGroup = _securityGroupMgr.createSecurityGroup( + SecurityGroupManager.DEFAULT_GROUP_NAME, + SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, + owner.getDomainId(), owner.getId(), + owner.getAccountName()); + securityGroupIdList.add(defaultGroup.getId()); + } + } + } - return createVirtualMachine(zone, serviceOffering, template, hostName, - displayName, owner, diskOfferingId, diskSize, networkList, - securityGroupIdList, group, userData, sshKeyPair, hypervisor, - caller, requestedIps, defaultIp, keyboard); - } + return createVirtualMachine(zone, serviceOffering, template, hostName, + displayName, owner, diskOfferingId, diskSize, networkList, + securityGroupIdList, group, userData, sshKeyPair, hypervisor, + caller, requestedIps, defaultIp, keyboard); + } - @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, Map requestedIps, - String defaultIp, String keyboard) - throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException, StorageUnavailableException, - ResourceAllocationException { + @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, Map requestedIps, + String defaultIp, String keyboard) + throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException, StorageUnavailableException, + ResourceAllocationException { - Account caller = UserContext.current().getCaller(); - List networkList = new ArrayList(); + Account caller = UserContext.current().getCaller(); + List networkList = new ArrayList(); - // Verify that caller can perform actions in behalf of vm owner - _accountMgr.checkAccess(caller, null, true, owner); + // Verify that caller can perform actions in behalf of vm owner + _accountMgr.checkAccess(caller, null, true, owner); - List vpcSupportedHTypes = _vpcMgr - .getSupportedVpcHypervisors(); - if (networkIdList == null || networkIdList.isEmpty()) { - NetworkVO defaultNetwork = null; + List vpcSupportedHTypes = _vpcMgr + .getSupportedVpcHypervisors(); + if (networkIdList == null || networkIdList.isEmpty()) { + NetworkVO defaultNetwork = null; - // if no network is passed in - // 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 + // if no network is passed in + // 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 - List requiredOfferings = _networkOfferingDao - .listByAvailability(Availability.Required, false); - if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException( - "Unable to find network offering with availability=" - + Availability.Required - + " to automatically create the network as a part of vm creation"); - } + List requiredOfferings = _networkOfferingDao + .listByAvailability(Availability.Required, false); + if (requiredOfferings.size() < 1) { + throw new InvalidParameterValueException( + "Unable to find network offering with availability=" + + Availability.Required + + " to automatically create the network as a part of vm creation"); + } - if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { - // get Virtual networks + if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { + // get Virtual networks List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.GuestType.Isolated); - if (virtualNetworks.isEmpty()) { - long physicalNetworkId = _networkMgr.findPhysicalNetworkId( - zone.getId(), requiredOfferings.get(0).getTags(), - requiredOfferings.get(0).getTrafficType()); - // Validate physical network - PhysicalNetwork physicalNetwork = _physicalNetworkDao - .findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException( - "Unable to find physical network with id: " - + physicalNetworkId + " and tag: " - + requiredOfferings.get(0).getTags()); - } - s_logger.debug("Creating network for account " + owner - + " from the network offering id=" - + requiredOfferings.get(0).getId() - + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createGuestNetwork( - requiredOfferings.get(0).getId(), - owner.getAccountName() + "-network", - owner.getAccountName() + "-network", null, null, - null, null, owner, null, physicalNetwork, - zone.getId(), ACLType.Account, null, null); - defaultNetwork = _networkDao.findById(newNetwork.getId()); - } else if (virtualNetworks.size() > 1) { - throw new InvalidParameterValueException( - "More than 1 default Isolated networks are found for account " - + owner + "; please specify networkIds"); - } else { + if (virtualNetworks.isEmpty()) { + long physicalNetworkId = _networkMgr.findPhysicalNetworkId( + zone.getId(), requiredOfferings.get(0).getTags(), + requiredOfferings.get(0).getTrafficType()); + // Validate physical network + PhysicalNetwork physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); + if (physicalNetwork == null) { + throw new InvalidParameterValueException( + "Unable to find physical network with id: " + + physicalNetworkId + " and tag: " + + requiredOfferings.get(0).getTags()); + } + s_logger.debug("Creating network for account " + owner + + " from the network offering id=" + + requiredOfferings.get(0).getId() + + " as a part of deployVM process"); + Network newNetwork = _networkMgr.createGuestNetwork( + requiredOfferings.get(0).getId(), + owner.getAccountName() + "-network", + owner.getAccountName() + "-network", null, null, + null, null, owner, null, physicalNetwork, + zone.getId(), ACLType.Account, null, null); + defaultNetwork = _networkDao.findById(newNetwork.getId()); + } else if (virtualNetworks.size() > 1) { + throw new InvalidParameterValueException( + "More than 1 default Isolated networks are found for account " + + owner + "; please specify networkIds"); + } else { defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); - } - } else { - throw new InvalidParameterValueException( - "Required network offering id=" - + requiredOfferings.get(0).getId() - + " is not in " + NetworkOffering.State.Enabled); - } - - networkList.add(defaultNetwork); - - } else { - 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.getVpcId() != null) { - // Only ISOs, XenServer, KVM, and VmWare template types are - // supported for vpc networks - if (template.getFormat() != ImageFormat.ISO - && !vpcSupportedHTypes.contains(template - .getHypervisorType())) { - throw new InvalidParameterValueException( - "Can't create vm from template with hypervisor " - + template.getHypervisorType() - + " in vpc network " + network); - } - - // Only XenServer, KVM, and VMware hypervisors are supported - // for vpc networks - if (!vpcSupportedHTypes.contains(hypervisor)) { - throw new InvalidParameterValueException( - "Can't create vm of hypervisor type " - + hypervisor + " in vpc network"); - } - - } - - _networkMgr.checkNetworkPermissions(owner, network); - - // don't allow to use system networks - NetworkOffering networkOffering = _configMgr - .getNetworkOffering(network.getNetworkOfferingId()); - if (networkOffering.isSystemOnly()) { - throw new InvalidParameterValueException( - "Network id=" - + networkId - + " is system only and can't be used for vm deployment"); - } - networkList.add(network); - } - } - - return createVirtualMachine(zone, serviceOffering, template, hostName, - displayName, owner, diskOfferingId, diskSize, networkList, - null, group, userData, sshKeyPair, hypervisor, caller, - requestedIps, defaultIp, keyboard); - } - - @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, - Map requestedIps, String defaultNetworkIp, - String keyboard) throws InsufficientCapacityException, - ResourceUnavailableException, ConcurrentOperationException, - StorageUnavailableException, ResourceAllocationException { - - _accountMgr.checkAccess(caller, null, true, owner); - - if (owner.getState() == Account.State.disabled) { - throw new PermissionDeniedException( - "The owner of vm to deploy is disabled: " + owner); - } - - long accountId = owner.getId(); - - assert !(requestedIps != null && defaultNetworkIp != null) : "requestedIp list and defaultNetworkIp should never be specified together"; - - 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 - _configMgr.checkZoneAccess(caller, zone); - // check that vm owner can create vm in the domain - _configMgr.checkZoneAccess(owner, zone); - } - - // check if account/domain is with in resource limits to create a new vm - boolean isIso = Storage.ImageFormat.ISO == template.getFormat(); - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.user_vm); - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso - || diskOfferingId == null ? 1 : 2)); - - // verify security group ids - if (securityGroupIdList != null) { - for (Long securityGroupId : securityGroupIdList) { - SecurityGroup sg = _securityGroupDao.findById(securityGroupId); - if (sg == null) { - throw new InvalidParameterValueException( - "Unable to find security group by id " - + securityGroupId); - } else { - // verify permissions - _accountMgr.checkAccess(caller, null, true, owner, sg); - } - } - } - - // check if we have available pools for vm deployment - long availablePools = _storagePoolDao - .countPoolsByStatus(StoragePoolStatus.Up); - if (availablePools < 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"); - } - 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"); - } - - if (isIso && !template.isBootable()) { - throw new InvalidParameterValueException( - "Installing from ISO requires an ISO that is bootable: " - + template.getId()); - } - - // Check templates permissions - if (!template.isPublicTemplate()) { - Account templateOwner = _accountMgr.getAccount(template - .getAccountId()); - _accountMgr.checkAccess(owner, null, true, templateOwner); - } - - // check if the user data is correct - 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("")) { - SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), - owner.getDomainId(), sshKeyPair); - if (pair == null) { - throw new InvalidParameterValueException( - "A key pair with name '" + sshKeyPair - + "' was not found."); - } - - sshPublicKey = pair.getPublicKey(); - } - - List> networks = new ArrayList>(); - - List networkUuidList = new ArrayList(); - - short defaultNetworkNumber = 0; - boolean securityGroupEnabled = false; - boolean vpcNetwork = false; - for (NetworkVO network : networkList) { - if (network.getDataCenterId() != zone.getId()) { - throw new InvalidParameterValueException("Network id=" - + network.getId() + " doesn't belong to zone " - + zone.getId()); - } - - String requestedIp = null; - if (requestedIps != null && !requestedIps.isEmpty()) { - requestedIp = requestedIps.get(network.getId()); - } - - NicProfile profile = new NicProfile(requestedIp); - - if (defaultNetworkNumber == 0) { - defaultNetworkNumber++; - // if user requested specific ip for default network, add it - if (defaultNetworkIp != null) { - profile = new NicProfile(defaultNetworkIp); - } - - profile.setDefaultNic(true); - } - - networks.add(new Pair(network, profile)); - - if (_networkMgr.isSecurityGroupSupportedInNetwork(network)) { - securityGroupEnabled = true; - } - - // vm can't be a part of more than 1 VPC network - if (network.getVpcId() != null) { - if (vpcNetwork) { - throw new InvalidParameterValueException( - "Vm can't be a part of more than 1 VPC network"); - } - vpcNetwork = true; - } - - networkUuidList.add(network.getUuid()); - } - - if (securityGroupIdList != null && !securityGroupIdList.isEmpty() - && !securityGroupEnabled) { - throw new InvalidParameterValueException( - "Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network"); - } - - // 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) { - 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); - - String uuidName = UUID.randomUUID().toString(); - - // verify hostname information - if (hostName == null) { - hostName = uuidName; - } else { - // 1) check is hostName is RFC complient - 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"); - } - // 2) hostName has to be unique in the network domain - Map> ntwkDomains = new HashMap>(); - for (NetworkVO network : networkList) { - String ntwkDomain = network.getNetworkDomain(); - if (!ntwkDomains.containsKey(ntwkDomain)) { - List ntwkIds = new ArrayList(); - ntwkIds.add(network.getId()); - ntwkDomains.put(ntwkDomain, ntwkIds); - } else { - List ntwkIds = ntwkDomains.get(ntwkDomain); - ntwkIds.add(network.getId()); - ntwkDomains.put(ntwkDomain, ntwkIds); - } - } - - for (String ntwkDomain : ntwkDomains.keySet()) { - for (Long ntwkId : ntwkDomains.get(ntwkDomain)) { - // * get all vms hostNames in the network - List hostNames = _vmInstanceDao - .listDistinctHostNames(ntwkId); - // * verify that there are no duplicates - if (hostNames.contains(hostName)) { - throw new InvalidParameterValueException( - "The vm with hostName " - + hostName - + " already exists in the network domain: " - + ntwkDomain + "; network=" - + _networkMgr.getNetwork(ntwkId)); - } - } - } - } - - HypervisorType hypervisorType = null; - if (template == null || template.getHypervisorType() == null - || template.getHypervisorType() == HypervisorType.None) { - hypervisorType = hypervisor; - } else { - hypervisorType = template.getHypervisorType(); - } - Transaction txn = Transaction.currentTxn(); - txn.start(); - UserVmVO vm = new UserVmVO(id, instanceName, displayName, - template.getId(), hypervisorType, template.getGuestOSId(), - offering.getOfferHA(), offering.getLimitCpuUse(), - owner.getDomainId(), owner.getId(), offering.getId(), userData, - hostName); - vm.setUuid(uuidName); - - if (sshPublicKey != null) { - vm.setDetail("SSH.PublicKey", sshPublicKey); - } - - if (keyboard != null && !keyboard.isEmpty()) - vm.setDetail(VmDetailConstants.KEYBOARD, keyboard); - - if (isIso) { - vm.setIsoId(template.getId()); - } - - s_logger.debug("Allocating in the DB for vm"); - DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); - - - _vmDao.persist(vm); - _vmDao.saveDetails(vm); - - long guestOSId = template.getGuestOSId(); - GuestOSVO guestOS = _guestOSDao.findById(guestOSId); - long guestOSCategoryId = guestOS.getCategoryId(); - GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId); - - List computeTags = new ArrayList(); - computeTags.add(offering.getHostTag()); - - List rootDiskTags = new ArrayList(); - rootDiskTags.add(offering.getTags()); - - if(isIso){ - VirtualMachineEntity vmEntity = _orchSrvc.createVirtualMachineFromScratch(vm.getUuid(), owner.getAccountName(), vm.getIsoId().toString(), hostName, displayName, hypervisor.name(), guestOSCategory.getName(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkUuidList, plan); - }else { - VirtualMachineEntity vmEntity = _orchSrvc.createVirtualMachine(vm.getUuid(), owner.getAccountName(), new Long(template.getId()).toString(), hostName, displayName, hypervisor.name(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkUuidList, plan); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Successfully allocated DB entry for " + vm); - } - UserContext.current().setEventDetails("Vm Id: " + vm.getId()); - - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, - accountId, zone.getId(), vm.getId(), vm.getHostName(), - offering.getId(), template.getId(), hypervisorType.toString()); - _usageEventDao.persist(usageEvent); - - _resourceLimitMgr.incrementResourceCount(accountId, - ResourceType.user_vm); - txn.commit(); - // Assign instance to the group - try { - if (group != null) { - boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group); - if (!addToGroup) { - throw new CloudRuntimeException( - "Unable to assign Vm to the group " + group); - } - } - } catch (Exception ex) { - throw new CloudRuntimeException("Unable to assign Vm to the group " - + group); - } - - _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList); - - return vm; - } - - private void validateUserData(String userData) { - byte[] decodedUserData = null; - if (userData != null) { - if (!Base64.isBase64(userData)) { - throw new InvalidParameterValueException( - "User data is not base64 encoded"); - } - if (userData.length() >= 2 * MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException( - "User data is too long"); - } - decodedUserData = Base64.decodeBase64(userData.getBytes()); - 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(); - Long hostId = cmd.getHostId(); - UserVmVO vm = _vmDao.findById(vmId); - - Pair> vmParamPair = null; - try { - vmParamPair = startVirtualMachine(vmId, hostId, additonalParams); - vm = vmParamPair.first(); - ; - } finally { - updateVmStateForFailedVmCreation(vm.getId()); - } - - // Check that the password was passed in and is valid - VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm - .getTemplateId()); - if (template.getEnablePassword()) { - // this value is not being sent to the backend; need only for api - // display purposes - vm.setPassword((String) vmParamPair.second().get( - VirtualMachineProfile.Param.VmPassword)); - } - - return vm; - } - - @Override - public boolean finalizeVirtualMachineProfile( - VirtualMachineProfile profile, DeployDestination dest, - ReservationContext context) { - UserVmVO vm = profile.getVirtualMachine(); - Map details = _vmDetailsDao.findDetails(vm.getId()); - vm.setDetails(details); - - if (vm.getIsoId() != null) { - String isoPath = null; - - VirtualMachineTemplate template = _templateDao.findById(vm - .getIsoId()); - if (template == null || template.getFormat() != ImageFormat.ISO) { - throw new CloudRuntimeException( - "Can not find ISO in vm_template table for id " - + vm.getIsoId()); - } - - Pair isoPathPair = _storageMgr.getAbsoluteIsoPath( - template.getId(), vm.getDataCenterIdToDeployIn()); - - if (template.getTemplateType() == TemplateType.PERHOST) { - isoPath = template.getName(); - } else { - 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 { - VirtualMachineTemplate template = profile.getTemplate(); - /* 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()); - } - } - 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(); - - Answer[] answersToCmds = cmds.getAnswers(); - if (answersToCmds == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Returning from finalizeStart() since there are no answers to read"); - } - return true; - } - Answer startAnswer = cmds.getAnswer(StartAnswer.class); - String returnedIp = null; - String originalIp = null; - if (startAnswer != null) { - StartAnswer startAns = (StartAnswer) startAnswer; - VirtualMachineTO vmTO = startAns.getVirtualMachine(); - for (NicTO nicTO : vmTO.getNics()) { - if (nicTO.getType() == TrafficType.Guest) { - returnedIp = nicTO.getIp(); - } - } - } - - List nics = _nicDao.listByVmId(vm.getId()); - NicVO guestNic = null; - NetworkVO guestNetwork = null; - for (NicVO nic : nics) { - NetworkVO network = _networkDao.findById(nic.getNetworkId()); - long isDefault = (nic.isDefaultNic()) ? 1 : 0; - UsageEventVO usageEvent = new UsageEventVO( - EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, - vm.getAccountId(), vm.getDataCenterIdToDeployIn(), - vm.getId(), vm.getHostName(), - network.getNetworkOfferingId(), null, isDefault); - _usageEventDao.persist(usageEvent); - if (network.getTrafficType() == TrafficType.Guest) { - originalIp = nic.getIp4Address(); - guestNic = nic; - guestNetwork = network; - } - } - boolean ipChanged = false; - if (originalIp != null && !originalIp.equalsIgnoreCase(returnedIp)) { - if (returnedIp != null && guestNic != null) { - guestNic.setIp4Address(returnedIp); - ipChanged = true; - } - } - if (returnedIp != null && !returnedIp.equalsIgnoreCase(originalIp)) { - if (guestNic != null) { - guestNic.setIp4Address(returnedIp); - ipChanged = true; - } - } - if (ipChanged) { - DataCenterVO dc = _dcDao.findById(vm.getDataCenterIdToDeployIn()); - UserVmVO userVm = profile.getVirtualMachine(); - // dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName()) - if (_ntwkSrvcDao.canProviderSupportServiceInNetwork( - guestNetwork.getId(), Service.Dhcp, - Provider.ExternalDhcpServer)) { - _nicDao.update(guestNic.getId(), guestNic); - userVm.setPrivateIpAddress(guestNic.getIp4Address()); - _vmDao.update(userVm.getId(), userVm); - - s_logger.info("Detected that ip changed in the answer, updated nic in the db with new ip " - + returnedIp); - } - } - - // get system ip and create static nat rule for the vm - try { - _rulesMgr.getSystemIpAndEnableStaticNatForVm( - profile.getVirtualMachine(), false); - } catch (Exception ex) { - s_logger.warn( - "Failed to get system ip and enable static nat for the vm " - + profile.getVirtualMachine() - + " due to exception ", ex); - return false; - } - - 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)) { - return null; - } - return findById(VirtualMachineName.getVmId(name)); - } - - @Override - @ActionEvent(eventType = EventTypes.EVENT_VM_STOP, eventDescription = "stopping Vm", async = true) - public UserVm stopVirtualMachine(long vmId, boolean forced) - throws ConcurrentOperationException { - // Input validation - Account caller = UserContext.current().getCaller(); - Long userId = UserContext.current().getCallerUserId(); - - // if account is removed, return error - if (caller != null && caller.getRemoved() != null) { - 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); - } - - UserVO user = _userDao.findById(userId); - - try { - _itMgr.advanceStop(vm, forced, user, caller); - } catch (ResourceUnavailableException e) { - 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) { - // release elastic IP here - IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId()); - if (ip != null && ip.getSystem()) { - UserContext ctx = UserContext.current(); - try { + } + } else { + throw new InvalidParameterValueException( + "Required network offering id=" + + requiredOfferings.get(0).getId() + + " is not in " + NetworkOffering.State.Enabled); + } + + networkList.add(defaultNetwork); + + } else { + 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.getVpcId() != null) { + // Only ISOs, XenServer, KVM, and VmWare template types are + // supported for vpc networks + if (template.getFormat() != ImageFormat.ISO + && !vpcSupportedHTypes.contains(template + .getHypervisorType())) { + throw new InvalidParameterValueException( + "Can't create vm from template with hypervisor " + + template.getHypervisorType() + + " in vpc network " + network); + } + + // Only XenServer, KVM, and VMware hypervisors are supported + // for vpc networks + if (!vpcSupportedHTypes.contains(hypervisor)) { + throw new InvalidParameterValueException( + "Can't create vm of hypervisor type " + + hypervisor + " in vpc network"); + } + + } + + _networkMgr.checkNetworkPermissions(owner, network); + + // don't allow to use system networks + NetworkOffering networkOffering = _configMgr + .getNetworkOffering(network.getNetworkOfferingId()); + if (networkOffering.isSystemOnly()) { + throw new InvalidParameterValueException( + "Network id=" + + networkId + + " is system only and can't be used for vm deployment"); + } + networkList.add(network); + } + } + + return createVirtualMachine(zone, serviceOffering, template, hostName, + displayName, owner, diskOfferingId, diskSize, networkList, + null, group, userData, sshKeyPair, hypervisor, caller, + requestedIps, defaultIp, keyboard); + } + + @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, + Map requestedIps, String defaultNetworkIp, + String keyboard) throws InsufficientCapacityException, + ResourceUnavailableException, ConcurrentOperationException, + StorageUnavailableException, ResourceAllocationException { + + _accountMgr.checkAccess(caller, null, true, owner); + + if (owner.getState() == Account.State.disabled) { + throw new PermissionDeniedException( + "The owner of vm to deploy is disabled: " + owner); + } + + long accountId = owner.getId(); + + assert !(requestedIps != null && defaultNetworkIp != null) : "requestedIp list and defaultNetworkIp should never be specified together"; + + 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 + _configMgr.checkZoneAccess(caller, zone); + // check that vm owner can create vm in the domain + _configMgr.checkZoneAccess(owner, zone); + } + + // check if account/domain is with in resource limits to create a new vm + boolean isIso = Storage.ImageFormat.ISO == template.getFormat(); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.user_vm); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso + || diskOfferingId == null ? 1 : 2)); + + // verify security group ids + if (securityGroupIdList != null) { + for (Long securityGroupId : securityGroupIdList) { + SecurityGroup sg = _securityGroupDao.findById(securityGroupId); + if (sg == null) { + throw new InvalidParameterValueException( + "Unable to find security group by id " + + securityGroupId); + } else { + // verify permissions + _accountMgr.checkAccess(caller, null, true, owner, sg); + } + } + } + + // check if we have available pools for vm deployment + long availablePools = _storagePoolDao + .countPoolsByStatus(StoragePoolStatus.Up); + if (availablePools < 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"); + } + 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"); + } + + if (isIso && !template.isBootable()) { + throw new InvalidParameterValueException( + "Installing from ISO requires an ISO that is bootable: " + + template.getId()); + } + + // Check templates permissions + if (!template.isPublicTemplate()) { + Account templateOwner = _accountMgr.getAccount(template + .getAccountId()); + _accountMgr.checkAccess(owner, null, true, templateOwner); + } + + // check if the user data is correct + 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("")) { + SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), + owner.getDomainId(), sshKeyPair); + if (pair == null) { + throw new InvalidParameterValueException( + "A key pair with name '" + sshKeyPair + + "' was not found."); + } + + sshPublicKey = pair.getPublicKey(); + } + + List> networks = new ArrayList>(); + + List networkUuidList = new ArrayList(); + + short defaultNetworkNumber = 0; + boolean securityGroupEnabled = false; + boolean vpcNetwork = false; + for (NetworkVO network : networkList) { + if (network.getDataCenterId() != zone.getId()) { + throw new InvalidParameterValueException("Network id=" + + network.getId() + " doesn't belong to zone " + + zone.getId()); + } + + String requestedIp = null; + if (requestedIps != null && !requestedIps.isEmpty()) { + requestedIp = requestedIps.get(network.getId()); + } + + NicProfile profile = new NicProfile(requestedIp); + + if (defaultNetworkNumber == 0) { + defaultNetworkNumber++; + // if user requested specific ip for default network, add it + if (defaultNetworkIp != null) { + profile = new NicProfile(defaultNetworkIp); + } + + profile.setDefaultNic(true); + } + + networks.add(new Pair(network, profile)); + + if (_networkMgr.isSecurityGroupSupportedInNetwork(network)) { + securityGroupEnabled = true; + } + + // vm can't be a part of more than 1 VPC network + if (network.getVpcId() != null) { + if (vpcNetwork) { + throw new InvalidParameterValueException( + "Vm can't be a part of more than 1 VPC network"); + } + vpcNetwork = true; + } + + networkUuidList.add(network.getUuid()); + } + + if (securityGroupIdList != null && !securityGroupIdList.isEmpty() + && !securityGroupEnabled) { + throw new InvalidParameterValueException( + "Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network"); + } + + // 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) { + 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); + + String uuidName = UUID.randomUUID().toString(); + + // verify hostname information + if (hostName == null) { + hostName = uuidName; + } else { + // 1) check is hostName is RFC complient + 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"); + } + // 2) hostName has to be unique in the network domain + Map> ntwkDomains = new HashMap>(); + for (NetworkVO network : networkList) { + String ntwkDomain = network.getNetworkDomain(); + if (!ntwkDomains.containsKey(ntwkDomain)) { + List ntwkIds = new ArrayList(); + ntwkIds.add(network.getId()); + ntwkDomains.put(ntwkDomain, ntwkIds); + } else { + List ntwkIds = ntwkDomains.get(ntwkDomain); + ntwkIds.add(network.getId()); + ntwkDomains.put(ntwkDomain, ntwkIds); + } + } + + for (String ntwkDomain : ntwkDomains.keySet()) { + for (Long ntwkId : ntwkDomains.get(ntwkDomain)) { + // * get all vms hostNames in the network + List hostNames = _vmInstanceDao + .listDistinctHostNames(ntwkId); + // * verify that there are no duplicates + if (hostNames.contains(hostName)) { + throw new InvalidParameterValueException( + "The vm with hostName " + + hostName + + " already exists in the network domain: " + + ntwkDomain + "; network=" + + _networkMgr.getNetwork(ntwkId)); + } + } + } + } + + HypervisorType hypervisorType = null; + if (template == null || template.getHypervisorType() == null + || template.getHypervisorType() == HypervisorType.None) { + hypervisorType = hypervisor; + } else { + hypervisorType = template.getHypervisorType(); + } + Transaction txn = Transaction.currentTxn(); + txn.start(); + UserVmVO vm = new UserVmVO(id, instanceName, displayName, + template.getId(), hypervisorType, template.getGuestOSId(), + offering.getOfferHA(), offering.getLimitCpuUse(), + owner.getDomainId(), owner.getId(), offering.getId(), userData, + hostName); + vm.setUuid(uuidName); + + if (sshPublicKey != null) { + vm.setDetail("SSH.PublicKey", sshPublicKey); + } + + if (keyboard != null && !keyboard.isEmpty()) + vm.setDetail(VmDetailConstants.KEYBOARD, keyboard); + + if (isIso) { + vm.setIsoId(template.getId()); + } + + s_logger.debug("Allocating in the DB for vm"); + DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); + + + _vmDao.persist(vm); + _vmDao.saveDetails(vm); + + long guestOSId = template.getGuestOSId(); + GuestOSVO guestOS = _guestOSDao.findById(guestOSId); + long guestOSCategoryId = guestOS.getCategoryId(); + GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId); + + List computeTags = new ArrayList(); + computeTags.add(offering.getHostTag()); + + List rootDiskTags = new ArrayList(); + rootDiskTags.add(offering.getTags()); + + if(isIso){ + VirtualMachineEntity vmEntity = _orchSrvc.createVirtualMachineFromScratch(vm.getUuid(), owner.getAccountName(), vm.getIsoId().toString(), hostName, displayName, hypervisor.name(), guestOSCategory.getName(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkUuidList, plan); + }else { + VirtualMachineEntity vmEntity = _orchSrvc.createVirtualMachine(vm.getUuid(), owner.getAccountName(), new Long(template.getId()).toString(), hostName, displayName, hypervisor.name(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkUuidList, plan); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Successfully allocated DB entry for " + vm); + } + UserContext.current().setEventDetails("Vm Id: " + vm.getId()); + + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, + accountId, zone.getId(), vm.getId(), vm.getHostName(), + offering.getId(), template.getId(), hypervisorType.toString()); + _usageEventDao.persist(usageEvent); + + _resourceLimitMgr.incrementResourceCount(accountId, + ResourceType.user_vm); + txn.commit(); + // Assign instance to the group + try { + if (group != null) { + boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group); + if (!addToGroup) { + throw new CloudRuntimeException( + "Unable to assign Vm to the group " + group); + } + } + } catch (Exception ex) { + throw new CloudRuntimeException("Unable to assign Vm to the group " + + group); + } + + _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList); + + return vm; + } + + private void validateUserData(String userData) { + byte[] decodedUserData = null; + if (userData != null) { + if (!Base64.isBase64(userData)) { + throw new InvalidParameterValueException( + "User data is not base64 encoded"); + } + if (userData.length() >= 2 * MAX_USER_DATA_LENGTH_BYTES) { + throw new InvalidParameterValueException( + "User data is too long"); + } + decodedUserData = Base64.decodeBase64(userData.getBytes()); + 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(); + Long hostId = cmd.getHostId(); + UserVmVO vm = _vmDao.findById(vmId); + + Pair> vmParamPair = null; + try { + vmParamPair = startVirtualMachine(vmId, hostId, additonalParams); + vm = vmParamPair.first(); + ; + } finally { + updateVmStateForFailedVmCreation(vm.getId()); + } + + // Check that the password was passed in and is valid + VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm + .getTemplateId()); + if (template.getEnablePassword()) { + // this value is not being sent to the backend; need only for api + // display purposes + vm.setPassword((String) vmParamPair.second().get( + VirtualMachineProfile.Param.VmPassword)); + } + + return vm; + } + + @Override + public boolean finalizeVirtualMachineProfile( + VirtualMachineProfile profile, DeployDestination dest, + ReservationContext context) { + UserVmVO vm = profile.getVirtualMachine(); + Map details = _vmDetailsDao.findDetails(vm.getId()); + vm.setDetails(details); + + if (vm.getIsoId() != null) { + String isoPath = null; + + VirtualMachineTemplate template = _templateDao.findById(vm + .getIsoId()); + if (template == null || template.getFormat() != ImageFormat.ISO) { + throw new CloudRuntimeException( + "Can not find ISO in vm_template table for id " + + vm.getIsoId()); + } + + Pair isoPathPair = _storageMgr.getAbsoluteIsoPath( + template.getId(), vm.getDataCenterIdToDeployIn()); + + if (template.getTemplateType() == TemplateType.PERHOST) { + isoPath = template.getName(); + } else { + 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 { + VirtualMachineTemplate template = profile.getTemplate(); + /* 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()); + } + } + 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(); + + Answer[] answersToCmds = cmds.getAnswers(); + if (answersToCmds == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Returning from finalizeStart() since there are no answers to read"); + } + return true; + } + Answer startAnswer = cmds.getAnswer(StartAnswer.class); + String returnedIp = null; + String originalIp = null; + if (startAnswer != null) { + StartAnswer startAns = (StartAnswer) startAnswer; + VirtualMachineTO vmTO = startAns.getVirtualMachine(); + for (NicTO nicTO : vmTO.getNics()) { + if (nicTO.getType() == TrafficType.Guest) { + returnedIp = nicTO.getIp(); + } + } + } + + List nics = _nicDao.listByVmId(vm.getId()); + NicVO guestNic = null; + NetworkVO guestNetwork = null; + for (NicVO nic : nics) { + NetworkVO network = _networkDao.findById(nic.getNetworkId()); + long isDefault = (nic.isDefaultNic()) ? 1 : 0; + UsageEventVO usageEvent = new UsageEventVO( + EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, + vm.getAccountId(), vm.getDataCenterIdToDeployIn(), + vm.getId(), vm.getHostName(), + network.getNetworkOfferingId(), null, isDefault); + _usageEventDao.persist(usageEvent); + if (network.getTrafficType() == TrafficType.Guest) { + originalIp = nic.getIp4Address(); + guestNic = nic; + guestNetwork = network; + } + } + boolean ipChanged = false; + if (originalIp != null && !originalIp.equalsIgnoreCase(returnedIp)) { + if (returnedIp != null && guestNic != null) { + guestNic.setIp4Address(returnedIp); + ipChanged = true; + } + } + if (returnedIp != null && !returnedIp.equalsIgnoreCase(originalIp)) { + if (guestNic != null) { + guestNic.setIp4Address(returnedIp); + ipChanged = true; + } + } + if (ipChanged) { + DataCenterVO dc = _dcDao.findById(vm.getDataCenterIdToDeployIn()); + UserVmVO userVm = profile.getVirtualMachine(); + // dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName()) + if (_ntwkSrvcDao.canProviderSupportServiceInNetwork( + guestNetwork.getId(), Service.Dhcp, + Provider.ExternalDhcpServer)) { + _nicDao.update(guestNic.getId(), guestNic); + userVm.setPrivateIpAddress(guestNic.getIp4Address()); + _vmDao.update(userVm.getId(), userVm); + + s_logger.info("Detected that ip changed in the answer, updated nic in the db with new ip " + + returnedIp); + } + } + + // get system ip and create static nat rule for the vm + try { + _rulesMgr.getSystemIpAndEnableStaticNatForVm( + profile.getVirtualMachine(), false); + } catch (Exception ex) { + s_logger.warn( + "Failed to get system ip and enable static nat for the vm " + + profile.getVirtualMachine() + + " due to exception ", ex); + return false; + } + + 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)) { + return null; + } + return findById(VirtualMachineName.getVmId(name)); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_STOP, eventDescription = "stopping Vm", async = true) + public UserVm stopVirtualMachine(long vmId, boolean forced) + throws ConcurrentOperationException { + // Input validation + Account caller = UserContext.current().getCaller(); + Long userId = UserContext.current().getCallerUserId(); + + // if account is removed, return error + if (caller != null && caller.getRemoved() != null) { + 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); + } + + UserVO user = _userDao.findById(userId); + + try { + _itMgr.advanceStop(vm, forced, user, caller); + } catch (ResourceUnavailableException e) { + 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) { + // release elastic IP here + IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId()); + if (ip != null && ip.getSystem()) { + UserContext ctx = UserContext.current(); + try { long networkId = ip.getAssociatedWithNetworkId(); Network guestNetwork = _networkMgr.getNetwork(networkId); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); assert (offering.getAssociatePublicIP() == true) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP."; _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); - } catch (Exception ex) { - s_logger.warn( - "Failed to disable static nat and release system ip " - + ip + " as a part of vm " - + profile.getVirtualMachine() - + " stop due to exception ", ex); - } - } - } + } catch (Exception ex) { + s_logger.warn( + "Failed to disable static nat and release system ip " + + ip + " as a part of vm " + + profile.getVirtualMachine() + + " stop due to exception ", ex); + } + } + } - public String generateRandomPassword() { - return PasswordGenerator.generateRandomPassword(6); - } + public String generateRandomPassword() { + return PasswordGenerator.generateRandomPassword(6); + } - @Override - public Pair> startVirtualMachine( - long vmId, Long hostId, - Map additionalParams) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - // Input validation - Account callerAccount = UserContext.current().getCaller(); - UserVO callerUser = _userDao.findById(UserContext.current() - .getCallerUserId()); + @Override + public Pair> startVirtualMachine( + long vmId, Long hostId, + Map additionalParams) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + // Input validation + Account callerAccount = UserContext.current().getCaller(); + UserVO callerUser = _userDao.findById(UserContext.current() + .getCallerUserId()); - // if account is removed, return error - if (callerAccount != null && callerAccount.getRemoved() != null) { - throw new InvalidParameterValueException("The account " - + callerAccount.getId() + " is removed"); - } + // if account is removed, return error + if (callerAccount != null && callerAccount.getRemoved() != null) { + throw new InvalidParameterValueException("The account " + + callerAccount.getId() + " is removed"); + } - UserVmVO vm = _vmDao.findById(vmId); - if (vm == null) { - throw new InvalidParameterValueException( - "unable to find a virtual machine with id " + vmId); - } + UserVmVO vm = _vmDao.findById(vmId); + if (vm == null) { + throw new InvalidParameterValueException( + "unable to find a virtual machine with id " + vmId); + } - _accountMgr.checkAccess(callerAccount, null, true, vm); + _accountMgr.checkAccess(callerAccount, null, true, vm); - Account owner = _accountDao.findById(vm.getAccountId()); + Account owner = _accountDao.findById(vm.getAccountId()); - if (owner == null) { - throw new InvalidParameterValueException("The owner of " + vm - + " does not exist: " + vm.getAccountId()); - } + if (owner == null) { + throw new InvalidParameterValueException("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()); - } + if (owner.getState() == Account.State.disabled) { + throw new PermissionDeniedException("The owner of " + vm + + " is disabled: " + vm.getAccountId()); + } - Host destinationHost = null; - if (hostId != null) { - Account account = UserContext.current().getCaller(); - if (!_accountService.isRootAdmin(account.getType())) { - throw new PermissionDeniedException( - "Parameter hostid can only be specified by a Root Admin, permission denied"); - } - destinationHost = _hostDao.findById(hostId); - if (destinationHost == null) { - throw new InvalidParameterValueException( - "Unable to find the host to deploy the VM, host id=" - + hostId); - } - } + Host destinationHost = null; + if (hostId != null) { + Account account = UserContext.current().getCaller(); + if (!_accountService.isRootAdmin(account.getType())) { + throw new PermissionDeniedException( + "Parameter hostid can only be specified by a Root Admin, permission denied"); + } + destinationHost = _hostDao.findById(hostId); + if (destinationHost == null) { + throw new InvalidParameterValueException( + "Unable to find the host to deploy the VM, host id=" + + hostId); + } + } - // check if vm is security group enabled - if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) - && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() - && !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) - && _networkMgr.canAddDefaultSecurityGroup()) { - // if vm is not mapped to security group, create a mapping - if (s_logger.isDebugEnabled()) { - s_logger.debug("Vm " - + vm - + " is security group enabled, but not mapped to default security group; creating the mapping automatically"); - } + // check if vm is security group enabled + if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) + && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() + && !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) + && _networkMgr.canAddDefaultSecurityGroup()) { + // if vm is not mapped to security group, create a mapping + if (s_logger.isDebugEnabled()) { + s_logger.debug("Vm " + + vm + + " is security group enabled, but not mapped to default security group; creating the mapping automatically"); + } - SecurityGroup defaultSecurityGroup = _securityGroupMgr - .getDefaultSecurityGroup(vm.getAccountId()); - if (defaultSecurityGroup != null) { - List groupList = new ArrayList(); - groupList.add(defaultSecurityGroup.getId()); - _securityGroupMgr.addInstanceToGroups(vmId, groupList); - } - } + SecurityGroup defaultSecurityGroup = _securityGroupMgr + .getDefaultSecurityGroup(vm.getAccountId()); + if (defaultSecurityGroup != null) { + List groupList = new ArrayList(); + groupList.add(defaultSecurityGroup.getId()); + _securityGroupMgr.addInstanceToGroups(vmId, groupList); + } + } - DataCenterDeployment plan = null; - if (destinationHost != null) { - s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM"); - plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), - destinationHost.getPodId(), destinationHost.getClusterId(), - destinationHost.getId(), null, null); - } + DataCenterDeployment plan = null; + if (destinationHost != null) { + s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM"); + plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), + destinationHost.getPodId(), destinationHost.getClusterId(), + destinationHost.getId(), null, null); + } - // Set parameters - Map params = null; - VMTemplateVO template = null; - if (vm.isUpdateParameters()) { - _vmDao.loadDetails(vm); - // Check that the password was passed in and is valid - template = _templateDao - .findByIdIncludingRemoved(vm.getTemplateId()); + // Set parameters + Map params = null; + VMTemplateVO template = null; + if (vm.isUpdateParameters()) { + _vmDao.loadDetails(vm); + // Check that the password was passed in and is valid + template = _templateDao + .findByIdIncludingRemoved(vm.getTemplateId()); - String password = "saved_password"; - if (template.getEnablePassword()) { - password = generateRandomPassword(); - } + String password = "saved_password"; + if (template.getEnablePassword()) { + password = generateRandomPassword(); + } - if (!validPassword(password)) { - throw new InvalidParameterValueException( - "A valid password for this virtual machine was not provided."); - } + if (!validPassword(password)) { + 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) { - throw new CloudRuntimeException("Error encrypting password"); - } + // 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) { + throw new CloudRuntimeException("Error encrypting password"); + } - vm.setDetail("Encrypted.Password", encryptedPasswd); - _vmDao.saveDetails(vm); - } + vm.setDetail("Encrypted.Password", encryptedPasswd); + _vmDao.saveDetails(vm); + } - params = new HashMap(); - if (additionalParams != null) { - params.putAll(additionalParams); - } - params.put(VirtualMachineProfile.Param.VmPassword, password); - } + params = new HashMap(); + if (additionalParams != null) { + params.putAll(additionalParams); + } + params.put(VirtualMachineProfile.Param.VmPassword, password); + } - vm = _itMgr.start(vm, params, callerUser, callerAccount, plan); + vm = _itMgr.start(vm, params, callerUser, callerAccount, plan); - Pair> vmParamPair = new Pair( - vm, params); - if (vm != null && vm.isUpdateParameters()) { - // this value is not being sent to the backend; need only for api - // display purposes - if (template.getEnablePassword()) { - vm.setPassword((String) vmParamPair.second().get( - VirtualMachineProfile.Param.VmPassword)); - vm.setUpdateParameters(false); - _vmDao.update(vm.getId(), vm); - } - } + Pair> vmParamPair = new Pair( + vm, params); + if (vm != null && vm.isUpdateParameters()) { + // this value is not being sent to the backend; need only for api + // display purposes + if (template.getEnablePassword()) { + vm.setPassword((String) vmParamPair.second().get( + VirtualMachineProfile.Param.VmPassword)); + vm.setUpdateParameters(false); + _vmDao.update(vm.getId(), vm); + } + } - return vmParamPair; - } + return vmParamPair; + } - @Override - public UserVm destroyVm(long vmId) throws ResourceUnavailableException, - ConcurrentOperationException { - Account caller = UserContext.current().getCaller(); - Long userId = UserContext.current().getCallerUserId(); + @Override + public UserVm destroyVm(long vmId) throws ResourceUnavailableException, + ConcurrentOperationException { + Account caller = UserContext.current().getCaller(); + Long userId = UserContext.current().getCallerUserId(); - // Verify input parameters - UserVmVO vm = _vmDao.findById(vmId); - if (vm == null || vm.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Unable to find a virtual machine with specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } + // Verify input parameters + UserVmVO vm = _vmDao.findById(vmId); + if (vm == null || vm.getRemoved() != null) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Unable to find a virtual machine with specified vmId"); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } - if (vm.getState() == State.Destroyed - || vm.getState() == State.Expunging) { - s_logger.trace("Vm id=" + vmId + " is already destroyed"); - return vm; - } + if (vm.getState() == State.Destroyed + || vm.getState() == State.Expunging) { + s_logger.trace("Vm id=" + vmId + " is already destroyed"); + return vm; + } - _accountMgr.checkAccess(caller, null, true, vm); - User userCaller = _userDao.findById(userId); + _accountMgr.checkAccess(caller, null, true, vm); + User userCaller = _userDao.findById(userId); - boolean status; - State vmState = vm.getState(); + boolean status; + State vmState = vm.getState(); - try { - status = _itMgr.destroy(vm, userCaller, caller); - } catch (OperationTimedoutException e) { - CloudRuntimeException ex = new CloudRuntimeException( - "Unable to destroy with specified vmId", e); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } + try { + status = _itMgr.destroy(vm, userCaller, caller); + } catch (OperationTimedoutException e) { + CloudRuntimeException ex = new CloudRuntimeException( + "Unable to destroy with specified vmId", e); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } - 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()); - _usageEventDao.persist(usageEvent); - } - } + 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()); + _usageEventDao.persist(usageEvent); + } + } - if (vmState != State.Error) { - _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), - ResourceType.user_vm); - } + if (vmState != State.Error) { + _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), + ResourceType.user_vm); + } - return _vmDao.findById(vmId); - } else { - CloudRuntimeException ex = new CloudRuntimeException( - "Failed to destroy vm with specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } - } + return _vmDao.findById(vmId); + } else { + CloudRuntimeException ex = new CloudRuntimeException( + "Failed to destroy vm with specified vmId"); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } + } @@ -3589,38 +3660,38 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - Object id = c.getCriteria(Criteria.ID); - Object name = c.getCriteria(Criteria.NAME); - Object state = c.getCriteria(Criteria.STATE); - Object notState = c.getCriteria(Criteria.NOTSTATE); - Object zone = c.getCriteria(Criteria.DATACENTERID); - Object pod = c.getCriteria(Criteria.PODID); - Object hostId = c.getCriteria(Criteria.HOSTID); - Object hostName = c.getCriteria(Criteria.HOSTNAME); - Object keyword = c.getCriteria(Criteria.KEYWORD); - Object isAdmin = c.getCriteria(Criteria.ISADMIN); - assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more. If you see this assert, it means we have to find a different way to search by the nic table."; - Object groupId = c.getCriteria(Criteria.GROUPID); - Object networkId = c.getCriteria(Criteria.NETWORKID); - Object hypervisor = c.getCriteria(Criteria.HYPERVISOR); - Object storageId = c.getCriteria(Criteria.STORAGE_ID); - Object templateId = c.getCriteria(Criteria.TEMPLATE_ID); - Object isoId = c.getCriteria(Criteria.ISO_ID); - Object vpcId = c.getCriteria(Criteria.VPC_ID); + Object id = c.getCriteria(Criteria.ID); + Object name = c.getCriteria(Criteria.NAME); + Object state = c.getCriteria(Criteria.STATE); + Object notState = c.getCriteria(Criteria.NOTSTATE); + Object zone = c.getCriteria(Criteria.DATACENTERID); + Object pod = c.getCriteria(Criteria.PODID); + Object hostId = c.getCriteria(Criteria.HOSTID); + Object hostName = c.getCriteria(Criteria.HOSTNAME); + Object keyword = c.getCriteria(Criteria.KEYWORD); + Object isAdmin = c.getCriteria(Criteria.ISADMIN); + assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more. If you see this assert, it means we have to find a different way to search by the nic table."; + Object groupId = c.getCriteria(Criteria.GROUPID); + Object networkId = c.getCriteria(Criteria.NETWORKID); + Object hypervisor = c.getCriteria(Criteria.HYPERVISOR); + Object storageId = c.getCriteria(Criteria.STORAGE_ID); + Object templateId = c.getCriteria(Criteria.TEMPLATE_ID); + Object isoId = c.getCriteria(Criteria.ISO_ID); + Object vpcId = c.getCriteria(Criteria.VPC_ID); - sb.and("displayName", sb.entity().getDisplayName(), - SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); - sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); - sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN); + sb.and("displayName", sb.entity().getDisplayName(), + SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN); sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ); - sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); + sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE); - sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ); sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); @@ -3656,89 +3727,89 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (tags != null && !tags.isEmpty()) { int count = 0; - for (String key : tags.keySet()) { + for (String key : tags.keySet()) { sc.setParameters("key" + String.valueOf(count), key); sc.setParameters("value" + String.valueOf(count), tags.get(key)); - count++; - } - } + count++; + } + } if (groupId != null && (Long)groupId != -1) { sc.setParameters("instanceGroupId", groupId); - } + } - if (keyword != null) { + if (keyword != null) { SearchCriteria ssc = _vmJoinDao.createSearchCriteria(); ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword - + "%"); - ssc.addOr("state", SearchCriteria.Op.EQ, keyword); + ssc.addOr("hostName", 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); - } + sc.addAnd("displayName", SearchCriteria.Op.SC, ssc); + } - if (id != null) { - sc.setParameters("id", id); - } + if (id != null) { + sc.setParameters("id", id); + } - if (templateId != null) { - sc.setParameters("templateId", templateId); - } + if (templateId != null) { + sc.setParameters("templateId", templateId); + } - if (isoId != null) { - sc.setParameters("isoId", isoId); - } + if (isoId != null) { + sc.setParameters("isoId", isoId); + } - if (networkId != null) { + if (networkId != null) { sc.setParameters("networkId", networkId); - } + } if(vpcId != null && networkId == null){ sc.setParameters("vpcId", vpcId); - } + } - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } - if (state != null) { - if (notState != null && (Boolean) notState == true) { - sc.setParameters("stateNEQ", state); - } else { - sc.setParameters("stateEQ", state); - } - } + if (state != null) { + if (notState != null && (Boolean) notState == true) { + sc.setParameters("stateNEQ", state); + } else { + sc.setParameters("stateEQ", state); + } + } - 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 - if ((isAdmin != null) && ((Boolean) isAdmin != true)) { - sc.setParameters("stateNIN", "Destroyed", "Expunging"); - } + // 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 (pod != null) { - sc.setParameters("podId", pod); + if (zone != null) { + sc.setParameters("dataCenterId", zone); + } + if (pod != null) { + sc.setParameters("podId", pod); - if (state == null) { - sc.setParameters("stateNEQ", "Destroyed"); - } - } + if (state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } + } - if (hostId != null) { - sc.setParameters("hostIdEQ", hostId); - } else { - if (hostName != null) { + if (hostId != null) { + sc.setParameters("hostIdEQ", hostId); + } else { + if (hostName != null) { sc.setParameters("hostName", hostName); - } - } + } + } - if (storageId != null) { + if (storageId != null) { sc.setParameters("poolId", storageId); } @@ -3748,7 +3819,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if ( count.intValue() == 0 ){ // handle empty result cases return uniqueVmPair; - } + } List uniqueVms = uniqueVmPair.first(); Long[] vmIds = new Long[uniqueVms.size()]; int i = 0; @@ -3757,724 +3828,724 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } List vms = _vmJoinDao.searchByIds(vmIds); return new Pair, Integer>(vms, count); - } + } - @Override - public HypervisorType getHypervisorTypeOfUserVM(long vmId) { - UserVmVO userVm = _vmDao.findById(vmId); - if (userVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "unable to find a virtual machine with specified id"); - ex.addProxyObject(userVm, vmId, "vmId"); - throw ex; - } + @Override + public HypervisorType getHypervisorTypeOfUserVM(long vmId) { + UserVmVO userVm = _vmDao.findById(vmId); + if (userVm == null) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "unable to find a virtual machine with specified id"); + ex.addProxyObject(userVm, vmId, "vmId"); + throw ex; + } - return userVm.getHypervisorType(); - } + 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 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 + public UserVm getUserVm(long vmId) { + return _vmDao.findById(vmId); + } - @Override - public VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool) { - // 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!"); - } + @Override + public VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool) { + // 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!"); + } - VMInstanceVO vm = _vmInstanceDao.findById(vmId); - if (vm == null) { - throw new InvalidParameterValueException( - "Unable to find the VM by id=" + vmId); - } + VMInstanceVO vm = _vmInstanceDao.findById(vmId); + if (vm == null) { + throw new InvalidParameterValueException( + "Unable to find the VM by id=" + vmId); + } - if (vm.getState() != State.Stopped) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "VM is not Stopped, unable to migrate the vm having the specified id"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } + if (vm.getState() != State.Stopped) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "VM is not Stopped, unable to migrate the vm having the specified id"); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } - if (vm.getType() != VirtualMachine.Type.User) { - throw new InvalidParameterValueException( - "can only do storage migration on user vm"); - } + if (vm.getType() != VirtualMachine.Type.User) { + throw new InvalidParameterValueException( + "can only do storage migration on user vm"); + } - List vols = _volsDao.findByInstance(vm.getId()); - if (vols.size() > 1) { - throw new InvalidParameterValueException( - "Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); - } + List vols = _volsDao.findByInstance(vm.getId()); + if (vols.size() > 1) { + throw new InvalidParameterValueException( + "Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); + } - HypervisorType destHypervisorType = _clusterDao.findById( - destPool.getClusterId()).getHypervisorType(); - if (vm.getHypervisorType() != destHypervisorType) { - throw new InvalidParameterValueException( - "hypervisor is not compatible: dest: " - + destHypervisorType.toString() + ", vm: " - + vm.getHypervisorType().toString()); - } - VMInstanceVO migratedVm = _itMgr.storageMigration(vm, destPool); - return migratedVm; + HypervisorType destHypervisorType = _clusterDao.findById( + destPool.getClusterId()).getHypervisorType(); + if (vm.getHypervisorType() != destHypervisorType) { + throw new InvalidParameterValueException( + "hypervisor is not compatible: dest: " + + destHypervisorType.toString() + ", vm: " + + vm.getHypervisorType().toString()); + } + VMInstanceVO migratedVm = _itMgr.storageMigration(vm, destPool); + return migratedVm; - } + } - private boolean isVMUsingLocalStorage(VMInstanceVO vm) { - boolean usesLocalStorage = false; - ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vm - .getServiceOfferingId()); - if (svcOffering.getUseLocalStorage()) { - usesLocalStorage = true; - } else { - List volumes = _volsDao.findByInstanceAndType(vm.getId(), - Volume.Type.DATADISK); - for (VolumeVO vol : volumes) { - DiskOfferingVO diskOffering = _diskOfferingDao.findById(vol - .getDiskOfferingId()); - if (diskOffering.getUseLocalStorage()) { - usesLocalStorage = true; - break; - } - } - } - return usesLocalStorage; - } + private boolean isVMUsingLocalStorage(VMInstanceVO vm) { + boolean usesLocalStorage = false; + ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vm + .getServiceOfferingId()); + if (svcOffering.getUseLocalStorage()) { + usesLocalStorage = true; + } else { + List volumes = _volsDao.findByInstanceAndType(vm.getId(), + Volume.Type.DATADISK); + for (VolumeVO vol : volumes) { + DiskOfferingVO diskOffering = _diskOfferingDao.findById(vol + .getDiskOfferingId()); + if (diskOffering.getUseLocalStorage()) { + usesLocalStorage = true; + break; + } + } + } + return usesLocalStorage; + } - @Override - @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true) - public VirtualMachine migrateVirtualMachine(Long vmId, 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!"); - } + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true) + public VirtualMachine migrateVirtualMachine(Long vmId, 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!"); + } - VMInstanceVO vm = _vmInstanceDao.findById(vmId); - if (vm == null) { - throw new InvalidParameterValueException( - "Unable to find the VM by id=" + vmId); - } - // business logic - if (vm.getState() != State.Running) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM is not Running, unable to migrate the vm " - + vm); - } - InvalidParameterValueException ex = new InvalidParameterValueException( - "VM is not Running, unable to migrate the vm with specified id"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) - && !vm.getHypervisorType().equals(HypervisorType.VMware) - && !vm.getHypervisorType().equals(HypervisorType.KVM) - && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug(vm - + " is not XenServer/VMware/KVM/Ovm, cannot migrate this VM."); - } - throw new InvalidParameterValueException( - "Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM only"); - } + VMInstanceVO vm = _vmInstanceDao.findById(vmId); + if (vm == null) { + throw new InvalidParameterValueException( + "Unable to find the VM by id=" + vmId); + } + // business logic + if (vm.getState() != State.Running) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("VM is not Running, unable to migrate the vm " + + vm); + } + InvalidParameterValueException ex = new InvalidParameterValueException( + "VM is not Running, unable to migrate the vm with specified id"); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) + && !vm.getHypervisorType().equals(HypervisorType.VMware) + && !vm.getHypervisorType().equals(HypervisorType.KVM) + && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug(vm + + " is not XenServer/VMware/KVM/Ovm, cannot migrate this VM."); + } + throw new InvalidParameterValueException( + "Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM only"); + } - if (isVMUsingLocalStorage(vm)) { - 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"); - } + if (isVMUsingLocalStorage(vm)) { + 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"); + } - // check if migrating to same host - long srcHostId = vm.getHostId(); - if (destinationHost.getId() == srcHostId) { - throw new InvalidParameterValueException( - "Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM"); - } + // check if migrating to same host + long srcHostId = vm.getHostId(); + if (destinationHost.getId() == srcHostId) { + throw new InvalidParameterValueException( + "Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM"); + } - // check if host is UP - if (destinationHost.getStatus() != com.cloud.host.Status.Up - || destinationHost.getResourceState() != ResourceState.Enabled) { - throw new InvalidParameterValueException( - "Cannot migrate VM, destination host is not in correct state, has status: " - + destinationHost.getStatus() + ", state: " - + destinationHost.getResourceState()); - } + // check if host is UP + if (destinationHost.getStatus() != com.cloud.host.Status.Up + || destinationHost.getResourceState() != ResourceState.Enabled) { + throw new InvalidParameterValueException( + "Cannot migrate VM, destination host is not in correct state, has status: " + + destinationHost.getStatus() + ", state: " + + destinationHost.getResourceState()); + } - // call to core process - DataCenterVO dcVO = _dcDao.findById(destinationHost.getDataCenterId()); - HostPodVO pod = _podDao.findById(destinationHost.getPodId()); - Cluster cluster = _clusterDao.findById(destinationHost.getClusterId()); - DeployDestination dest = new DeployDestination(dcVO, pod, cluster, - destinationHost); + // call to core process + DataCenterVO dcVO = _dcDao.findById(destinationHost.getDataCenterId()); + HostPodVO pod = _podDao.findById(destinationHost.getPodId()); + Cluster cluster = _clusterDao.findById(destinationHost.getClusterId()); + DeployDestination dest = new DeployDestination(dcVO, pod, cluster, + destinationHost); - // check max guest vm limit for the destinationHost - HostVO destinationHostVO = _hostDao.findById(destinationHost.getId()); - if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Host name: " - + destinationHost.getName() - + ", hostId: " - + destinationHost.getId() - + " already has max Running VMs(count includes system VMs), cannot migrate to this host"); - } - throw new VirtualMachineMigrationException( - "Destination host, hostId: " - + destinationHost.getId() - + " already has max Running VMs(count includes system VMs), cannot migrate to this host"); - } + // check max guest vm limit for the destinationHost + HostVO destinationHostVO = _hostDao.findById(destinationHost.getId()); + if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Host name: " + + destinationHost.getName() + + ", hostId: " + + destinationHost.getId() + + " already has max Running VMs(count includes system VMs), cannot migrate to this host"); + } + throw new VirtualMachineMigrationException( + "Destination host, hostId: " + + destinationHost.getId() + + " already has max Running VMs(count includes system VMs), cannot migrate to this host"); + } - VMInstanceVO migratedVm = _itMgr.migrate(vm, srcHostId, dest); - return migratedVm; - } + VMInstanceVO migratedVm = _itMgr.migrate(vm, srcHostId, dest); + return migratedVm; + } - @DB - @Override - @ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false) - public UserVm moveVMToUser(AssignVMCmd cmd) - throws ResourceAllocationException, ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - // VERIFICATIONS and VALIDATIONS + @DB + @Override + @ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false) + public UserVm moveVMToUser(AssignVMCmd cmd) + throws ResourceAllocationException, ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException { + // VERIFICATIONS and VALIDATIONS - // VV 1: verify the two users - Account caller = UserContext.current().getCaller(); - if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN - && caller.getType() != Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { // only - // root - // admin - // can - // assign - // VMs - throw new InvalidParameterValueException( - "Only domain admins are allowed to assign VMs and not " - + caller.getType()); - } + // VV 1: verify the two users + Account caller = UserContext.current().getCaller(); + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN + && caller.getType() != Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { // only + // root + // admin + // can + // assign + // VMs + throw new InvalidParameterValueException( + "Only domain admins are allowed to assign VMs and not " + + caller.getType()); + } - // get and check the valid VM - UserVmVO vm = _vmDao.findById(cmd.getVmId()); - if (vm == null) { - throw new InvalidParameterValueException( - "There is no vm by that id " + cmd.getVmId()); - } else if (vm.getState() == State.Running) { // VV 3: check if vm is - // running - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM is Running, unable to move the vm " + vm); - } - InvalidParameterValueException ex = new InvalidParameterValueException( - "VM is Running, unable to move the vm with specified vmId"); - ex.addProxyObject(vm, cmd.getVmId(), "vmId"); - throw ex; - } + // get and check the valid VM + UserVmVO vm = _vmDao.findById(cmd.getVmId()); + if (vm == null) { + throw new InvalidParameterValueException( + "There is no vm by that id " + cmd.getVmId()); + } else if (vm.getState() == State.Running) { // VV 3: check if vm is + // running + if (s_logger.isDebugEnabled()) { + s_logger.debug("VM is Running, unable to move the vm " + vm); + } + InvalidParameterValueException ex = new InvalidParameterValueException( + "VM is Running, unable to move the vm with specified vmId"); + ex.addProxyObject(vm, cmd.getVmId(), "vmId"); + throw ex; + } - Account oldAccount = _accountService.getActiveAccountById(vm - .getAccountId()); - if (oldAccount == null) { - throw new InvalidParameterValueException("Invalid account for VM " - + vm.getAccountId() + " in domain."); - } - // don't allow to move the vm from the project - if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Specified Vm id belongs to the project and can't be moved"); - ex.addProxyObject(vm, cmd.getVmId(), "vmId"); - throw ex; - } - Account newAccount = _accountService.getActiveAccountByName( - cmd.getAccountName(), cmd.getDomainId()); - if (newAccount == null - || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Invalid accountid=" - + cmd.getAccountName() + " in domain " + cmd.getDomainId()); - } + Account oldAccount = _accountService.getActiveAccountById(vm + .getAccountId()); + if (oldAccount == null) { + throw new InvalidParameterValueException("Invalid account for VM " + + vm.getAccountId() + " in domain."); + } + // don't allow to move the vm from the project + if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Specified Vm id belongs to the project and can't be moved"); + ex.addProxyObject(vm, cmd.getVmId(), "vmId"); + throw ex; + } + Account newAccount = _accountService.getActiveAccountByName( + cmd.getAccountName(), cmd.getDomainId()); + if (newAccount == null + || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { + throw new InvalidParameterValueException("Invalid accountid=" + + cmd.getAccountName() + " in domain " + cmd.getDomainId()); + } - if (newAccount.getState() == Account.State.disabled) { - throw new InvalidParameterValueException("The new account owner " - + cmd.getAccountName() + " is disabled."); - } + if (newAccount.getState() == Account.State.disabled) { + throw new InvalidParameterValueException("The new account owner " + + cmd.getAccountName() + " is disabled."); + } - // make sure the accounts are under same domain - if (oldAccount.getDomainId() != newAccount.getDomainId()) { - throw new InvalidParameterValueException( - "The account should be under same domain for moving VM between two accounts. Old owner domain =" - + oldAccount.getDomainId() - + " New owner domain=" - + newAccount.getDomainId()); - } + // make sure the accounts are under same domain + if (oldAccount.getDomainId() != newAccount.getDomainId()) { + throw new InvalidParameterValueException( + "The account should be under same domain for moving VM between two accounts. Old owner domain =" + + oldAccount.getDomainId() + + " New owner domain=" + + newAccount.getDomainId()); + } - // make sure the accounts are not same - if (oldAccount.getAccountId() == newAccount.getAccountId()) { - throw new InvalidParameterValueException( - "The account should be same domain for moving VM between two accounts. Account id =" - + oldAccount.getAccountId()); - } + // make sure the accounts are not same + if (oldAccount.getAccountId() == newAccount.getAccountId()) { + throw new InvalidParameterValueException( + "The account should be same domain for moving VM between two accounts. Account id =" + + oldAccount.getAccountId()); + } - // don't allow to move the vm if there are existing PF/LB/Static Nat - // rules, or vm is assigned to static Nat ip - List pfrules = _portForwardingDao.listByVm(cmd - .getVmId()); - if (pfrules != null && pfrules.size() > 0) { - throw new InvalidParameterValueException( - "Remove the Port forwarding rules for this VM before assigning to another user."); - } - List snrules = _rulesDao - .listStaticNatByVmId(vm.getId()); - if (snrules != null && snrules.size() > 0) { - throw new InvalidParameterValueException( - "Remove the StaticNat rules for this VM before assigning to another user."); - } - List maps = _loadBalancerVMMapDao - .listByInstanceId(vm.getId()); - if (maps != null && maps.size() > 0) { - throw new InvalidParameterValueException( - "Remove the load balancing rules for this VM before assigning to another user."); - } - // check for one on one nat - IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(cmd.getVmId()); - if (ip != null) { - if (ip.isOneToOneNat()) { - throw new InvalidParameterValueException( - "Remove the one to one nat rule for this VM for ip " - + ip.toString()); - } - } + // don't allow to move the vm if there are existing PF/LB/Static Nat + // rules, or vm is assigned to static Nat ip + List pfrules = _portForwardingDao.listByVm(cmd + .getVmId()); + if (pfrules != null && pfrules.size() > 0) { + throw new InvalidParameterValueException( + "Remove the Port forwarding rules for this VM before assigning to another user."); + } + List snrules = _rulesDao + .listStaticNatByVmId(vm.getId()); + if (snrules != null && snrules.size() > 0) { + throw new InvalidParameterValueException( + "Remove the StaticNat rules for this VM before assigning to another user."); + } + List maps = _loadBalancerVMMapDao + .listByInstanceId(vm.getId()); + if (maps != null && maps.size() > 0) { + throw new InvalidParameterValueException( + "Remove the load balancing rules for this VM before assigning to another user."); + } + // check for one on one nat + IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(cmd.getVmId()); + if (ip != null) { + if (ip.isOneToOneNat()) { + throw new InvalidParameterValueException( + "Remove the one to one nat rule for this VM for ip " + + ip.toString()); + } + } - DataCenterVO zone = _dcDao.findById(vm.getDataCenterIdToDeployIn()); + DataCenterVO zone = _dcDao.findById(vm.getDataCenterIdToDeployIn()); - // Remove vm from instance group - removeInstanceFromInstanceGroup(cmd.getVmId()); + // Remove vm from instance group + removeInstanceFromInstanceGroup(cmd.getVmId()); - // VV 2: check if account/domain is with in resource limits to create a - // new vm - _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.user_vm); + // VV 2: check if account/domain is with in resource limits to create a + // new vm + _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.user_vm); - // VV 3: check if volumes are with in resource limits - _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, - _volsDao.findByInstance(cmd.getVmId()).size()); + // VV 3: check if volumes are with in resource limits + _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, + _volsDao.findByInstance(cmd.getVmId()).size()); - // VV 4: Check if new owner can use the vm template - VirtualMachineTemplate template = _templateDao.findById(vm - .getTemplateId()); - if (!template.isPublicTemplate()) { - Account templateOwner = _accountMgr.getAccount(template - .getAccountId()); - _accountMgr.checkAccess(newAccount, null, true, templateOwner); - } + // VV 4: Check if new owner can use the vm template + VirtualMachineTemplate template = _templateDao.findById(vm + .getTemplateId()); + if (!template.isPublicTemplate()) { + Account templateOwner = _accountMgr.getAccount(template + .getAccountId()); + _accountMgr.checkAccess(newAccount, null, true, templateOwner); + } - // VV 5: check the new account can create vm in the domain - DomainVO domain = _domainDao.findById(cmd.getDomainId()); - _accountMgr.checkAccess(newAccount, domain); + // VV 5: check the new account can create vm in the domain + DomainVO domain = _domainDao.findById(cmd.getDomainId()); + _accountMgr.checkAccess(newAccount, domain); - Transaction txn = Transaction.currentTxn(); - txn.start(); - // generate destroy vm event for usage - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm - .getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm - .getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), - vm.getHypervisorType().toString())); - // update resource counts - _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), - ResourceType.user_vm); + Transaction txn = Transaction.currentTxn(); + txn.start(); + // generate destroy vm event for usage + _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm + .getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm + .getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), + vm.getHypervisorType().toString())); + // update resource counts + _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), + ResourceType.user_vm); - // OWNERSHIP STEP 1: update the vm owner - vm.setAccountId(newAccount.getAccountId()); - vm.setDomainId(cmd.getDomainId()); - _vmDao.persist(vm); + // OWNERSHIP STEP 1: update the vm owner + vm.setAccountId(newAccount.getAccountId()); + vm.setDomainId(cmd.getDomainId()); + _vmDao.persist(vm); - // OS 2: update volume - List volumes = _volsDao.findByInstance(cmd.getVmId()); - for (VolumeVO volume : volumes) { - _usageEventDao - .persist(new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, - volume.getAccountId(), volume.getDataCenterId(), - volume.getId(), volume.getName())); - _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), - ResourceType.volume); - volume.setAccountId(newAccount.getAccountId()); - _volsDao.persist(volume); - _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), - ResourceType.volume); - _usageEventDao.persist(new UsageEventVO( - EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), - volume.getDataCenterId(), volume.getId(), volume.getName(), - volume.getDiskOfferingId(), volume.getTemplateId(), volume - .getSize())); - // snapshots: mark these removed in db - List snapshots = _snapshotDao - .listByVolumeIdIncludingRemoved(volume.getId()); - for (SnapshotVO snapshot : snapshots) { - _snapshotDao.remove(snapshot.getId()); - } - } + // OS 2: update volume + List volumes = _volsDao.findByInstance(cmd.getVmId()); + for (VolumeVO volume : volumes) { + _usageEventDao + .persist(new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, + volume.getAccountId(), volume.getDataCenterId(), + volume.getId(), volume.getName())); + _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), + ResourceType.volume); + volume.setAccountId(newAccount.getAccountId()); + _volsDao.persist(volume); + _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), + ResourceType.volume); + _usageEventDao.persist(new UsageEventVO( + EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), + volume.getDiskOfferingId(), volume.getTemplateId(), volume + .getSize())); + // snapshots: mark these removed in db + List snapshots = _snapshotDao + .listByVolumeIdIncludingRemoved(volume.getId()); + for (SnapshotVO snapshot : snapshots) { + _snapshotDao.remove(snapshot.getId()); + } + } - _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), - ResourceType.user_vm); - // generate usage events to account for this change - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm - .getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm - .getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), - vm.getHypervisorType().toString())); + _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), + ResourceType.user_vm); + // generate usage events to account for this change + _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm + .getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm + .getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), + vm.getHypervisorType().toString())); - txn.commit(); + txn.commit(); - VMInstanceVO vmoi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); - VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl( - vmoi); + VMInstanceVO vmoi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); + VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl( + vmoi); - // OS 3: update the network - List networkIdList = cmd.getNetworkIds(); - List securityGroupIdList = cmd.getSecurityGroupIdList(); + // OS 3: update the network + List networkIdList = cmd.getNetworkIds(); + List securityGroupIdList = cmd.getSecurityGroupIdList(); - if (zone.getNetworkType() == NetworkType.Basic) { - if (networkIdList != null && !networkIdList.isEmpty()) { - throw new InvalidParameterValueException( - "Can't move vm with network Ids; this is a basic zone VM"); - } - // cleanup the old security groups - _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); - // cleanup the network for the oldOwner - _networkMgr.cleanupNics(vmOldProfile); - _networkMgr.expungeNics(vmOldProfile); - // security groups will be recreated for the new account, when the - // VM is started - List networkList = new ArrayList(); + if (zone.getNetworkType() == NetworkType.Basic) { + if (networkIdList != null && !networkIdList.isEmpty()) { + throw new InvalidParameterValueException( + "Can't move vm with network Ids; this is a basic zone VM"); + } + // cleanup the old security groups + _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); + // cleanup the network for the oldOwner + _networkMgr.cleanupNics(vmOldProfile); + _networkMgr.expungeNics(vmOldProfile); + // security groups will be recreated for the new account, when the + // VM is started + List networkList = new ArrayList(); - // Get default guest network in Basic zone - Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone - .getId()); + // Get default guest network in Basic zone + Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone + .getId()); - if (defaultNetwork == null) { - throw new InvalidParameterValueException( - "Unable to find a default network to start a vm"); - } else { - networkList.add(_networkDao.findById(defaultNetwork.getId())); - } + if (defaultNetwork == null) { + throw new InvalidParameterValueException( + "Unable to find a default network to start a vm"); + } else { + networkList.add(_networkDao.findById(defaultNetwork.getId())); + } - boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware); + boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware); - if (securityGroupIdList != null && isVmWare) { - throw new InvalidParameterValueException( - "Security group feature is not supported for vmWare hypervisor"); - } else if (!isVmWare - && _networkMgr - .isSecurityGroupSupportedInNetwork(defaultNetwork) - && _networkMgr.canAddDefaultSecurityGroup()) { - if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList(); - } - SecurityGroup defaultGroup = _securityGroupMgr - .getDefaultSecurityGroup(newAccount.getId()); - if (defaultGroup != null) { - // check if security group id list already contains Default - // security group, and if not - add it - boolean defaultGroupPresent = false; - for (Long securityGroupId : securityGroupIdList) { - if (securityGroupId.longValue() == defaultGroup.getId()) { - defaultGroupPresent = true; - break; - } - } + if (securityGroupIdList != null && isVmWare) { + throw new InvalidParameterValueException( + "Security group feature is not supported for vmWare hypervisor"); + } else if (!isVmWare + && _networkMgr + .isSecurityGroupSupportedInNetwork(defaultNetwork) + && _networkMgr.canAddDefaultSecurityGroup()) { + if (securityGroupIdList == null) { + securityGroupIdList = new ArrayList(); + } + SecurityGroup defaultGroup = _securityGroupMgr + .getDefaultSecurityGroup(newAccount.getId()); + if (defaultGroup != null) { + // check if security group id list already contains Default + // security group, and if not - add it + boolean defaultGroupPresent = false; + for (Long securityGroupId : securityGroupIdList) { + if (securityGroupId.longValue() == defaultGroup.getId()) { + defaultGroupPresent = true; + break; + } + } - if (!defaultGroupPresent) { - securityGroupIdList.add(defaultGroup.getId()); - } + if (!defaultGroupPresent) { + securityGroupIdList.add(defaultGroup.getId()); + } - } else { - // create default security group for the account - if (s_logger.isDebugEnabled()) { - s_logger.debug("Couldn't find default security group for the account " - + newAccount + " so creating a new one"); - } - defaultGroup = _securityGroupMgr.createSecurityGroup( - SecurityGroupManager.DEFAULT_GROUP_NAME, - SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, - newAccount.getDomainId(), newAccount.getId(), - newAccount.getAccountName()); - securityGroupIdList.add(defaultGroup.getId()); - } - } + } else { + // create default security group for the account + if (s_logger.isDebugEnabled()) { + s_logger.debug("Couldn't find default security group for the account " + + newAccount + " so creating a new one"); + } + defaultGroup = _securityGroupMgr.createSecurityGroup( + SecurityGroupManager.DEFAULT_GROUP_NAME, + SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, + newAccount.getDomainId(), newAccount.getId(), + newAccount.getAccountName()); + securityGroupIdList.add(defaultGroup.getId()); + } + } - List> networks = new ArrayList>(); - NicProfile profile = new NicProfile(); - profile.setDefaultNic(true); - networks.add(new Pair(networkList.get(0), - profile)); + List> networks = new ArrayList>(); + NicProfile profile = new NicProfile(); + profile.setDefaultNic(true); + networks.add(new Pair(networkList.get(0), + profile)); - VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl( - vmi); - _networkMgr.allocate(vmProfile, networks); + VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); + VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl( + vmi); + _networkMgr.allocate(vmProfile, networks); - _securityGroupMgr.addInstanceToGroups(vm.getId(), - securityGroupIdList); + _securityGroupMgr.addInstanceToGroups(vm.getId(), + securityGroupIdList); - s_logger.debug("AssignVM: Basic zone, adding security groups no " - + securityGroupIdList.size() + " to " - + vm.getInstanceName()); - } else { - if (zone.isSecurityGroupEnabled()) { - throw new InvalidParameterValueException( - "Not yet implemented for SecurityGroupEnabled advanced networks."); - } else { - if (securityGroupIdList != null - && !securityGroupIdList.isEmpty()) { - throw new InvalidParameterValueException( - "Can't move vm with security groups; security group feature is not enabled in this zone"); - } - // cleanup the network for the oldOwner - _networkMgr.cleanupNics(vmOldProfile); - _networkMgr.expungeNics(vmOldProfile); + s_logger.debug("AssignVM: Basic zone, adding security groups no " + + securityGroupIdList.size() + " to " + + vm.getInstanceName()); + } else { + if (zone.isSecurityGroupEnabled()) { + throw new InvalidParameterValueException( + "Not yet implemented for SecurityGroupEnabled advanced networks."); + } else { + if (securityGroupIdList != null + && !securityGroupIdList.isEmpty()) { + throw new InvalidParameterValueException( + "Can't move vm with security groups; security group feature is not enabled in this zone"); + } + // cleanup the network for the oldOwner + _networkMgr.cleanupNics(vmOldProfile); + _networkMgr.expungeNics(vmOldProfile); - Set applicableNetworks = new HashSet(); + Set applicableNetworks = new HashSet(); - if (networkIdList != null && !networkIdList.isEmpty()) { - // add any additional networks - for (Long networkId : networkIdList) { - NetworkVO network = _networkDao.findById(networkId); - if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Unable to find specified network id"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; - } + if (networkIdList != null && !networkIdList.isEmpty()) { + // add any additional networks + for (Long networkId : networkIdList) { + NetworkVO network = _networkDao.findById(networkId); + if (network == null) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Unable to find specified network id"); + ex.addProxyObject(network, networkId, "networkId"); + throw ex; + } - _networkMgr - .checkNetworkPermissions(newAccount, network); + _networkMgr + .checkNetworkPermissions(newAccount, network); - // don't allow to use system networks - NetworkOffering networkOffering = _configMgr - .getNetworkOffering(network - .getNetworkOfferingId()); - if (networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Specified Network id is system only and can't be used for vm deployment"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; - } - applicableNetworks.add(network); - } - } else { - NetworkVO defaultNetwork = null; - List requiredOfferings = _networkOfferingDao - .listByAvailability(Availability.Required, false); - if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException( - "Unable to find network offering with availability=" - + Availability.Required - + " to automatically create the network as a part of vm creation"); - } - if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { - // get Virtual networks + // don't allow to use system networks + NetworkOffering networkOffering = _configMgr + .getNetworkOffering(network + .getNetworkOfferingId()); + if (networkOffering.isSystemOnly()) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Specified Network id is system only and can't be used for vm deployment"); + ex.addProxyObject(network, networkId, "networkId"); + throw ex; + } + applicableNetworks.add(network); + } + } else { + NetworkVO defaultNetwork = null; + List requiredOfferings = _networkOfferingDao + .listByAvailability(Availability.Required, false); + if (requiredOfferings.size() < 1) { + throw new InvalidParameterValueException( + "Unable to find network offering with availability=" + + Availability.Required + + " to automatically create the network as a part of vm creation"); + } + if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { + // get Virtual networks List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated); - if (virtualNetworks.isEmpty()) { - long physicalNetworkId = _networkMgr - .findPhysicalNetworkId(zone.getId(), - requiredOfferings.get(0).getTags(), - requiredOfferings.get(0) - .getTrafficType()); - // Validate physical network - PhysicalNetwork physicalNetwork = _physicalNetworkDao - .findById(physicalNetworkId); - if (physicalNetwork == null) { + if (virtualNetworks.isEmpty()) { + long physicalNetworkId = _networkMgr + .findPhysicalNetworkId(zone.getId(), + requiredOfferings.get(0).getTags(), + requiredOfferings.get(0) + .getTrafficType()); + // Validate physical network + PhysicalNetwork physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); + if (physicalNetwork == null) { throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags()); } s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of deployVM process"); + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); - } else if (virtualNetworks.size() > 1) { - throw new InvalidParameterValueException( - "More than 1 default Isolated networks are found " - + "for account " + newAccount - + "; please specify networkIds"); - } else { + } else if (virtualNetworks.size() > 1) { + throw new InvalidParameterValueException( + "More than 1 default Isolated networks are found " + + "for account " + newAccount + + "; please specify networkIds"); + } else { defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); - } - } else { - throw new InvalidParameterValueException( - "Required network offering id=" - + requiredOfferings.get(0).getId() - + " is not in " - + NetworkOffering.State.Enabled); - } + } + } else { + throw new InvalidParameterValueException( + "Required network offering id=" + + requiredOfferings.get(0).getId() + + " is not in " + + NetworkOffering.State.Enabled); + } - applicableNetworks.add(defaultNetwork); - } + applicableNetworks.add(defaultNetwork); + } - // add the new nics - List> networks = new ArrayList>(); - int toggle = 0; - for (NetworkVO appNet : applicableNetworks) { - NicProfile defaultNic = new NicProfile(); - if (toggle == 0) { - defaultNic.setDefaultNic(true); - toggle++; - } - networks.add(new Pair(appNet, - defaultNic)); - } - VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), - vm.getId()); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl( - vmi); - _networkMgr.allocate(vmProfile, networks); - s_logger.debug("AssignVM: Advance virtual, adding networks no " - + networks.size() + " to " + vm.getInstanceName()); - } // END IF NON SEC GRP ENABLED - } // END IF ADVANCED - s_logger.info("AssignVM: vm " + vm.getInstanceName() - + " now belongs to account " + cmd.getAccountName()); - return vm; - } + // add the new nics + List> networks = new ArrayList>(); + int toggle = 0; + for (NetworkVO appNet : applicableNetworks) { + NicProfile defaultNic = new NicProfile(); + if (toggle == 0) { + defaultNic.setDefaultNic(true); + toggle++; + } + networks.add(new Pair(appNet, + defaultNic)); + } + VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), + vm.getId()); + VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl( + vmi); + _networkMgr.allocate(vmProfile, networks); + s_logger.debug("AssignVM: Advance virtual, adding networks no " + + networks.size() + " to " + vm.getInstanceName()); + } // END IF NON SEC GRP ENABLED + } // END IF ADVANCED + s_logger.info("AssignVM: vm " + vm.getInstanceName() + + " now belongs to account " + cmd.getAccountName()); + return vm; + } - @Override - public UserVm restoreVM(RestoreVMCmd cmd) { - // Input validation - Account caller = UserContext.current().getCaller(); - Long userId = UserContext.current().getCallerUserId(); - UserVO user = _userDao.findById(userId); - boolean needRestart = false; + @Override + public UserVm restoreVM(RestoreVMCmd cmd) { + // Input validation + Account caller = UserContext.current().getCaller(); + Long userId = UserContext.current().getCallerUserId(); + UserVO user = _userDao.findById(userId); + boolean needRestart = false; - long vmId = cmd.getVmId(); - UserVmVO vm = _vmDao.findById(vmId); - if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Cann not find VM with ID " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } + long vmId = cmd.getVmId(); + UserVmVO vm = _vmDao.findById(vmId); + if (vm == null) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Cann not find VM with ID " + vmId); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } - Account owner = _accountDao.findById(vm.getAccountId()); - if (owner == null) { - throw new InvalidParameterValueException("The owner of " + vm - + " does not exist: " + vm.getAccountId()); - } + Account owner = _accountDao.findById(vm.getAccountId()); + if (owner == null) { + throw new InvalidParameterValueException("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()); - } + if (owner.getState() == Account.State.disabled) { + throw new PermissionDeniedException("The owner of " + vm + + " is disabled: " + vm.getAccountId()); + } - if (vm.getState() != VirtualMachine.State.Running - && vm.getState() != VirtualMachine.State.Stopped) { - throw new CloudRuntimeException( - "Vm " - + vmId - + " currently in " - + vm.getState() - + " state, restore vm can only execute when VM in Running or Stopped"); - } + if (vm.getState() != VirtualMachine.State.Running + && vm.getState() != VirtualMachine.State.Stopped) { + throw new CloudRuntimeException( + "Vm " + + vmId + + " currently in " + + vm.getState() + + " state, restore vm can only execute when VM in Running or Stopped"); + } - if (vm.getState() == VirtualMachine.State.Running) { - needRestart = true; - } + if (vm.getState() == VirtualMachine.State.Running) { + needRestart = true; + } - List rootVols = _volsDao.findByInstance(vmId); - if (rootVols.isEmpty()) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Can not find root volume for VM " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } + List rootVols = _volsDao.findByInstance(vmId); + if (rootVols.isEmpty()) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Can not find root volume for VM " + vmId); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } - VolumeVO root = rootVols.get(0); - long templateId = root.getTemplateId(); - VMTemplateVO template = _templateDao.findById(templateId); - if (template == null) { - InvalidParameterValueException ex = new InvalidParameterValueException( - "Cannot find template for specified volumeid and vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - ex.addProxyObject(root, root.getId(), "volumeId"); - throw ex; - } + VolumeVO root = rootVols.get(0); + long templateId = root.getTemplateId(); + VMTemplateVO template = _templateDao.findById(templateId); + if (template == null) { + InvalidParameterValueException ex = new InvalidParameterValueException( + "Cannot find template for specified volumeid and vmId"); + ex.addProxyObject(vm, vmId, "vmId"); + ex.addProxyObject(root, root.getId(), "volumeId"); + throw ex; + } - if (needRestart) { - try { - _itMgr.stop(vm, user, caller); - } catch (ResourceUnavailableException e) { - s_logger.debug("Stop vm " + vmId + " failed", e); - CloudRuntimeException ex = new CloudRuntimeException( - "Stop vm failed for specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } - } + if (needRestart) { + try { + _itMgr.stop(vm, user, caller); + } catch (ResourceUnavailableException e) { + s_logger.debug("Stop vm " + vmId + " failed", e); + CloudRuntimeException ex = new CloudRuntimeException( + "Stop vm failed for specified vmId"); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } + } - /* allocate a new volume from original template */ - VolumeVO newVol = _storageMgr.allocateDuplicateVolume(root, null); - _volsDao.attachVolume(newVol.getId(), vmId, newVol.getDeviceId()); + /* allocate a new volume from original template */ + VolumeVO newVol = _storageMgr.allocateDuplicateVolume(root, null); + _volsDao.attachVolume(newVol.getId(), vmId, newVol.getDeviceId()); - /* Detach and destory the old root volume */ - try { - _volsDao.detachVolume(root.getId()); - _storageMgr.destroyVolume(root); - } catch (ConcurrentOperationException e) { - s_logger.debug("Unable to delete old root volume " + root.getId() - + ", user may manually delete it", e); - } + /* Detach and destory the old root volume */ + try { + _volsDao.detachVolume(root.getId()); + _storageMgr.destroyVolume(root); + } catch (ConcurrentOperationException e) { + s_logger.debug("Unable to delete old root volume " + root.getId() + + ", user may manually delete it", e); + } - if (needRestart) { - try { - _itMgr.start(vm, null, user, caller); - } catch (Exception e) { - s_logger.debug("Unable to start VM " + vmId, e); - CloudRuntimeException ex = new CloudRuntimeException( - "Unable to start VM with specified id" + e.getMessage()); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; - } - } + if (needRestart) { + try { + _itMgr.start(vm, null, user, caller); + } catch (Exception e) { + s_logger.debug("Unable to start VM " + vmId, e); + CloudRuntimeException ex = new CloudRuntimeException( + "Unable to start VM with specified id" + e.getMessage()); + ex.addProxyObject(vm, vmId, "vmId"); + throw ex; + } + } - s_logger.debug("Restore VM " + vmId + " with template " - + root.getTemplateId() + " successfully"); - return vm; - } + s_logger.debug("Restore VM " + vmId + " with template " + + root.getTemplateId() + " successfully"); + return vm; + } - @Override - public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, - ReservationContext context, DeployDestination dest) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - // not supported - throw new UnsupportedOperationException( - "Plug nic is not supported for vm of type " + vm.getType()); - } + @Override + public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, + ReservationContext context, DeployDestination dest) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + // not supported + throw new UnsupportedOperationException( + "Plug nic is not supported for vm of type " + vm.getType()); + } - @Override - public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, - ReservationContext context, DeployDestination dest) - throws ConcurrentOperationException, ResourceUnavailableException { - // not supported - throw new UnsupportedOperationException( - "Unplug nic is not supported for vm of type " + vm.getType()); - } + @Override + public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, + ReservationContext context, DeployDestination dest) + throws ConcurrentOperationException, ResourceUnavailableException { + // not supported + throw new UnsupportedOperationException( + "Unplug nic is not supported for vm of type " + vm.getType()); + } - @Override - public void prepareStop(VirtualMachineProfile profile) { - } + @Override + public void prepareStop(VirtualMachineProfile profile) { + } } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 3a55751bd72..db8a088fe57 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -156,6 +156,7 @@ DROP TABLE IF EXISTS `cloud`.`autoscale_vmprofiles`; DROP TABLE IF EXISTS `cloud`.`autoscale_policies`; DROP TABLE IF EXISTS `cloud`.`counter`; DROP TABLE IF EXISTS `cloud`.`conditions`; +DROP TABLE IF EXISTS `cloud`.`inline_load_balancer_nic_map`; CREATE TABLE `cloud`.`version` ( `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', diff --git a/utils/src/com/cloud/utils/StringUtils.java b/utils/src/com/cloud/utils/StringUtils.java index e840310c6a7..8f0a503abef 100644 --- a/utils/src/com/cloud/utils/StringUtils.java +++ b/utils/src/com/cloud/utils/StringUtils.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.utils; -import static java.util.Arrays.*; +import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.Iterator; @@ -151,4 +151,17 @@ public class StringUtils { } + public static int formatForOutput(String text, int start, int columns, char separator) { + if (start >= text.length()) { + return -1; + } + + int end = start + columns; + if (end > text.length()) { + end = text.length(); + } + String searchable = text.substring(start, end); + int found = searchable.lastIndexOf(separator); + return found > 0 ? found : end - start; + } }