merge compiles

This commit is contained in:
Alex Huang 2013-01-09 04:41:27 -08:00
parent 7f3a748d6c
commit 14bd345f1f
30 changed files with 5902 additions and 5829 deletions

View File

@ -430,21 +430,6 @@
'${db.cloud.password}';</sqlCommand> '${db.cloud.password}';</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>grant-user-cloud-usage-all</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<username>root</username>
<password>${db.root.password}</password>
<url>jdbc:mysql://${db.cloud.host}:${db.cloud.port}</url>
<sqlCommand>GRANT ALL ON cloud_usage.* to
${db.cloud.username}@`%` identified by
'${db.cloud.password}';</sqlCommand>
</configuration>
</execution>
<execution> <execution>
<id>grant-user-cloud-bridge</id> <id>grant-user-cloud-bridge</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
@ -507,9 +492,9 @@
</goals> </goals>
<configuration> <configuration>
<autocommit>true</autocommit> <autocommit>true</autocommit>
<srcFiles> <srcFiles>
<srcFile>${basedir}/developer-prefill.sql</srcFile> <srcFile>${basedir}/developer-prefill.sql</srcFile>
</srcFiles> </srcFiles>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -518,56 +503,58 @@
</build> </build>
</profile> </profile>
<!-- Simulator profile --> <!-- Simulator profile -->
<profile> <profile>
<id>simulator</id> <id>simulator</id>
<activation> <activation>
<property><name>deploydb-simulator</name></property> <property>
</activation> <name>deploydb-simulator</name>
<build> </property>
<plugins> </activation>
<plugin> <build>
<groupId>org.codehaus.mojo</groupId> <plugins>
<artifactId>properties-maven-plugin</artifactId> <plugin>
<version>1.0-alpha-2</version> <groupId>org.codehaus.mojo</groupId>
<executions> <artifactId>properties-maven-plugin</artifactId>
<execution> <version>1.0-alpha-2</version>
<phase>initialize</phase> <executions>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${project.parent.basedir}/utils/conf/db.properties</file>
<file>${project.parent.basedir}/utils/conf/db.properties.override</file>
</files>
<quiet>true</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${cs.mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<driver>org.gjt.mm.mysql.Driver</driver>
<url>jdbc:mysql://${db.simulator.host}:3306/simulator</url>
<username>${db.simulator.username}</username>
<password>${db.simulator.password}</password>
<skip>${maven.test.skip}</skip>
<forceMojoExecution>true</forceMojoExecution>
</configuration>
<executions>
<execution> <execution>
<id>drop-database</id> <phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${project.parent.basedir}/utils/conf/db.properties</file>
<file>${project.parent.basedir}/utils/conf/db.properties.override</file>
</files>
<quiet>true</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${cs.mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<driver>org.gjt.mm.mysql.Driver</driver>
<url>jdbc:mysql://${db.simulator.host}:3306/simulator</url>
<username>${db.simulator.username}</username>
<password>${db.simulator.password}</password>
<skip>${maven.test.skip}</skip>
<forceMojoExecution>true</forceMojoExecution>
</configuration>
<executions>
<execution>
<id>drop-database</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
@ -575,12 +562,12 @@
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>drop database if exists `simulator`</sqlCommand> <sqlCommand>drop database if exists `simulator`</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>create-database</id> <id>create-database</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
@ -588,51 +575,51 @@
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>create database `simulator`</sqlCommand> <sqlCommand>create database `simulator`</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>grant-user-cloud</id> <id>grant-user-cloud</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to <sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`localhost` identified by ${db.simulator.username}@`localhost` identified by
'${db.simulator.password}';</sqlCommand> '${db.simulator.password}';</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>grant-user-cloud-all</id> <id>grant-user-cloud-all</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to <sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`%` identified by ${db.simulator.username}@`%` identified by
'${db.simulator.password}';</sqlCommand> '${db.simulator.password}';</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>create-schema</id> <id>create-schema</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<srcFiles> <srcFiles>
<srcFile>${basedir}/target/db/create-schema-simulator.sql</srcFile> <srcFile>${basedir}/target/db/create-schema-simulator.sql</srcFile>
<srcFile>${basedir}/target/db/templates.simulator.sql</srcFile> <srcFile>${basedir}/target/db/templates.simulator.sql</srcFile>
</srcFiles> </srcFiles>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>

View File

@ -20,6 +20,11 @@
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-utils</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.cloudstack</groupId> <groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-api</artifactId> <artifactId>cloud-api</artifactId>

View File

@ -21,8 +21,6 @@ package org.apache.cloudstack.engine.service.api;
import java.util.List; import java.util.List;
import java.util.Map; 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.ClusterEntity;
import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity; import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity;
import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity;
@ -42,10 +40,8 @@ public interface ProvisioningService {
StorageEntity registerStorage(String name, List<String> tags, Map<String, String> details); StorageEntity registerStorage(String name, List<String> tags, Map<String, String> details);
@POST
ZoneEntity registerZone(String zoneUuid, String name, String owner, List<String> tags, Map<String, String> details); ZoneEntity registerZone(String zoneUuid, String name, String owner, List<String> tags, Map<String, String> details);
@POST
PodEntity registerPod(String podUuid, String name, String owner, String zoneUuid, List<String> tags, Map<String, String> details); PodEntity registerPod(String podUuid, String name, String owner, String zoneUuid, List<String> tags, Map<String, String> details);
ClusterEntity registerCluster(String clusterUuid, String name, String owner, List<String> tags, Map<String, String> details); ClusterEntity registerCluster(String clusterUuid, String name, String owner, List<String> tags, Map<String, String> details);

View File

@ -501,60 +501,66 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject<State, Virt
this.serviceOfferingId = serviceOfferingId; this.serviceOfferingId = serviceOfferingId;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public int getSpeed() { public int getSpeed() {
return speed; return speed;
} }
public void setSpeed(int speed) { public void setSpeed(int speed) {
this.speed = speed; this.speed = speed;
} }
public List<String> getComputeTags() { public List<String> getComputeTags() {
return computeTags; return computeTags;
} }
public void setComputeTags(List<String> computeTags) { public void setComputeTags(List<String> computeTags) {
this.computeTags = computeTags; this.computeTags = computeTags;
} }
public List<String> getRootDiskTags() { public List<String> getRootDiskTags() {
return rootDiskTags; return rootDiskTags;
} }
public void setRootDiskTags(List<String> rootDiskTags) { public void setRootDiskTags(List<String> rootDiskTags) {
this.rootDiskTags = rootDiskTags; this.rootDiskTags = rootDiskTags;
} }
public String getHostname() { public String getHostname() {
return hostname; return hostname;
} }
public void setHostname(String hostname) { public void setHostname(String hostname) {
this.hostname = hostname; this.hostname = hostname;
} }
public String getDisplayname() { public String getDisplayname() {
return displayname; return displayname;
} }
public void setDisplayname(String displayname) { public void setDisplayname(String displayname) {
this.displayname = displayname; this.displayname = displayname;
} }
public List<String> getNetworkIds() { public List<String> getNetworkIds() {
return networkIds; return networkIds;
} }
public void setNetworkIds(List<String> networkIds) { public void setNetworkIds(List<String> networkIds) {
this.networkIds = networkIds; this.networkIds = networkIds;
} }
@Override
public long getDiskOfferingId() {
// TODO Auto-generated method stub
return 0;
}
} }

View File

@ -26,14 +26,14 @@ import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; 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;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; 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.hypervisor.Hypervisor.HypervisorType;
import com.cloud.org.Cluster; import com.cloud.org.Cluster;
import com.cloud.org.Managed.ManagedState;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
import com.cloud.org.Managed.ManagedState;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.StateMachine; import com.cloud.utils.db.StateMachine;
@ -104,56 +104,63 @@ public class ClusterVO implements Cluster, Identity {
public ClusterVO() { public ClusterVO() {
clusterType = Cluster.ClusterType.CloudManaged; clusterType = Cluster.ClusterType.CloudManaged;
allocationState = Grouping.AllocationState.Enabled; allocationState = Grouping.AllocationState.Enabled;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled; this.state = State.Disabled;
} }
public ClusterVO(long dataCenterId, long podId, String name) { public ClusterVO(long dataCenterId, long podId, String name) {
this.dataCenterId = dataCenterId; this.dataCenterId = dataCenterId;
this.podId = podId; this.podId = podId;
this.name = name; this.name = name;
this.clusterType = Cluster.ClusterType.CloudManaged; this.clusterType = Cluster.ClusterType.CloudManaged;
this.allocationState = Grouping.AllocationState.Enabled; this.allocationState = Grouping.AllocationState.Enabled;
this.managedState = ManagedState.Managed; this.managedState = ManagedState.Managed;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled; this.state = State.Disabled;
} }
@Override
public long getId() { public long getId() {
return id; return id;
} }
@Override
public String getName() { public String getName() {
return name; return name;
} }
@Override
public long getDataCenterId() { public long getDataCenterId() {
return dataCenterId; return dataCenterId;
} }
@Override
public long getPodId() { public long getPodId() {
return podId; return podId;
} }
@Override
public Cluster.ClusterType getClusterType() { public Cluster.ClusterType getClusterType() {
return clusterType; return clusterType;
} }
public void setClusterType(Cluster.ClusterType clusterType) { public void setClusterType(Cluster.ClusterType clusterType) {
this.clusterType = clusterType; this.clusterType = clusterType;
} }
@Override
public AllocationState getAllocationState() { public AllocationState getAllocationState() {
return allocationState; return allocationState;
} }
public void setAllocationState(AllocationState allocationState) { public void setAllocationState(AllocationState allocationState) {
this.allocationState = allocationState; this.allocationState = allocationState;
} }
@Override
public ManagedState getManagedState() { public ManagedState getManagedState() {
return managedState; return managedState;
} }
@ -180,12 +187,13 @@ public class ClusterVO implements Cluster, Identity {
return this.id == that.id; return this.id == that.id;
} }
@Override
public HypervisorType getHypervisorType() { public HypervisorType getHypervisorType() {
return HypervisorType.getType(hypervisorType); return HypervisorType.getType(hypervisorType);
} }
public void setHypervisorType(String hy) { public void setHypervisorType(String hy) {
hypervisorType = hy; hypervisorType = hy;
} }
public String getGuid() { public String getGuid() {
@ -206,30 +214,30 @@ public class ClusterVO implements Cluster, Identity {
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public Date getCreated() { public Date getCreated() {
return created; return created;
} }
public Date getLastUpdated() { public Date getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public State getState() { public State getState() {
return state; return state;
} }
} }

View File

@ -29,10 +29,10 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; 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;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event;
import com.cloud.api.Identity;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
@ -49,8 +49,8 @@ public class DataCenterVO implements DataCenter, Identity {
@Column(name="id") @Column(name="id")
private long id; private long id;
@Column(name="name") @Column(name="name")
private String name = null; private String name = null;
@Column(name="description") @Column(name="description")
private String description = null; private String description = null;
@ -108,8 +108,8 @@ public class DataCenterVO implements DataCenter, Identity {
@TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1) @TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1)
private long macAddress = 1; private long macAddress = 1;
@Column(name="zone_token") @Column(name="zone_token")
private String zoneToken; private String zoneToken;
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name=GenericDao.REMOVED_COLUMN)
private Date removed; private Date removed;
@ -124,8 +124,8 @@ public class DataCenterVO implements DataCenter, Identity {
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
AllocationState allocationState; AllocationState allocationState;
@Column(name="uuid") @Column(name="uuid")
private String uuid; private String uuid;
@Column(name="is_security_group_enabled") @Column(name="is_security_group_enabled")
boolean securityGroupEnabled; boolean securityGroupEnabled;
@ -205,7 +205,7 @@ public class DataCenterVO implements DataCenter, Identity {
this.id = id; this.id = id;
this.allocationState = Grouping.AllocationState.Enabled; this.allocationState = Grouping.AllocationState.Enabled;
this.uuid = UUID.randomUUID().toString(); 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) { 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; this.name = name;
@ -264,22 +264,22 @@ public class DataCenterVO implements DataCenter, Identity {
@Override @Override
public String getGuestNetworkCidr() public String getGuestNetworkCidr()
{ {
return guestNetworkCidr; return guestNetworkCidr;
} }
public void setGuestNetworkCidr(String guestNetworkCidr) public void setGuestNetworkCidr(String guestNetworkCidr)
{ {
this.guestNetworkCidr = guestNetworkCidr; this.guestNetworkCidr = guestNetworkCidr;
} }
@Override @Override
public Long getDomainId() { public Long getDomainId() {
return domainId; return domainId;
} }
public void setDomainId(Long domainId) { public void setDomainId(Long domainId) {
this.domainId = domainId; this.domainId = domainId;
} }
@Override @Override
public String getDescription() { public String getDescription() {
@ -310,38 +310,38 @@ public class DataCenterVO implements DataCenter, Identity {
return internalDns2; return internalDns2;
} }
protected DataCenterVO() { protected DataCenterVO() {
} }
@Override @Override
public long getId() { public long getId() {
return id; return id;
} }
@Override @Override
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public void setDns1(String dns1) { public void setDns1(String dns1) {
this.dns1 = dns1; this.dns1 = dns1;
} }
public void setDns2(String dns2) { public void setDns2(String dns2) {
this.dns2 = dns2; this.dns2 = dns2;
} }
public void setInternalDns1(String dns3) { public void setInternalDns1(String dns3) {
this.internalDns1 = dns3; this.internalDns1 = dns3;
} }
public void setInternalDns2(String dns4) { public void setInternalDns2(String dns4) {
this.internalDns2 = dns4; this.internalDns2 = dns4;
} }
public void setRouterMacAddress(String routerMacAddress) { public void setRouterMacAddress(String routerMacAddress) {
this.routerMacAddress = routerMacAddress; this.routerMacAddress = routerMacAddress;
@ -405,12 +405,13 @@ public class DataCenterVO implements DataCenter, Identity {
details.put(name, value); details.put(name, value);
} }
@Override
public AllocationState getAllocationState() { public AllocationState getAllocationState() {
return allocationState; return allocationState;
} }
public void setAllocationState(AllocationState allocationState) { public void setAllocationState(AllocationState allocationState) {
this.allocationState = allocationState; this.allocationState = allocationState;
} }
@Override @Override
@ -429,25 +430,25 @@ public class DataCenterVO implements DataCenter, Identity {
@Override @Override
public String getZoneToken() { public String getZoneToken() {
return zoneToken; return zoneToken;
} }
public void setZoneToken(String zoneToken) { public void setZoneToken(String zoneToken) {
this.zoneToken = zoneToken; this.zoneToken = zoneToken;
} }
public Date getRemoved() { public Date getRemoved() {
return removed; return removed;
} }
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public long getMacAddress() { public long getMacAddress() {
return macAddress; return macAddress;
@ -457,23 +458,23 @@ public class DataCenterVO implements DataCenter, Identity {
this.macAddress = macAddress; this.macAddress = macAddress;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public Date getCreated() { public Date getCreated() {
return created; return created;
} }
public Date getLastUpdated() { public Date getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public State getState() { public State getState() {
return state; return state;
} }
} }

View File

@ -26,10 +26,10 @@ import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; 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;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event;
import com.cloud.api.Identity;
import com.cloud.dc.Pod; import com.cloud.dc.Pod;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
@ -39,40 +39,40 @@ import com.cloud.utils.db.StateMachine;
@Entity @Entity
@Table(name = "host_pod_ref") @Table(name = "host_pod_ref")
public class HostPodVO implements Pod, Identity { public class HostPodVO implements Pod, Identity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
long id; long id;
@Column(name = "name") @Column(name = "name")
private String name = null; private String name = null;
@Column(name = "data_center_id") @Column(name = "data_center_id")
private long dataCenterId; private long dataCenterId;
@Column(name = "gateway") @Column(name = "gateway")
private String gateway; private String gateway;
@Column(name = "cidr_address") @Column(name = "cidr_address")
private String cidrAddress; private String cidrAddress;
@Column(name = "cidr_size") @Column(name = "cidr_size")
private int cidrSize; private int cidrSize;
@Column(name = "description") @Column(name = "description")
private String description; private String description;
@Column(name="allocation_state") @Column(name="allocation_state")
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
AllocationState allocationState; AllocationState allocationState;
@Column(name = "external_dhcp") @Column(name = "external_dhcp")
private Boolean externalDhcp; private Boolean externalDhcp;
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name=GenericDao.REMOVED_COLUMN)
private Date removed; private Date removed;
@Column(name = "uuid") @Column(name = "uuid")
private String uuid; private String uuid;
//orchestration //orchestration
@Column(name="owner") @Column(name="owner")
@ -95,116 +95,121 @@ public class HostPodVO implements Pod, Identity {
@Column(name="state", updatable=true, nullable=false, length=32) @Column(name="state", updatable=true, nullable=false, length=32)
protected State state = null; protected State state = null;
public HostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { public HostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) {
this.name = name; this.name = name;
this.dataCenterId = dcId; this.dataCenterId = dcId;
this.gateway = gateway; this.gateway = gateway;
this.cidrAddress = cidrAddress; this.cidrAddress = cidrAddress;
this.cidrSize = cidrSize; this.cidrSize = cidrSize;
this.description = description; this.description = description;
this.allocationState = Grouping.AllocationState.Enabled; this.allocationState = Grouping.AllocationState.Enabled;
this.externalDhcp = false; this.externalDhcp = false;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled; this.state = State.Disabled;
} }
/* /*
* public HostPodVO(String name, long dcId) { this(null, name, dcId); } * public HostPodVO(String name, long dcId) { this(null, name, dcId); }
*/ */
protected HostPodVO() { protected HostPodVO() {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
} }
@Override @Override
public long getId() { public long getId() {
return id; return id;
} }
public long getDataCenterId() { @Override
return dataCenterId; public long getDataCenterId() {
} return dataCenterId;
}
public void setDataCenterId(long dataCenterId) { public void setDataCenterId(long dataCenterId) {
this.dataCenterId = dataCenterId; this.dataCenterId = dataCenterId;
} }
public String getName() { @Override
return name; public String getName() {
} return name;
}
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String getCidrAddress() { public String getCidrAddress() {
return cidrAddress; return cidrAddress;
} }
public void setCidrAddress(String cidrAddress) { public void setCidrAddress(String cidrAddress) {
this.cidrAddress = cidrAddress; this.cidrAddress = cidrAddress;
} }
@Override @Override
public int getCidrSize() { public int getCidrSize() {
return cidrSize; return cidrSize;
} }
public void setCidrSize(int cidrSize) { public void setCidrSize(int cidrSize) {
this.cidrSize = cidrSize; this.cidrSize = cidrSize;
} }
@Override @Override
public String getGateway() { public String getGateway() {
return gateway; return gateway;
} }
public void setGateway(String gateway) { public void setGateway(String gateway) {
this.gateway = gateway; this.gateway = gateway;
} }
public String getDescription() { @Override
return description; public String getDescription() {
} return description;
}
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
@Override
public AllocationState getAllocationState() { public AllocationState getAllocationState() {
return allocationState; return allocationState;
} }
public void setAllocationState(AllocationState allocationState) { public void setAllocationState(AllocationState allocationState) {
this.allocationState = allocationState; this.allocationState = allocationState;
} }
// Use for comparisons only. // Use for comparisons only.
public HostPodVO(Long id) { public HostPodVO(Long id) {
this.id = id; this.id = id;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return NumbersUtil.hash(id); return NumbersUtil.hash(id);
} }
public boolean getExternalDhcp() { @Override
return externalDhcp; public boolean getExternalDhcp() {
} return externalDhcp;
}
public void setExternalDhcp(boolean use) { public void setExternalDhcp(boolean use) {
externalDhcp = use; externalDhcp = use;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof HostPodVO) { if (obj instanceof HostPodVO) {
return id == ((HostPodVO)obj).id; return id == ((HostPodVO)obj).id;
} else { } else {
return false; return false;
} }
} }
public Date getRemoved() { public Date getRemoved() {
return removed; return removed;
@ -212,30 +217,30 @@ public class HostPodVO implements Pod, Identity {
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public Date getCreated() { public Date getCreated() {
return created; return created;
} }
public Date getLastUpdated() { public Date getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public State getState() { public State getState() {
return state; return state;
} }
} }

View File

@ -37,10 +37,10 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; 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;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; 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.Host;
import com.cloud.host.Status; import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
@ -719,13 +719,13 @@ public class HostVO implements Host, Identity {
return hypervisorVersion; return hypervisorVersion;
} }
@Override @Override
// TODO, I tempoerary disable it as it breaks GenericSearchBuild when @Transient is applied // TODO, I tempoerary disable it as it breaks GenericSearchBuild when @Transient is applied
// @Transient // @Transient
public Status getState() { public Status getState() {
return status; return status;
} }
@Override @Override
public ResourceState getResourceState() { public ResourceState getResourceState() {
@ -733,7 +733,7 @@ public class HostVO implements Host, Identity {
} }
public void setResourceState(ResourceState state) { public void setResourceState(ResourceState state) {
resourceState = state; resourceState = state;
} }
@Override @Override
@ -743,37 +743,37 @@ public class HostVO implements Host, Identity {
} }
public long getUpdated() { public long getUpdated() {
return updated; return updated;
} }
public long incrUpdated() { public long incrUpdated() {
updated++; updated++;
return updated; return updated;
} }
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public Date getLastUpdated() { public Date getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public State getOrchestrationState() { public State getOrchestrationState() {
return state; return state;
} }
} }

View File

@ -29,14 +29,12 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.inject.Inject;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.storage.image.format.ISO; import org.apache.cloudstack.storage.image.format.ISO;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.api.BaseCmd;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.DomainVO; import com.cloud.domain.DomainVO;
@ -48,9 +46,9 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.storage.Storage; import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.Storage.TemplateType; import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.VMTemplateDaoImpl; import com.cloud.storage.dao.VMTemplateDaoImpl;
import com.cloud.storage.dao.VMTemplateDetailsDao; import com.cloud.storage.dao.VMTemplateDetailsDao;
import com.cloud.storage.dao.VMTemplateZoneDao; 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.template.VirtualMachineTemplate.TemplateFilter;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.Pair; 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.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase; 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.JoinBuilder;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@Component @Component
@ -674,15 +670,17 @@ public class ImageDataDaoImpl extends GenericDaoBase<ImageDataVO, Long> implemen
} }
// for now, defaulting pageSize to a large val if null; may need to // for now, defaulting pageSize to a large val if null; may need to
// revisit post 2.2RC2 // revisit post 2.2RC2
if (isIso && templateZonePairList.size() < (pageSize != null ? pageSize : 500) && templateFilter != TemplateFilter.community if (isIso &&
&& !(templateFilter == TemplateFilter.self && !BaseCmd.isRootAdmin(caller.getType()))) { // evaluates templateZonePairList.size() < (pageSize != null ? pageSize : 500) &&
// to templateFilter != TemplateFilter.community &&
// true !(templateFilter == TemplateFilter.self) /* TODO: Fix this! && !BaseCmd.isRootAdmin(caller.getType())*/) { // evaluates
// If // to
// root // true
// admin // If
// and // root
// filter=self // admin
// and
// filter=self
List<ImageDataVO> publicIsos = publicIsoSearch(bootable, false, tags); List<ImageDataVO> publicIsos = publicIsoSearch(bootable, false, tags);
List<ImageDataVO> userIsos = userIsoSearch(false); List<ImageDataVO> userIsos = userIsoSearch(false);
@ -855,6 +853,7 @@ public class ImageDataDaoImpl extends GenericDaoBase<ImageDataVO, Long> implemen
} }
} }
@Override
public ImageDataVO findSystemVMTemplate(long zoneId, HypervisorType hType) { public ImageDataVO findSystemVMTemplate(long zoneId, HypervisorType hType) {
SearchCriteria<ImageDataVO> sc = tmpltTypeHyperSearch.create(); SearchCriteria<ImageDataVO> sc = tmpltTypeHyperSearch.create();
sc.setParameters("templateType", Storage.TemplateType.SYSTEM); sc.setParameters("templateType", Storage.TemplateType.SYSTEM);

View File

@ -33,11 +33,12 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import com.cloud.api.Identity; import org.apache.cloudstack.api.Identity;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.Storage; import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Storage.TemplateType; import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateVO;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
@Entity @Entity
@ -77,7 +78,7 @@ public class ImageDataVO implements Identity {
@Temporal(value = TemporalType.TIMESTAMP) @Temporal(value = TemporalType.TIMESTAMP)
@Column(name = GenericDao.CREATED_COLUMN) @Column(name = GenericDao.CREATED_COLUMN)
private Date created = null; private final Date created = null;
@Column(name = GenericDao.REMOVED) @Column(name = GenericDao.REMOVED)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)

View File

@ -32,11 +32,11 @@ import javax.persistence.TableGenerator;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.engine.subsystem.api.storage.disktype.Unknown; 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.Storage.StoragePoolType;
import com.cloud.storage.Volume;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
import com.cloud.utils.fsm.StateObject; import com.cloud.utils.fsm.StateObject;
@ -124,9 +124,9 @@ public class VolumeVO implements Identity, StateObject<Volume.State> {
@Column(name = "update_count", updatable = true, nullable = false) @Column(name = "update_count", updatable = true, nullable = false)
protected long updatedCount; // This field should be updated everytime the protected long updatedCount; // This field should be updated everytime the
// state is updated. There's no set method in // state is updated. There's no set method in
// the vo object because it is done with in the // the vo object because it is done with in the
// dao code. // dao code.
@Column(name = "recreatable") @Column(name = "recreatable")
boolean recreatable; boolean recreatable;
@ -345,6 +345,7 @@ public class VolumeVO implements Identity, StateObject<Volume.State> {
return updated; return updated;
} }
@Override
public Volume.State getState() { public Volume.State getState() {
return state; return state;
} }

View File

@ -19,7 +19,6 @@
package org.apache.cloudstack.storage.datastore.db; package org.apache.cloudstack.storage.datastore.db;
import java.util.Date; import java.util.Date;
import java.util.UUID;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -30,12 +29,10 @@ import javax.persistence.Table;
import javax.persistence.TableGenerator; import javax.persistence.TableGenerator;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.storage.datastore.DataStoreStatus; import org.apache.cloudstack.storage.datastore.DataStoreStatus;
import com.cloud.api.Identity;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
@Entity @Entity
@ -118,6 +115,7 @@ public class PrimaryDataStoreVO implements Identity {
return name; return name;
} }
@Override
public String getUuid() { public String getUuid() {
return uuid; return uuid;
} }
@ -239,11 +237,11 @@ public class PrimaryDataStoreVO implements Identity {
} }
public void setKey(String key) { public void setKey(String key) {
this.key = key; this.key = key;
} }
public String getKey() { public String getKey() {
return this.key; return this.key;
} }
@Override @Override

View File

@ -21,22 +21,23 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; 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.ejb.Local;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.APIAccessChecker;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.User; import com.cloud.user.User;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject; import com.cloud.utils.component.Inject;
import com.cloud.utils.component.PluggableService; import com.cloud.utils.component.PluggableService;
@ -60,6 +61,7 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
private static List<String> s_allCommands = null; private static List<String> s_allCommands = null;
protected @Inject AccountManager _accountMgr; protected @Inject AccountManager _accountMgr;
@Inject protected List<PluggableService> _services;
protected StaticRoleBasedAPIAccessChecker() { protected StaticRoleBasedAPIAccessChecker() {
super(); super();
@ -77,10 +79,10 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
boolean commandExists = s_allCommands.contains(apiCommandName); boolean commandExists = s_allCommands.contains(apiCommandName);
if(commandExists && user != null){ if(commandExists && user != null){
Long accountId = user.getAccountId(); Long accountId = user.getAccountId();
Account userAccount = _accountMgr.getAccount(accountId); Account userAccount = _accountMgr.getAccount(accountId);
short accountType = userAccount.getType(); short accountType = userAccount.getType();
return isCommandAvailableForAccount(accountType, apiCommandName); return isCommandAvailableForAccount(accountType, apiCommandName);
} }
return commandExists; return commandExists;
@ -109,13 +111,8 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params); super.configure(name, params);
// Read command properties files to build the static map per role.
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
List<PluggableService> services = locator.getAllPluggableServices();
services.add((PluggableService) ComponentLocator.getComponent(ManagementServer.Name));
List<String> configFiles = new ArrayList<String>(); List<String> configFiles = new ArrayList<String>();
for (PluggableService service : services) { for (PluggableService service : _services) {
configFiles.addAll(Arrays.asList(service.getPropertiesFiles())); configFiles.addAll(Arrays.asList(service.getPropertiesFiles()));
} }

View File

@ -30,10 +30,11 @@ import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult; import javax.naming.directory.SearchResult;
import org.apache.cloudstack.api.ApiConstants.LDAPParams;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64; 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.configuration.dao.ConfigurationDao;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
@ -81,7 +82,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
String protocol = "ldap://" ; String protocol = "ldap://" ;
if (new Boolean(useSSL)){ if (new Boolean(useSSL)){
env.put(Context.SECURITY_PROTOCOL, "ssl"); env.put(Context.SECURITY_PROTOCOL, "ssl");
protocol="ldaps://" ; protocol="ldaps://" ;
System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStore", trustStore);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
@ -93,10 +94,10 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.SECURITY_CREDENTIALS, bindPasswd); env.put(Context.SECURITY_CREDENTIALS, bindPasswd);
} }
else { else {
// Use anonymous authentication // Use anonymous authentication
env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.SECURITY_AUTHENTICATION, "none");
} }
// Create the initial context // Create the initial context
DirContext ctx = new InitialDirContext(env); DirContext ctx = new InitialDirContext(env);
// use this context to search // use this context to search
@ -115,7 +116,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
// Search for objects with those matching attributes // Search for objects with those matching attributes
NamingEnumeration<SearchResult> answer = ctx.search(searchBase, queryFilter, sc); NamingEnumeration<SearchResult> answer = ctx.search(searchBase, queryFilter, sc);
SearchResult sr = (SearchResult)answer.next(); SearchResult sr = answer.next();
String cn = sr.getName(); String cn = sr.getName();
answer.close(); answer.close();
ctx.close(); ctx.close();
@ -127,7 +128,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
protocol = "ldap://" ; protocol = "ldap://" ;
if (new Boolean(useSSL)){ if (new Boolean(useSSL)){
env.put(Context.SECURITY_PROTOCOL, "ssl"); env.put(Context.SECURITY_PROTOCOL, "ssl");
protocol="ldaps://" ; protocol="ldaps://" ;
} }
env.put(Context.PROVIDER_URL, protocol + url + ":" + port); env.put(Context.PROVIDER_URL, protocol + url + ":" + port);
@ -143,7 +144,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return false; return false;
} }
catch (Exception e){ catch (Exception e){
e.printStackTrace(); e.printStackTrace();
s_logger.warn("Unknown error encountered " + e.getMessage()); s_logger.warn("Unknown error encountered " + e.getMessage());
return false; return false;
} }
@ -152,6 +153,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return true; return true;
} }
@Override
public boolean configure(String name, Map<String, Object> params) public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException { throws ConfigurationException {
super.configure(name, params); super.configure(name, params);
@ -161,16 +163,16 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return true; return true;
} }
@Override @Override
public String encode(String password) { public String encode(String password) {
// Password is not used, so set to a random string // Password is not used, so set to a random string
try { try {
SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
byte bytes[] = new byte[20]; byte bytes[] = new byte[20];
randomGen.nextBytes(bytes); randomGen.nextBytes(bytes);
return Base64.encode(bytes).toString(); return Base64.encode(bytes).toString();
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Failed to generate random password",e); throw new CloudRuntimeException("Failed to generate random password",e);
} }
} }
} }

View File

@ -85,6 +85,11 @@
<artifactId>reflections</artifactId> <artifactId>reflections</artifactId>
<version>0.9.8</version> <version>0.9.8</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-engine-api</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<defaultGoal>install</defaultGoal> <defaultGoal>install</defaultGoal>

View File

@ -52,16 +52,29 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.apache.cloudstack.acl.APIAccessChecker; import org.apache.cloudstack.acl.APIAccessChecker;
import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.*; 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.ListAccountsCmd;
import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; 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.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.vm.ListVMsCmd;
import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; 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.commons.codec.binary.Base64;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException; import org.apache.http.HttpException;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
@ -69,6 +82,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.HttpServerConnection; import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection; 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.ResponseDate;
import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.ResponseServer;
import org.apache.log4j.Logger; 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 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.AsyncJob;
import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO; import com.cloud.async.AsyncJobVO;
@ -123,18 +128,15 @@ import com.cloud.user.UserAccount;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.StringUtils; import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.utils.exception.CSExceptionErrorCode;
import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDao;
import org.reflections.Reflections;
public class ApiServer implements HttpRequestHandler { public class ApiServer implements HttpRequestHandler {
private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName()); private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName());
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + 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"; public static String jsonContentType = "text/javascript";
private ApiDispatcher _dispatcher; private ApiDispatcher _dispatcher;
@Inject private AccountManager _accountMgr = null; @Inject private final AccountManager _accountMgr = null;
@Inject private DomainManager _domainMgr = null; @Inject private final DomainManager _domainMgr = null;
@Inject private AsyncJobManager _asyncMgr = null; @Inject private final AsyncJobManager _asyncMgr = null;
@Inject(adapter = APIAccessChecker.class) @Inject private ConfigurationDao _configDao;
protected Adapters<APIAccessChecker> _apiAccessCheckers; @Inject protected List<APIAccessChecker> _apiAccessCheckers;
private Account _systemAccount = null; private Account _systemAccount = null;
private User _systemUser = null; private User _systemUser = null;
private static int _workerCount = 0; private static int _workerCount = 0;
private static ApiServer s_instance = null; private static ApiServer s_instance = null;
private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>(); private final Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>();
private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer")); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
@ -164,20 +166,13 @@ public class ApiServer implements HttpRequestHandler {
public static void initApiServer(String[] apiConfig) { public static void initApiServer(String[] apiConfig) {
if (s_instance == null) { if (s_instance == null) {
//Injecting will create ApiServer object with all its s_instance = new ApiServer();
//vars injected as well, no need to do the following: s_instance = ComponentContext.inject(s_instance);
//s_instance = new ApiServer();
s_instance = ComponentLocator.inject(ApiServer.class);
s_instance.init(apiConfig); s_instance.init(apiConfig);
} }
} }
public static ApiServer getInstance() { 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; return s_instance;
} }
@ -190,9 +185,7 @@ public class ApiServer implements HttpRequestHandler {
_dispatcher = ApiDispatcher.getInstance(); _dispatcher = ApiDispatcher.getInstance();
Integer apiPort = null; // api port, null by default Integer apiPort = null; // api port, null by default
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); SearchCriteria<ConfigurationVO> sc = _configDao.createSearchCriteria();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
SearchCriteria<ConfigurationVO> sc = configDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port"); sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port");
List<ConfigurationVO> values = _configDao.search(sc, null); List<ConfigurationVO> values = _configDao.search(sc, null);
if ((values != null) && (values.size() > 0)) { if ((values != null) && (values.size() > 0)) {
@ -215,8 +208,8 @@ public class ApiServer implements HttpRequestHandler {
_apiNameCmdClassMap.put(apiName, cmdClass); _apiNameCmdClassMap.put(apiName, cmdClass);
} }
encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key()));
String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key()); String jsonType = _configDao.getValue(Config.JavaScriptDefaultContentType.key());
if (jsonType != null) { if (jsonType != null) {
jsonContentType = jsonType; jsonContentType = jsonType;
} }
@ -357,29 +350,29 @@ public class ApiServer implements HttpRequestHandler {
} }
} catch (Exception ex) { } catch (Exception ex) {
if (ex instanceof InvalidParameterValueException) { if (ex instanceof InvalidParameterValueException) {
InvalidParameterValueException ref = (InvalidParameterValueException)ex; InvalidParameterValueException ref = (InvalidParameterValueException)ex;
ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage());
// copy over the IdentityProxy information as well and throw the serverapiexception. // copy over the IdentityProxy information as well and throw the serverapiexception.
ArrayList<String> idList = ref.getIdProxyList(); ArrayList<String> idList = ref.getIdProxyList();
if (idList != null) { if (idList != null) {
// Iterate through entire arraylist and copy over each proxy id. // Iterate through entire arraylist and copy over each proxy id.
for (int i = 0 ; i < idList.size(); i++) { for (int i = 0 ; i < idList.size(); i++) {
e.addProxyObject(idList.get(i)); e.addProxyObject(idList.get(i));
} }
} }
// Also copy over the cserror code and the function/layer in which it was thrown. // 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; throw e;
} else if (ex instanceof PermissionDeniedException) { } else if (ex instanceof PermissionDeniedException) {
PermissionDeniedException ref = (PermissionDeniedException)ex; PermissionDeniedException ref = (PermissionDeniedException)ex;
ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage()); ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage());
// copy over the IdentityProxy information as well and throw the serverapiexception. // copy over the IdentityProxy information as well and throw the serverapiexception.
ArrayList<String> idList = ref.getIdProxyList(); ArrayList<String> idList = ref.getIdProxyList();
if (idList != null) { if (idList != null) {
// Iterate through entire arraylist and copy over each proxy id. // Iterate through entire arraylist and copy over each proxy id.
for (int i = 0 ; i < idList.size(); i++) { for (int i = 0 ; i < idList.size(); i++) {
e.addProxyObject(idList.get(i)); e.addProxyObject(idList.get(i));
} }
} }
e.setCSErrorCode(ref.getCSErrorCode()); e.setCSErrorCode(ref.getCSErrorCode());
throw e; 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())) { if (response.getObjectId() != null && objectJobMap.containsKey(response.getObjectId())) {
AsyncJob job = objectJobMap.get(response.getObjectId()); AsyncJob job = objectJobMap.get(response.getObjectId());
response.setJobId(job.getUuid()); response.setJobId(job.getUuid());
response.setJobStatus(job.getStatus()); response.setJobStatus(job.getStatus());
}
} }
} }
} }
}
private void buildAuditTrail(StringBuffer auditTrailSb, String command, String result) { private void buildAuditTrail(StringBuffer auditTrailSb, String command, String result) {
if (result == null) { 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 not null, that mean that user is logged in
if (userId != null) { if (userId != null) {
User user = ApiDBUtils.findUserById(userId); User user = ApiDBUtils.findUserById(userId);
if (!isCommandAvailable(user, commandName)) { if (!isCommandAvailable(user, commandName)) {
s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user"); 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"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user");
@ -855,8 +848,8 @@ public class ApiServer implements HttpRequestHandler {
_params = new BasicHttpParams(); _params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor // Set up the HTTP protocol processor
BasicHttpProcessor httpproc = new BasicHttpProcessor(); BasicHttpProcessor httpproc = new BasicHttpProcessor();
@ -968,41 +961,41 @@ public class ApiServer implements HttpRequestHandler {
// Exception. When invoked from ApiServlet's processRequest(), this can be // Exception. When invoked from ApiServlet's processRequest(), this can be
// a standard exception like NumberFormatException. We'll leave the standard ones alone. // a standard exception like NumberFormatException. We'll leave the standard ones alone.
if (ex != null) { if (ex != null) {
if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException
|| ex instanceof InvalidParameterValueException) { || ex instanceof InvalidParameterValueException) {
// Cast the exception appropriately and retrieve the IdentityProxy // Cast the exception appropriately and retrieve the IdentityProxy
if (ex instanceof ServerApiException) { if (ex instanceof ServerApiException) {
ServerApiException ref = (ServerApiException) ex; ServerApiException ref = (ServerApiException) ex;
ArrayList<String> idList = ref.getIdProxyList(); ArrayList<String> idList = ref.getIdProxyList();
if (idList != null) { if (idList != null) {
for (int i=0; i < idList.size(); i++) { for (int i=0; i < idList.size(); i++) {
apiResponse.addProxyObject(idList.get(i)); apiResponse.addProxyObject(idList.get(i));
} }
} }
// Also copy over the cserror code and the function/layer in which it was thrown. // Also copy over the cserror code and the function/layer in which it was thrown.
apiResponse.setCSErrorCode(ref.getCSErrorCode()); apiResponse.setCSErrorCode(ref.getCSErrorCode());
} else if (ex instanceof PermissionDeniedException) { } else if (ex instanceof PermissionDeniedException) {
PermissionDeniedException ref = (PermissionDeniedException) ex; PermissionDeniedException ref = (PermissionDeniedException) ex;
ArrayList<String> idList = ref.getIdProxyList(); ArrayList<String> idList = ref.getIdProxyList();
if (idList != null) { if (idList != null) {
for (int i=0; i < idList.size(); i++) { for (int i=0; i < idList.size(); i++) {
apiResponse.addProxyObject(idList.get(i)); apiResponse.addProxyObject(idList.get(i));
} }
} }
// Also copy over the cserror code and the function/layer in which it was thrown. // Also copy over the cserror code and the function/layer in which it was thrown.
apiResponse.setCSErrorCode(ref.getCSErrorCode()); apiResponse.setCSErrorCode(ref.getCSErrorCode());
} else if (ex instanceof InvalidParameterValueException) { } else if (ex instanceof InvalidParameterValueException) {
InvalidParameterValueException ref = (InvalidParameterValueException) ex; InvalidParameterValueException ref = (InvalidParameterValueException) ex;
ArrayList<String> idList = ref.getIdProxyList(); ArrayList<String> idList = ref.getIdProxyList();
if (idList != null) { if (idList != null) {
for (int i=0; i < idList.size(); i++) { for (int i=0; i < idList.size(); i++) {
apiResponse.addProxyObject(idList.get(i)); apiResponse.addProxyObject(idList.get(i));
} }
} }
// Also copy over the cserror code and the function/layer in which it was thrown. // Also copy over the cserror code and the function/layer in which it was thrown.
apiResponse.setCSErrorCode(ref.getCSErrorCode()); apiResponse.setCSErrorCode(ref.getCSErrorCode());
} }
} }
} }
SerializationContext.current().setUuidTranslation(true); SerializationContext.current().setUuidTranslation(true);
responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType); responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);

View File

@ -27,15 +27,15 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; 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.ListStorageNetworkIpRangeCmd;
import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd;
import com.cloud.dc.HostPodVO; import com.cloud.dc.HostPodVO;
import com.cloud.dc.StorageNetworkIpRange;
import com.cloud.dc.StorageNetworkIpAddressVO; import com.cloud.dc.StorageNetworkIpAddressVO;
import com.cloud.dc.StorageNetworkIpRange;
import com.cloud.dc.StorageNetworkIpRangeVO; import com.cloud.dc.StorageNetworkIpRangeVO;
import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.StorageNetworkIpAddressDao; import com.cloud.dc.dao.StorageNetworkIpAddressDao;
@ -43,12 +43,11 @@ import com.cloud.dc.dao.StorageNetworkIpRangeDao;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkDao;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteriaService; import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.SecondaryStorageVmVO;
@ -56,83 +55,83 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.SecondaryStorageVmDao;
@Component @Component
@Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) @Local(value = { StorageNetworkManager.class, StorageNetworkService.class })
public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService { public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService {
private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class);
String _name; String _name;
@Inject @Inject
StorageNetworkIpAddressDao _sNwIpDao; StorageNetworkIpAddressDao _sNwIpDao;
@Inject @Inject
StorageNetworkIpRangeDao _sNwIpRangeDao; StorageNetworkIpRangeDao _sNwIpRangeDao;
@Inject @Inject
NetworkDao _networkDao; NetworkDao _networkDao;
@Inject @Inject
HostPodDao _podDao; HostPodDao _podDao;
@Inject @Inject
SecondaryStorageVmDao _ssvmDao; SecondaryStorageVmDao _ssvmDao;
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public boolean start() { public boolean start() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return true; return true;
} }
@Override @Override
public boolean stop() { public boolean stop() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return true; return true;
} }
@Override @Override
public String getName() { public String getName() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) {
HostPodVO pod = _podDao.findById(podId); HostPodVO pod = _podDao.findById(podId);
if (pod == null) { if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId); throw new CloudRuntimeException("Cannot find pod " + podId);
} }
String[] IpRange = pod.getDescription().split("-"); String[] IpRange = pod.getDescription().split("-");
if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) {
return; return;
} }
if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { 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]); 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) { private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) {
List<StorageNetworkIpRangeVO> curRanges = _sNwIpRangeDao.listByPodId(podId); List<StorageNetworkIpRangeVO> curRanges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO range : curRanges) { for (StorageNetworkIpRangeVO range : curRanges) {
if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { 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()); 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 createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException {
long startIPLong = NetUtils.ip2Long(startIp); long startIPLong = NetUtils.ip2Long(startIp);
long endIPLong = NetUtils.ip2Long(endIp); 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 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=?"; String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
PreparedStatement stmt = null; PreparedStatement stmt = null;
Connection conn = txn.getConnection(); Connection conn = txn.getConnection();
while (startIPLong <= endIPLong) { while (startIPLong <= endIPLong) {
stmt = conn.prepareStatement(insertSql); stmt = conn.prepareStatement(insertSql);
stmt.setLong(1, rangeId); stmt.setLong(1, rangeId);
stmt.setString(2, NetUtils.long2Ip(startIPLong++)); stmt.setString(2, NetUtils.long2Ip(startIPLong++));
stmt.setLong(3, zoneId); stmt.setLong(3, zoneId);
stmt.setNull(4, java.sql.Types.DATE); stmt.setNull(4, java.sql.Types.DATE);
stmt.executeUpdate(); stmt.executeUpdate();
stmt.close(); stmt.close();
@ -141,244 +140,247 @@ public class StorageNetworkManagerImpl implements StorageNetworkManager, Storage
stmt.executeUpdate(); stmt.executeUpdate();
stmt.close(); stmt.close();
} }
} }
@Override @Override
@DB @DB
public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) { public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) {
Integer vlan = cmd.getVlan(); Integer vlan = cmd.getVlan();
Long rangeId = cmd.getId(); Long rangeId = cmd.getId();
String startIp = cmd.getStartIp(); String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp(); String endIp = cmd.getEndIp();
String netmask = cmd.getNetmask(); String netmask = cmd.getNetmask();
if (netmask != null && !NetUtils.isValidNetmask(netmask)) { if (netmask != null && !NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask); throw new CloudRuntimeException("Invalid netmask:" + netmask);
} }
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId));
} }
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) { if (range == null) {
throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); throw new CloudRuntimeException("Cannot find storage ip range " + rangeId);
} }
if (startIp != null || endIp != null) { if (startIp != null || endIp != null) {
long podId = range.getPodId(); long podId = range.getPodId();
startIp = startIp == null ? range.getStartIp() : startIp; startIp = startIp == null ? range.getStartIp() : startIp;
endIp = endIp == null ? range.getEndIp() : endIp; endIp = endIp == null ? range.getEndIp() : endIp;
checkOverlapPrivateIpRange(podId, startIp, endIp); checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp); checkOverlapStorageIpRange(podId, startIp, endIp);
} }
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
try { try {
range = _sNwIpRangeDao.acquireInLockTable(range.getId()); range = _sNwIpRangeDao.acquireInLockTable(range.getId());
if (range == null) { if (range == null) {
throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId);
} }
StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate();
if (vlan != null) { if (vlan != null) {
vo.setVlan(vlan); vo.setVlan(vlan);
} }
if (startIp != null) { if (startIp != null) {
vo.setStartIp(startIp); vo.setStartIp(startIp);
} }
if (endIp != null) { if (endIp != null) {
vo.setEndIp(endIp); vo.setEndIp(endIp);
} }
if (netmask != null) { if (netmask != null) {
vo.setNetmask(netmask); vo.setNetmask(netmask);
} }
_sNwIpRangeDao.update(rangeId, vo); _sNwIpRangeDao.update(rangeId, vo);
} finally { } finally {
if (range != null) { if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(range.getId()); _sNwIpRangeDao.releaseFromLockTable(range.getId());
} }
} }
txn.commit(); txn.commit();
return _sNwIpRangeDao.findById(rangeId); return _sNwIpRangeDao.findById(rangeId);
} }
@Override @Override
@DB @DB
public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException {
Long podId = cmd.getPodId(); Long podId = cmd.getPodId();
String startIp = cmd.getStartIp(); String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp(); String endIp = cmd.getEndIp();
Integer vlan = cmd.getVlan(); Integer vlan = cmd.getVlan();
String netmask = cmd.getNetmask(); String netmask = cmd.getNetmask();
if (endIp == null) { if (endIp == null) {
endIp = startIp; endIp = startIp;
} }
if (!NetUtils.isValidNetmask(netmask)) { if (!NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask); throw new CloudRuntimeException("Invalid netmask:" + netmask);
} }
HostPodVO pod = _podDao.findById(podId); HostPodVO pod = _podDao.findById(podId);
if (pod == null) { if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId); throw new CloudRuntimeException("Cannot find pod " + podId);
} }
Long zoneId = pod.getDataCenterId(); Long zoneId = pod.getDataCenterId();
List<NetworkVO> nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); List<NetworkVO> nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage);
if (nws.size() == 0) { if (nws.size() == 0) {
throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId);
} }
if (nws.size() > 1) { if (nws.size() > 1) {
throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found");
} }
NetworkVO nw = nws.get(0); NetworkVO nw = nws.get(0);
checkOverlapPrivateIpRange(podId, startIp, endIp); checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp); checkOverlapStorageIpRange(podId, startIp, endIp);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
StorageNetworkIpRangeVO range = null; StorageNetworkIpRangeVO range = null;
txn.start(); txn.start();
range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay());
_sNwIpRangeDao.persist(range); _sNwIpRangeDao.persist(range);
try { try {
createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId);
} catch (SQLException e) { } catch (SQLException e) {
txn.rollback(); txn.rollback();
StringBuilder err = new StringBuilder(); StringBuilder err = new StringBuilder();
err.append("Create storage network range failed."); err.append("Create storage network range failed.");
err.append("startIp=" + startIp); err.append("startIp=" + startIp);
err.append("endIp=" + endIp); err.append("endIp=" + endIp);
err.append("netmask=" + netmask); err.append("netmask=" + netmask);
err.append("zoneId=" + zoneId); err.append("zoneId=" + zoneId);
s_logger.debug(err.toString(), e); s_logger.debug(err.toString(), e);
throw e; throw e;
} }
txn.commit(); txn.commit();
return range; return range;
} }
private String getInUseIpAddress(long rangeId) { private String getInUseIpAddress(long rangeId) {
List<String> ips = _sNwIpDao.listInUseIpByRangeId(rangeId); List<String> ips = _sNwIpDao.listInUseIpByRangeId(rangeId);
StringBuilder res = new StringBuilder(); StringBuilder res = new StringBuilder();
res.append("Below IP of range " + rangeId + " is still in use:"); res.append("Below IP of range " + rangeId + " is still in use:");
for (String ip : ips) { for (String ip : ips) {
res.append(ip).append(","); res.append(ip).append(",");
} }
return res.toString(); return res.toString();
} }
@Override @Override
@DB @DB
public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) { public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) {
long rangeId = cmd.getId(); long rangeId = cmd.getId();
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) { if (range == null) {
throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); throw new CloudRuntimeException("Can not find storage network ip range " + rangeId);
} }
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException(getInUseIpAddress(rangeId)); throw new CloudRuntimeException(getInUseIpAddress(rangeId));
} }
final Transaction txn = Transaction.currentTxn(); final Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
try { try {
range = _sNwIpRangeDao.acquireInLockTable(rangeId); range = _sNwIpRangeDao.acquireInLockTable(rangeId);
if (range == null) { if (range == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed";
s_logger.warn(msg); s_logger.warn(msg);
throw new CloudRuntimeException(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); * entries in op_dc_storage_network_ip_address will be deleted automatically due to
} finally { * fk_storage_ip_address__range_id constraint key
if (range != null) { */
_sNwIpRangeDao.releaseFromLockTable(rangeId); _sNwIpRangeDao.remove(rangeId);
} } finally {
} if (range != null) {
txn.commit(); _sNwIpRangeDao.releaseFromLockTable(rangeId);
} }
}
txn.commit();
}
@Override @Override
public List<StorageNetworkIpRange> listIpRange(ListStorageNetworkIpRangeCmd cmd) { public List<StorageNetworkIpRange> listIpRange(ListStorageNetworkIpRangeCmd cmd) {
Long rangeId = cmd.getRangeId(); Long rangeId = cmd.getRangeId();
Long podId = cmd.getPodId(); Long podId = cmd.getPodId();
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();
List result = null; List result = null;
if (rangeId != null) { if (rangeId != null) {
result = _sNwIpRangeDao.listByRangeId(rangeId); result = _sNwIpRangeDao.listByRangeId(rangeId);
} else if (podId != null) { } else if (podId != null) {
result = _sNwIpRangeDao.listByPodId(podId); result = _sNwIpRangeDao.listByPodId(podId);
} else if (zoneId != null) { } else if (zoneId != null) {
result = _sNwIpRangeDao.listByDataCenterId(zoneId); result = _sNwIpRangeDao.listByDataCenterId(zoneId);
} else { } else {
result = _sNwIpRangeDao.listAll(); result = _sNwIpRangeDao.listAll();
} }
return (List<StorageNetworkIpRange>)result; return result;
} }
@Override @Override
public void releaseIpAddress(String ip) { public void releaseIpAddress(String ip) {
_sNwIpDao.releaseIpAddress(ip); _sNwIpDao.releaseIpAddress(ip);
} }
@Override @Override
public StorageNetworkIpAddressVO acquireIpAddress(long podId) { public StorageNetworkIpAddressVO acquireIpAddress(long podId) {
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByPodId(podId); List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO r : ranges) { for (StorageNetworkIpRangeVO r : ranges) {
try { try {
r = _sNwIpRangeDao.acquireInLockTable(r.getId()); r = _sNwIpRangeDao.acquireInLockTable(r.getId());
if (r == null) { if (r == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed";
s_logger.warn(msg); s_logger.warn(msg);
throw new CloudRuntimeException(msg); throw new CloudRuntimeException(msg);
} }
StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId());
if (ip != null) { if (ip != null) {
return ip; return ip;
} }
} finally { } finally {
if (r != null) { if (r != null) {
_sNwIpRangeDao.releaseFromLockTable(r.getId()); _sNwIpRangeDao.releaseFromLockTable(r.getId());
} }
} }
} }
return null; return null;
} }
@Override @Override
public boolean isStorageIpRangeAvailable(long zoneId) { public boolean isStorageIpRangeAvailable(long zoneId) {
SearchCriteriaService<StorageNetworkIpRangeVO, StorageNetworkIpRangeVO> sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); SearchCriteriaService<StorageNetworkIpRangeVO, StorageNetworkIpRangeVO> sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class);
sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId);
List<StorageNetworkIpRangeVO> entries = sc.list(); List<StorageNetworkIpRangeVO> entries = sc.list();
return entries.size() > 0; return entries.size() > 0;
} }
@Override @Override
public List<SecondaryStorageVmVO> getSSVMWithNoStorageNetwork(long zoneId) { public List<SecondaryStorageVmVO> getSSVMWithNoStorageNetwork(long zoneId) {
List<SecondaryStorageVmVO> ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); List<SecondaryStorageVmVO> ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping);
return ssvms; return ssvms;
} }
@Override @Override
public boolean isAnyStorageIpInUseInZone(long zoneId) { public boolean isAnyStorageIpInUseInZone(long zoneId) {
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByDataCenterId(zoneId);
for (StorageNetworkIpRangeVO r : ranges) { for (StorageNetworkIpRangeVO r : ranges) {
if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@ -22,10 +22,11 @@ import java.util.Random;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import javax.persistence.TableGenerator; import javax.persistence.TableGenerator;
import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.springframework.stereotype.Component;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.GuestType; import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
@ -61,21 +62,21 @@ import com.cloud.utils.net.NetUtils;
@Local(value = NetworkDao.class) @Local(value = NetworkDao.class)
@DB(txn = false) @DB(txn = false)
public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao { public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao {
final SearchBuilder<NetworkVO> AllFieldsSearch; SearchBuilder<NetworkVO> AllFieldsSearch;
final SearchBuilder<NetworkVO> AccountSearch; SearchBuilder<NetworkVO> AccountSearch;
final SearchBuilder<NetworkVO> RelatedConfigSearch; SearchBuilder<NetworkVO> RelatedConfigSearch;
final SearchBuilder<NetworkVO> AccountNetworkSearch; SearchBuilder<NetworkVO> AccountNetworkSearch;
final SearchBuilder<NetworkVO> ZoneBroadcastUriSearch; SearchBuilder<NetworkVO> ZoneBroadcastUriSearch;
final SearchBuilder<NetworkVO> ZoneSecurityGroupSearch; SearchBuilder<NetworkVO> ZoneSecurityGroupSearch;
final GenericSearchBuilder<NetworkVO, Integer> CountBy; GenericSearchBuilder<NetworkVO, Integer> CountBy;
final SearchBuilder<NetworkVO> PhysicalNetworkSearch; SearchBuilder<NetworkVO> PhysicalNetworkSearch;
final SearchBuilder<NetworkVO> SecurityGroupSearch; SearchBuilder<NetworkVO> SecurityGroupSearch;
final GenericSearchBuilder<NetworkVO, Long> NetworksRegularUserCanCreateSearch; GenericSearchBuilder<NetworkVO, Long> NetworksRegularUserCanCreateSearch;
private final GenericSearchBuilder<NetworkVO, Integer> NetworksCount; GenericSearchBuilder<NetworkVO, Integer> NetworksCount;
final SearchBuilder<NetworkVO> SourceNATSearch; SearchBuilder<NetworkVO> SourceNATSearch;
final GenericSearchBuilder<NetworkVO, Long> CountByZoneAndURI; GenericSearchBuilder<NetworkVO, Long> CountByZoneAndURI;
final GenericSearchBuilder<NetworkVO, Long> VpcNetworksCount; GenericSearchBuilder<NetworkVO, Long> VpcNetworksCount;
final SearchBuilder<NetworkVO> OfferingAccountNetworkSearch; SearchBuilder<NetworkVO> OfferingAccountNetworkSearch;
ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class);
@ -85,7 +86,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
NetworkOfferingDaoImpl _ntwkOffDao = ComponentLocator.inject(NetworkOfferingDaoImpl.class); NetworkOfferingDaoImpl _ntwkOffDao = ComponentLocator.inject(NetworkOfferingDaoImpl.class);
final TableGenerator _tgMacAddress; TableGenerator _tgMacAddress;
Random _rand = new Random(System.currentTimeMillis()); Random _rand = new Random(System.currentTimeMillis());
long _prefix = 0x2; long _prefix = 0x2;
@ -549,6 +550,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return findOneBy(sc); return findOneBy(sc);
} }
@Override
@DB @DB
public boolean remove(Long id) { public boolean remove(Long id) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();

View File

@ -35,18 +35,16 @@ import javax.persistence.InheritanceType;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.apache.cloudstack.api.Identity; import com.cloud.network.dao.FirewallRulesCidrsDao;
import com.cloud.network.dao.FirewallRulesCidrsDaoImpl;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import org.apache.cloudstack.api.InternalIdentity;
@Entity @Entity
@Table(name="firewall_rules") @Table(name="firewall_rules")
@Inheritance(strategy=InheritanceType.JOINED) @Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32) @DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32)
public class FirewallRuleVO implements FirewallRule { public class FirewallRuleVO implements FirewallRule {
protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); @Inject protected FirewallRulesCidrsDao _firewallRulesCidrsDao;
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy=GenerationType.IDENTITY)

View File

@ -38,10 +38,10 @@ import javax.mail.URLName;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; 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.ProjectAccountJoinDao;
import com.cloud.api.query.dao.ProjectInvitationJoinDao; import com.cloud.api.query.dao.ProjectInvitationJoinDao;
import com.cloud.api.query.dao.ProjectJoinDao; 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.user.dao.AccountDao;
import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
@ -159,7 +158,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
@Override @Override
public boolean start() { public boolean start() {
_executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS);
return true; return true;
} }
@ -182,7 +181,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
//check if the user authorized to create the project //check if the user authorized to create the project
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && !_allowUserToCreateProject) { 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 //Verify request parameters
@ -320,7 +319,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
} }
s_logger.debug("Removing all invitations for the project " + project + " as a part of project cleanup..."); 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(); txn.commit();
if (result) { if (result) {
@ -358,7 +357,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
@Override @Override
public long getInvitationTimeout() { public long getInvitationTimeout() {
return _invitationTimeOut; return _invitationTimeOut;
} }
@Override @Override
@ -428,6 +427,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
return _projectAccountDao.canAccessProjectAccount(caller.getId(), accountId); return _projectAccountDao.canAccessProjectAccount(caller.getId(), accountId);
} }
@Override
public boolean canModifyProjectAccount(Account caller, long accountId) { public boolean canModifyProjectAccount(Account caller, long accountId) {
//ROOT admin always can access the project //ROOT admin always can access the project
if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) {
@ -510,15 +510,15 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
Project project = getProject(projectId); Project project = getProject(projectId);
if (project == null) { if (project == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id");
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
//User can be added to Active project only //User can be added to Active project only
if (project.getState() != Project.State.Active) { 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"); 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"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
@ -527,7 +527,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
if (accountName != null) { if (accountName != null) {
account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId());
if (account == null) { 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. // We don't have a DomainVO object with us, so just pass the tablename "domain" manually.
ex.addProxyObject("domain", project.getDomainId(), "domainId"); ex.addProxyObject("domain", project.getDomainId(), "domainId");
throw ex; throw ex;
@ -575,8 +575,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
if (generateTokenBasedInvitation(project, email, token) != null) { if (generateTokenBasedInvitation(project, email, token) != null) {
return true; return true;
} else { } else {
s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project); s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project);
return false; return false;
} }
} }
@ -592,15 +592,15 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
Project project = getProject(projectId); Project project = getProject(projectId);
if (project == null) { if (project == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id");
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
//check that account-to-remove exists //check that account-to-remove exists
Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId());
if (account == null) { 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. // Since we don't have a domainVO object, pass the table name manually.
ex.addProxyObject("domain", project.getDomainId(), "domainId"); ex.addProxyObject("domain", project.getDomainId(), "domainId");
} }
@ -611,16 +611,16 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
//Check if the account exists in the project //Check if the account exists in the project
ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId());
if (projectAccount == null) { if (projectAccount == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id"); 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. // Use the projectVO object and not the projectAccount object to inject the projectId.
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
//can't remove the owner of the project //can't remove the owner of the project
if (projectAccount.getAccountRole() == Role.Admin) { 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"); 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"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
@ -641,21 +641,21 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
} }
@DB @DB
public boolean activeInviteExists(Project project, Long accountId, String email) { public boolean activeInviteExists(Project project, Long accountId, String email) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
//verify if the invitation was already generated //verify if the invitation was already generated
ProjectInvitationVO invite = null; ProjectInvitationVO invite = null;
if (accountId != null) { if (accountId != null) {
invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId()); invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId());
} else if (email != null) { } else if (email != null) {
invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId());
} }
if (invite != null) { if (invite != null) {
if (invite.getState() == ProjectInvitation.State.Completed || if (invite.getState() == ProjectInvitation.State.Completed ||
(invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) { (invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) {
return true; return true;
} else { } else {
if (invite.getState() == ProjectInvitation.State.Pending) { if (invite.getState() == ProjectInvitation.State.Pending) {
expireInvitation(invite); expireInvitation(invite);
@ -664,7 +664,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
if (accountId != null) { if (accountId != null) {
s_logger.debug("Removing invitation in state " + invite.getState() + " for account id=" + accountId + " to project " + project); s_logger.debug("Removing invitation in state " + invite.getState() + " for account id=" + accountId + " to project " + project);
} else if (email != null) { } 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()); _projectInvitationDao.expunge(invite.getId());
@ -672,13 +672,13 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
} }
txn.commit(); txn.commit();
return false; return false;
} }
public ProjectInvitation generateTokenBasedInvitation(Project project, String email, String token) { public ProjectInvitation generateTokenBasedInvitation(Project project, String email, String token) {
//verify if the invitation was already generated //verify if the invitation was already generated
if (activeInviteExists(project, null, email)) { if (activeInviteExists(project, null, email)) {
throw new InvalidParameterValueException("There is already a pending invitation for email " + email + " to the project id=" + project); 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)); ProjectInvitation projectInvitation = _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), null, project.getDomainId(), email, token));
try { try {
@ -752,24 +752,24 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined; ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined;
//update invitation //update invitation
s_logger.debug("Marking invitation " + invite + " with state " + newState); s_logger.debug("Marking invitation " + invite + " with state " + newState);
invite.setState(newState); invite.setState(newState);
result = _projectInvitationDao.update(invite.getId(), invite); result = _projectInvitationDao.update(invite.getId(), invite);
if (result && accept) { if (result && accept) {
//check if account already exists for the project (was added before invitation got accepted) //check if account already exists for the project (was added before invitation got accepted)
ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId);
if (projectAccount != null) { if (projectAccount != null) {
s_logger.debug("Account " + accountName + " already added to the project id=" + projectId); s_logger.debug("Account " + accountName + " already added to the project id=" + projectId);
} else { } else {
assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); assignAccountToProject(project, accountId, ProjectAccount.Role.Regular);
} }
} else { } else {
s_logger.warn("Failed to update project invitation " + invite + " with state " + newState); s_logger.warn("Failed to update project invitation " + invite + " with state " + newState);
} }
txn.commit(); txn.commit();
} }
} else { } else {
throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId); throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId);
@ -793,8 +793,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
ProjectVO project = getProject(projectId); ProjectVO project = getProject(projectId);
if (project == null) { if (project == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id");
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
@ -835,8 +835,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
ProjectVO project= getProject(projectId); ProjectVO project= getProject(projectId);
//verify input parameters //verify input parameters
if (project == null) { if (project == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id");
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
@ -846,8 +846,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
s_logger.debug("Successfully suspended project id=" + projectId); s_logger.debug("Successfully suspended project id=" + projectId);
return _projectDao.findById(projectId); return _projectDao.findById(projectId);
} else { } else {
CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id"); CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id");
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
@ -995,33 +995,33 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
} }
public class ExpiredInvitationsCleanup implements Runnable { public class ExpiredInvitationsCleanup implements Runnable {
@Override @Override
public void run() { public void run() {
try { try {
TimeZone.getDefault(); TimeZone.getDefault();
List<ProjectInvitationVO> invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut); List<ProjectInvitationVO> invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut);
if (!invitationsToExpire.isEmpty()) { if (!invitationsToExpire.isEmpty()) {
s_logger.debug("Found " + invitationsToExpire.size() + " projects to expire"); s_logger.debug("Found " + invitationsToExpire.size() + " projects to expire");
for (ProjectInvitationVO invitationToExpire : invitationsToExpire) { for (ProjectInvitationVO invitationToExpire : invitationsToExpire) {
invitationToExpire.setState(ProjectInvitation.State.Expired); invitationToExpire.setState(ProjectInvitation.State.Expired);
_projectInvitationDao.update(invitationToExpire.getId(), invitationToExpire); _projectInvitationDao.update(invitationToExpire.getId(), invitationToExpire);
s_logger.trace("Expired project invitation id=" + invitationToExpire.getId()); s_logger.trace("Expired project invitation id=" + invitationToExpire.getId());
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
s_logger.warn("Exception while running expired invitations cleanup", ex); s_logger.warn("Exception while running expired invitations cleanup", ex);
} }
} }
} }
@Override @Override
public boolean projectInviteRequired() { public boolean projectInviteRequired() {
return _invitationRequired; return _invitationRequired;
} }
@Override @Override
public boolean allowUserToCreateProject() { public boolean allowUserToCreateProject() {
return _allowUserToCreateProject; return _allowUserToCreateProject;
} }
} }

View File

@ -16,6 +16,35 @@
// under the License. // under the License.
package com.cloud.server; 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.Config;
import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.Resource; 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.Mode;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao; 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;
import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offering.NetworkOffering.Availability;
import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingServiceMapVO;
@ -63,7 +96,6 @@ import com.cloud.user.User;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction; 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.net.NetUtils;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
import com.cloud.uuididentity.dao.IdentityDao; 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 @Component
public class ConfigurationServerImpl implements ConfigurationServer { public class ConfigurationServerImpl implements ConfigurationServer {
@ -506,26 +524,26 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) { if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) {
return; return;
} }
String already = _configDao.getValue("system.vm.password"); String already = _configDao.getValue("system.vm.password");
if (already == null) { if (already == null) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
String rpassword = PasswordGenerator.generatePresharedKey(8); String rpassword = PasswordGenerator.generatePresharedKey(8);
String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) "
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')"; + "','randmon password generated each management server starts for system vm')";
PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql);
stmt.executeUpdate(wSql); stmt.executeUpdate(wSql);
s_logger.info("Updated systemvm password in database"); s_logger.info("Updated systemvm password in database");
} catch (SQLException e) { } catch (SQLException e) {
s_logger.error("Cannot retrieve systemvm password", e); s_logger.error("Cannot retrieve systemvm password", e);
} }
} }
} }
@Override @Override
@DB @DB
@ -541,7 +559,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String already = _configDao.getValue("ssh.privatekey"); String already = _configDao.getValue("ssh.privatekey");
String homeDir = null; String homeDir = null;
homeDir = Script.runSimpleBashScript("echo ~" + username); homeDir = Script.runSimpleBashScript("echo ~" + username);
if (homeDir == null) { if (homeDir == null) {
throw new CloudRuntimeException("Cannot get home directory for account: " + username); throw new CloudRuntimeException("Cannot get home directory for account: " + username);
} }
@ -622,11 +640,11 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
s_logger.info("Going to update systemvm iso with generated keypairs if needed"); s_logger.info("Going to update systemvm iso with generated keypairs if needed");
try { try {
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
} catch (CloudRuntimeException e) { } catch (CloudRuntimeException e) {
if (!devel) { if (!devel) {
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
} }
} }

View File

@ -26,7 +26,6 @@ import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -48,13 +47,24 @@ import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException; import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException; 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.BaseUpdateTemplateOrIsoCmd;
import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; 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.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.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.storage.ListStoragePoolsCmd;
import org.apache.cloudstack.api.command.admin.systemvm.DestroySystemVmCmd; 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.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.address.ListPublicIpAddressesCmd;
import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd; import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd;
import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; 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.iso.UpdateIsoCmd;
import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; 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.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.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.ssh.RegisterSSHKeyPairCmd;
import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; 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.template.UpdateTemplateCmd;
import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; 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.command.user.zone.ListZonesByCmd;
import org.apache.cloudstack.api.response.ExtractResponse;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager;
import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortAnswer;
import com.cloud.agent.api.GetVncPortCommand; import com.cloud.agent.api.GetVncPortCommand;
@ -86,38 +98,19 @@ import com.cloud.alert.Alert;
import com.cloud.alert.AlertManager; import com.cloud.alert.AlertManager;
import com.cloud.alert.AlertVO; import com.cloud.alert.AlertVO;
import com.cloud.alert.dao.AlertDao; import com.cloud.alert.dao.AlertDao;
import org.apache.cloudstack.api.ApiConstants;
import com.cloud.api.ApiDBUtils; 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.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult; import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO; import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor; import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.async.dao.AsyncJobDao;
import com.cloud.capacity.Capacity; import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityVO; import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDao;
import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Configuration; import com.cloud.configuration.Configuration;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.consoleproxy.ConsoleProxyManagementState; import com.cloud.consoleproxy.ConsoleProxyManagementState;
@ -146,7 +139,6 @@ import com.cloud.event.EventTypes;
import com.cloud.event.EventUtils; import com.cloud.event.EventUtils;
import com.cloud.event.EventVO; import com.cloud.event.EventVO;
import com.cloud.event.dao.EventDao; import com.cloud.event.dao.EventDao;
import com.cloud.event.dao.EventJoinDao;
import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.CloudAuthenticationException;
import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
@ -233,9 +225,7 @@ import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapter; import com.cloud.utils.component.Adapter;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.component.SystemIntegrityChecker;
import com.cloud.utils.concurrency.NamedThreadFactory; 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.ConsoleProxyDao;
import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.InstanceGroupDao;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.SecondaryStorageVmDao;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.dao.VMInstanceDao;
@ -281,64 +270,107 @@ import edu.emory.mathcs.backport.java.util.Collections;
public class ManagementServerImpl implements ManagementServer { public class ManagementServerImpl implements ManagementServer {
public static final Logger s_logger = Logger.getLogger(ManagementServerImpl.class.getName()); public static final Logger s_logger = Logger.getLogger(ManagementServerImpl.class.getName());
private final AccountManager _accountMgr; @Inject
private final AgentManager _agentMgr; private AccountManager _accountMgr;
private final AlertManager _alertMgr; @Inject
private final IPAddressDao _publicIpAddressDao; private AgentManager _agentMgr;
private final DomainRouterDao _routerDao; @Inject
private final DomainRouterJoinDao _routerJoinDao; private AlertManager _alertMgr;
private final ConsoleProxyDao _consoleProxyDao; @Inject
private final ClusterDao _clusterDao; private IPAddressDao _publicIpAddressDao;
private final SecondaryStorageVmDao _secStorageVmDao; @Inject
private final EventDao _eventDao; private DomainRouterDao _routerDao;
private final EventJoinDao _eventJoinDao; @Inject
private final DataCenterDao _dcDao; private ConsoleProxyDao _consoleProxyDao;
private final VlanDao _vlanDao; @Inject
private final AccountVlanMapDao _accountVlanMapDao; private ClusterDao _clusterDao;
private final PodVlanMapDao _podVlanMapDao; @Inject
private final HostDao _hostDao; private SecondaryStorageVmDao _secStorageVmDao;
private final HostDetailsDao _detailsDao; @Inject
private final UserDao _userDao; private EventDao _eventDao;
private final UserVmDao _userVmDao; @Inject
private final ConfigurationDao _configDao; private DataCenterDao _dcDao;
private final ConsoleProxyManager _consoleProxyMgr; @Inject
private final SecondaryStorageVmManager _secStorageVmMgr; private VlanDao _vlanDao;
private final SwiftManager _swiftMgr; @Inject
private final S3Manager _s3Mgr; private AccountVlanMapDao _accountVlanMapDao;
private final ServiceOfferingDao _offeringsDao; @Inject
private final DiskOfferingDao _diskOfferingDao; private PodVlanMapDao _podVlanMapDao;
private final VMTemplateDao _templateDao; @Inject
private final DomainDao _domainDao; private HostDao _hostDao;
private final AccountDao _accountDao; @Inject
private final AlertDao _alertDao; private HostDetailsDao _detailsDao;
private final CapacityDao _capacityDao; @Inject
private final GuestOSDao _guestOSDao; private UserDao _userDao;
private final GuestOSCategoryDao _guestOSCategoryDao; @Inject
private final StoragePoolDao _poolDao; private UserVmDao _userVmDao;
private final NicDao _nicDao; @Inject
private final NetworkDao _networkDao; private ConfigurationDao _configDao;
private final StorageManager _storageMgr; @Inject
private final VirtualMachineManager _itMgr; private ConsoleProxyManager _consoleProxyMgr;
private final HostPodDao _hostPodDao; @Inject
private final VMInstanceDao _vmInstanceDao; private SecondaryStorageVmManager _secStorageVmMgr;
private final VolumeDao _volumeDao; @Inject
private final AsyncJobDao _jobDao; private SwiftManager _swiftMgr;
private final AsyncJobManager _asyncMgr; @Inject
private final int _purgeDelay; private ServiceOfferingDao _offeringsDao;
private final InstanceGroupDao _vmGroupDao; @Inject
private final InstanceGroupJoinDao _vmGroupJoinDao; private DiskOfferingDao _diskOfferingDao;
private final UploadMonitor _uploadMonitor; @Inject
private final UploadDao _uploadDao; private VMTemplateDao _templateDao;
private final SSHKeyPairDao _sshKeyPairDao; @Inject
private final LoadBalancerDao _loadbalancerDao; private DomainDao _domainDao;
private final HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; @Inject
private final Adapters<HostAllocator> _hostAllocators; private AccountDao _accountDao;
private final ConfigurationManager _configMgr; @Inject
private final ResourceTagDao _resourceTagDao; 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<HostAllocator> _hostAllocators;
@Inject
private ConfigurationManager _configMgr;
@Inject
private ResourceTagDao _resourceTagDao;
@Inject @Inject
ProjectManager _projectMgr; ProjectManager _projectMgr;
private final ResourceManager _resourceMgr; @Inject
ResourceManager _resourceMgr;
@Inject @Inject
SnapshotManager _snapshotMgr; SnapshotManager _snapshotMgr;
@Inject @Inject
@ -346,94 +378,33 @@ public class ManagementServerImpl implements ManagementServer {
@Inject @Inject
HostTagsDao _hostTagsDao; HostTagsDao _hostTagsDao;
private final KeystoreManager _ksMgr; @Inject
S3Manager _s3Mgr;
@Inject
ComponentContext _placeholder;
private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker"));
private KeystoreManager _ksMgr;
private final Map<String, String> _configs; private Map<String, String> _configs;
private final StatsCollector _statsCollector; private Map<String, Boolean> _availableIdsMap;
private final Map<String, Boolean> _availableIdsMap; @Inject List<UserAuthenticator> _userAuthenticators;
private Adapters<UserAuthenticator> _userAuthenticators;
private String _hashKey = null; private String _hashKey = null;
protected ManagementServerImpl() { public 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");
} }
@PostConstruct @PostConstruct
void init() { void init() {
_configs = _configDao.getConfiguration(); _configs = _configDao.getConfiguration();
String value = _configs.get("event.purge.interval"); String value = _configs.get("event.purge.interval");
int cleanup = NumbersUtil.parseInt(value, 60 * 60 * 24); // 1 day. int cleanup = NumbersUtil.parseInt(value, 60 * 60 * 24); // 1 day.
_statsCollector = StatsCollector.getInstance(_configs);
_purgeDelay = NumbersUtil.parseInt(_configs.get("event.purge.delay"), 0); _purgeDelay = NumbersUtil.parseInt(_configs.get("event.purge.delay"), 0);
if (_purgeDelay != 0) { if (_purgeDelay != 0) {
_eventExecutor.scheduleAtFixedRate(new EventPurgeTask(), cleanup, cleanup, TimeUnit.SECONDS); _eventExecutor.scheduleAtFixedRate(new EventPurgeTask(), cleanup, cleanup, TimeUnit.SECONDS);
@ -444,115 +415,111 @@ public class ManagementServerImpl implements ManagementServer {
for (String id : availableIds) { for (String id : availableIds) {
_availableIdsMap.put(id, true); _availableIdsMap.put(id, true);
} }
}
_userAuthenticators = locator.getAdapters(UserAuthenticator.class); @Override
if (_userAuthenticators == null || !_userAuthenticators.isSet()) { public void startup() {
s_logger.error("Unable to find an user authenticator."); s_logger.info("Startup CloudStack management server...");
initCloudStackComponents();
}
private void initCloudStackComponents() {
runCheckers();
startDaos(); // daos should not be using managers and adapters.
startManagers();
startAdapters();
}
private void runCheckers() {
Map<String, SystemIntegrityChecker> 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);
}
} }
} }
public void startup() {
s_logger.info("Startup CloudStack management server...");
initCloudStackComponents();
}
private void initCloudStackComponents() {
runCheckers();
startDaos(); // daos should not be using managers and adapters.
startManagers();
startAdapters();
}
private void runCheckers() {
Map<String, SystemIntegrityChecker> 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() { private void startDaos() {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, GenericDaoBase> daos = ComponentContext.getApplicationContext().getBeansOfType( Map<String, GenericDaoBase> daos = ComponentContext.getApplicationContext().getBeansOfType(
GenericDaoBase.class); GenericDaoBase.class);
for(GenericDaoBase dao : daos.values()) { for (GenericDaoBase dao : daos.values()) {
try { try {
s_logger.info("Starting dao " + ComponentContext.getTargetClass(dao).getName()); s_logger.info("Starting dao " + ComponentContext.getTargetClass(dao).getName());
// TODO // TODO
// dao.configure(dao.getClass().getSimpleName(), params); // dao.configure(dao.getClass().getSimpleName(), params);
} catch (Exception e) { } catch (Exception e) {
s_logger.error("Problems with running checker:" + ComponentContext.getTargetClass(dao).getName(), e); s_logger.error("Problems with running checker:" + ComponentContext.getTargetClass(dao).getName(), e);
System.exit(1); System.exit(1);
} }
} }
} }
private void startManagers() { private void startManagers() {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, Manager> managers = ComponentContext.getApplicationContext().getBeansOfType( Map<String, Manager> managers = ComponentContext.getApplicationContext().getBeansOfType(
Manager.class); Manager.class);
Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> params = new HashMap<String, Object>();
for(Manager manager : managers.values()) { for (Manager manager : managers.values()) {
s_logger.info("Start manager: " + ComponentContext.getTargetClass(manager).getName() + "..."); s_logger.info("Start manager: " + ComponentContext.getTargetClass(manager).getName() + "...");
try { try {
if(!ComponentContext.isPrimary(manager, Manager.class)) { if (!ComponentContext.isPrimary(manager, Manager.class)) {
s_logger.error("Skip manager:" + ComponentContext.getTargetClass(manager).getName() + " as there are multiple matches"); s_logger.error("Skip manager:" + ComponentContext.getTargetClass(manager).getName() + " as there are multiple matches");
continue; continue;
} }
if(!manager.configure(manager.getClass().getSimpleName(), params)) { if (!manager.configure(manager.getClass().getSimpleName(), params)) {
throw new CloudRuntimeException("Failed to start manager: " + ComponentContext.getTargetClass(manager).getName()); throw new CloudRuntimeException("Failed to start manager: " + ComponentContext.getTargetClass(manager).getName());
} }
if (!manager.start()) { if (!manager.start()) {
throw new CloudRuntimeException("Failed to start manager: " + ComponentContext.getTargetClass(manager).getName()); throw new CloudRuntimeException("Failed to start manager: " + ComponentContext.getTargetClass(manager).getName());
} }
if (manager instanceof ManagementBean) { 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); s_logger.error("Problems to start manager:" + ComponentContext.getTargetClass(manager).getName(), e);
System.exit(1); System.exit(1);
} }
} }
} }
private void startAdapters() { private void startAdapters() {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, Adapter> adapters = ComponentContext.getApplicationContext().getBeansOfType( Map<String, Adapter> adapters = ComponentContext.getApplicationContext().getBeansOfType(
Adapter.class); Adapter.class);
Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> params = new HashMap<String, Object>();
for(Adapter adapter : adapters.values()) { for (Adapter adapter : adapters.values()) {
try { try {
if(!ComponentContext.isPrimary(adapter, Adapter.class)) if (!ComponentContext.isPrimary(adapter, Adapter.class))
continue; continue;
if(!adapter.configure(adapter.getClass().getSimpleName(), params)) { if (!adapter.configure(adapter.getClass().getSimpleName(), params)) {
throw new CloudRuntimeException("Failed to start adapter: " + ComponentContext.getTargetClass(adapter).getName()); throw new CloudRuntimeException("Failed to start adapter: " + ComponentContext.getTargetClass(adapter).getName());
} }
if (!adapter.start()) { if (!adapter.start()) {
throw new CloudRuntimeException("Failed to start adapter: " + ComponentContext.getTargetClass(adapter).getName()); throw new CloudRuntimeException("Failed to start adapter: " + ComponentContext.getTargetClass(adapter).getName());
} }
if (adapter instanceof ManagementBean) { 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); s_logger.error("Problems to start manager:" + ComponentContext.getTargetClass(adapter).getName(), e);
System.exit(1); System.exit(1);
} }
} }
} }
protected void registerMBean(ManagementBean mbean) { protected void registerMBean(ManagementBean mbean) {
@ -592,7 +559,7 @@ public class ManagementServerImpl implements ManagementServer {
// right now, we made the decision to only list zones associated // right now, we made the decision to only list zones associated
// with this domain // with this domain
dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private
// zones // zones
} else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) {
if (keyword != null) { if (keyword != null) {
dcs = _dcDao.findByKeyword(keyword); dcs = _dcDao.findByKeyword(keyword);
@ -861,8 +828,8 @@ public class ManagementServerImpl implements ManagementServer {
} else if (vmId != null) { } else if (vmId != null) {
UserVmVO vmInstance = _userVmDao.findById(vmId); UserVmVO vmInstance = _userVmDao.findById(vmId);
if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id");
ex.addProxyObject(vmInstance, vmId, "vmId"); ex.addProxyObject(vmInstance, vmId, "vmId");
throw ex; throw ex;
} }
@ -937,8 +904,8 @@ public class ManagementServerImpl implements ManagementServer {
} else if (vmId != null) { } else if (vmId != null) {
UserVmVO vmInstance = _userVmDao.findById(vmId); UserVmVO vmInstance = _userVmDao.findById(vmId);
if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
ex.addProxyObject(vmInstance, vmId, "vmId"); ex.addProxyObject(vmInstance, vmId, "vmId");
throw ex; throw ex;
} }
@ -987,15 +954,15 @@ public class ManagementServerImpl implements ManagementServer {
@Override @Override
public List<? extends Cluster> searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) { public List<? extends Cluster> searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) {
Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal);
SearchCriteria<ClusterVO> sc = _clusterDao.createSearchCriteria(); SearchCriteria<ClusterVO> sc = _clusterDao.createSearchCriteria();
zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId);
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType);
return _clusterDao.search(sc, searchFilter); return _clusterDao.search(sc, searchFilter);
} }
@Override @Override
@ -1053,7 +1020,6 @@ public class ManagementServerImpl implements ManagementServer {
return new Pair<List<? extends Cluster>, Integer>(result.first(), result.second()); return new Pair<List<? extends Cluster>, Integer>(result.first(), result.second());
} }
@Override @Override
public Pair<List<? extends Host>, List<? extends Host>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) { public Pair<List<? extends Host>, List<? extends Host>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) {
// access check - only root admin can migrate VM // access check - only root admin can migrate VM
@ -1067,8 +1033,8 @@ public class ManagementServerImpl implements ManagementServer {
VMInstanceVO vm = _vmInstanceDao.findById(vmId); VMInstanceVO vm = _vmInstanceDao.findById(vmId);
if (vm == null) { if (vm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id");
ex.addProxyObject(vm, vmId, "vmId"); ex.addProxyObject(vm, vmId, "vmId");
throw ex; throw ex;
} }
// business logic // business logic
@ -1135,7 +1101,7 @@ public class ManagementServerImpl implements ManagementServer {
ExcludeList excludes = new ExcludeList(); ExcludeList excludes = new ExcludeList();
excludes.addHost(srcHostId); 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); suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, HostAllocator.RETURN_UPTO_ALL, false);
if (suitableHosts != null && !suitableHosts.isEmpty()) { if (suitableHosts != null && !suitableHosts.isEmpty()) {
break; break;
@ -1310,8 +1276,8 @@ public class ManagementServerImpl implements ManagementServer {
if (projectId != null) { if (projectId != null) {
Project project = _projectMgr.getProject(projectId); Project project = _projectMgr.getProject(projectId);
if (project == null) { if (project == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
ex.addProxyObject(project, projectId, "projectId"); ex.addProxyObject(project, projectId, "projectId");
throw ex; throw ex;
} }
accountId = project.getProjectAccountId(); accountId = project.getProjectAccountId();
@ -1613,15 +1579,15 @@ public class ManagementServerImpl implements ManagementServer {
// verify that template exists // verify that template exists
VMTemplateVO template = _templateDao.findById(id); VMTemplateVO template = _templateDao.findById(id);
if (template == null || template.getRemoved() != null) { if (template == null || template.getRemoved() != null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
ex.addProxyObject(template, id, "templateId"); ex.addProxyObject(template, id, "templateId");
throw ex; throw ex;
} }
// Don't allow to modify system template // Don't allow to modify system template
if (id == Long.valueOf(1)) { if (id == Long.valueOf(1)) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id");
ex.addProxyObject(template, id, "templateId"); ex.addProxyObject(template, id, "templateId");
throw ex; throw ex;
} }
@ -1683,9 +1649,6 @@ public class ManagementServerImpl implements ManagementServer {
return _templateDao.findById(id); return _templateDao.findById(id);
} }
@Override @Override
public Pair<List<? extends IpAddress>, Integer> searchForIPAddresses(ListPublicIpAddressesCmd cmd) { public Pair<List<? extends IpAddress>, Integer> searchForIPAddresses(ListPublicIpAddressesCmd cmd) {
Object keyword = cmd.getKeyword(); Object keyword = cmd.getKeyword();
@ -1723,7 +1686,7 @@ public class ManagementServerImpl implements ManagementServer {
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
listProjectResourcesCriteria = domainIdRecursiveListProject.third(); 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("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
@ -1736,7 +1699,7 @@ public class ManagementServerImpl implements ManagementServer {
sb.and("isStaticNat", sb.entity().isOneToOneNat(), SearchCriteria.Op.EQ); sb.and("isStaticNat", sb.entity().isOneToOneNat(), SearchCriteria.Op.EQ);
sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
if (forLoadBalancing != null && (Boolean) forLoadBalancing) { if (forLoadBalancing != null && forLoadBalancing) {
SearchBuilder<LoadBalancerVO> lbSearch = _loadbalancerDao.createSearchBuilder(); SearchBuilder<LoadBalancerVO> lbSearch = _loadbalancerDao.createSearchBuilder();
sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER); sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER);
sb.groupBy(sb.entity().getId()); sb.groupBy(sb.entity().getId());
@ -1770,14 +1733,14 @@ public class ManagementServerImpl implements ManagementServer {
VlanType vlanType = null; VlanType vlanType = null;
if (forVirtualNetwork != null) { if (forVirtualNetwork != null) {
vlanType = (Boolean) forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached;
} else { } else {
vlanType = VlanType.VirtualNetwork; vlanType = VlanType.VirtualNetwork;
} }
SearchCriteria<IPAddressVO> sc = sb.create(); SearchCriteria<IPAddressVO> sc = sb.create();
if (isAllocated) { if (isAllocated) {
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
} }
sc.setJoinParameters("vlanSearch", "vlanType", vlanType); sc.setJoinParameters("vlanSearch", "vlanType", vlanType);
@ -1903,7 +1866,7 @@ public class ManagementServerImpl implements ManagementServer {
@ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true) @ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true)
private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException,
ConcurrentOperationException { ConcurrentOperationException {
User caller = _userDao.findById(UserContext.current().getCallerUserId()); User caller = _userDao.findById(UserContext.current().getCallerUserId());
@ -1971,8 +1934,8 @@ public class ManagementServerImpl implements ManagementServer {
// check if domain exists in the system // check if domain exists in the system
DomainVO domain = _domainDao.findById(domainId); DomainVO domain = _domainDao.findById(domainId);
if (domain == null) { if (domain == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
ex.addProxyObject(domain, domainId, "domainId"); ex.addProxyObject(domain, domainId, "domainId");
throw ex; throw ex;
} else if (domain.getParent() == null && domainName != null) { } else if (domain.getParent() == null && domainName != null) {
// check if domain is ROOT domain - and deny to edit it with the new // check if domain is ROOT domain - and deny to edit it with the new
@ -1996,7 +1959,7 @@ public class ManagementServerImpl implements ManagementServer {
InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '"
+ domainName + "' since it already exists in the system"); + domainName + "' since it already exists in the system");
ex.addProxyObject(domain, domainId, "domainId"); ex.addProxyObject(domain, domainId, "domainId");
throw ex; throw ex;
} }
} }
@ -2235,10 +2198,10 @@ public class ManagementServerImpl implements ManagementServer {
dcList.add(ApiDBUtils.findZoneById(zoneId)); dcList.add(ApiDBUtils.findZoneById(zoneId));
} else { } else {
if (clusterId != null) { if (clusterId != null) {
zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId();
} else { } else {
zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); zoneId = ApiDBUtils.findPodById(podId).getDataCenterId();
} }
if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) { if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) {
capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId)); capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId));
} }
@ -2366,7 +2329,7 @@ public class ManagementServerImpl implements ManagementServer {
if (domainId != null) { if (domainId != null) {
if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
return _diskOfferingDao.listByDomainId(domainId);// no perm return _diskOfferingDao.listByDomainId(domainId);// no perm
// check // check
} else { } else {
// check if the user's domain == do's domain || user's domain is // check if the user's domain == do's domain || user's domain is
// a child of so's domain // a child of so's domain
@ -2540,8 +2503,7 @@ public class ManagementServerImpl implements ManagementServer {
} }
return _poolDao.searchAndCount(sc, searchFilter); return _poolDao.searchAndCount(sc, searchFilter);
} }
@ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true) @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true)
public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { 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) @ActionEvent(eventType = EventTypes.EVENT_SSVM_STOP, eventDescription = "stopping secondary storage Vm", async = true)
private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException,
OperationTimedoutException, ConcurrentOperationException { OperationTimedoutException, ConcurrentOperationException {
User caller = _userDao.findById(UserContext.current().getCallerUserId()); User caller = _userDao.findById(UserContext.current().getCallerUserId());
@ -2653,8 +2615,8 @@ public class ManagementServerImpl implements ManagementServer {
public VirtualMachine.Type findSystemVMTypeById(long instanceId) { public VirtualMachine.Type findSystemVMTypeById(long instanceId) {
VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if (systemVm == null) { if (systemVm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId");
ex.addProxyObject(systemVm, instanceId, "instanceId"); ex.addProxyObject(systemVm, instanceId, "instanceId");
throw ex; throw ex;
} }
return systemVm.getType(); return systemVm.getType();
@ -2665,8 +2627,8 @@ public class ManagementServerImpl implements ManagementServer {
VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if (systemVm == null) { if (systemVm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
ex.addProxyObject(systemVm, vmId, "vmId"); ex.addProxyObject(systemVm, vmId, "vmId");
throw ex; throw ex;
} }
@ -2675,8 +2637,8 @@ public class ManagementServerImpl implements ManagementServer {
} else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) { } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) {
return startSecondaryStorageVm(vmId); return startSecondaryStorageVm(vmId);
} else { } else {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId");
ex.addProxyObject(systemVm, vmId, "vmId"); ex.addProxyObject(systemVm, vmId, "vmId");
throw ex; throw ex;
} }
} }
@ -2688,8 +2650,8 @@ public class ManagementServerImpl implements ManagementServer {
// verify parameters // verify parameters
VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if (systemVm == null) { if (systemVm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
ex.addProxyObject(systemVm, id, "vmId"); ex.addProxyObject(systemVm, id, "vmId");
throw ex; throw ex;
} }
@ -2710,8 +2672,8 @@ public class ManagementServerImpl implements ManagementServer {
VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if (systemVm == null) { if (systemVm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
ex.addProxyObject(systemVm, cmd.getId(), "vmId"); ex.addProxyObject(systemVm, cmd.getId(), "vmId");
throw ex; throw ex;
} }
@ -2727,8 +2689,8 @@ public class ManagementServerImpl implements ManagementServer {
VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if (systemVm == null) { if (systemVm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
ex.addProxyObject(systemVm, cmd.getId(), "vmId"); ex.addProxyObject(systemVm, cmd.getId(), "vmId");
throw ex; throw ex;
} }
@ -2765,8 +2727,8 @@ public class ManagementServerImpl implements ManagementServer {
// verify that user exists // verify that user exists
User user = _accountMgr.getUserIncludingRemoved(userId); User user = _accountMgr.getUserIncludingRemoved(userId);
if ((user == null) || (user.getRemoved() != null)) { if ((user == null) || (user.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id");
ex.addProxyObject(user, userId, "userId"); ex.addProxyObject(user, userId, "userId");
throw ex; throw ex;
} }
@ -2821,7 +2783,7 @@ public class ManagementServerImpl implements ManagementServer {
capabilities.put("securityGroupsEnabled", securityGroupsEnabled); capabilities.put("securityGroupsEnabled", securityGroupsEnabled);
capabilities 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("cloudStackVersion", getVersion());
capabilities.put("supportELB", supportELB); capabilities.put("supportELB", supportELB);
capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired()); capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired());
@ -2852,8 +2814,8 @@ public class ManagementServerImpl implements ManagementServer {
VolumeVO volume = _volumeDao.findById(volumeId); VolumeVO volume = _volumeDao.findById(volumeId);
if (volume == null) { if (volume == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId"); InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
ex.addProxyObject(volume, volumeId, "volumeId"); ex.addProxyObject(volume, volumeId, "volumeId");
throw ex; throw ex;
} }
@ -2878,19 +2840,19 @@ public class ManagementServerImpl implements ManagementServer {
} }
if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont
// have any // have any
// template // template
// dependence. // dependence.
VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
if (template != null) { // For ISO based volumes template = null and if (template != null) { // For ISO based volumes template = null and
// we allow extraction of all ISO based // we allow extraction of all ISO based
// volumes // volumes
boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global
// admins are always allowed to extract // admins are always allowed to extract
PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
ex.addProxyObject(volume, volumeId, "volumeId"); ex.addProxyObject(volume, volumeId, "volumeId");
throw ex; throw ex;
} }
} }
@ -2939,7 +2901,7 @@ public class ManagementServerImpl implements ManagementServer {
if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) { if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) {
return extractURLList.get(0).getId(); // If download url already return extractURLList.get(0).getId(); // If download url already
// exists then return // exists then return
} else { } else {
UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME,
url, extractMode); url, extractMode);
@ -2997,12 +2959,12 @@ public class ManagementServerImpl implements ManagementServer {
_uploadDao.update(uploadJob.getId(), uploadJob); _uploadDao.update(uploadJob.getId(), uploadJob);
if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is
// copied perform the actual // copied perform the actual
// uploading // uploading
_uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath, cmd.getStartEventId(), job.getId(), _asyncMgr); _uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath, cmd.getStartEventId(), job.getId(), _asyncMgr);
return uploadJob.getId(); return uploadJob.getId();
} else { // Volume is copied now make it visible under apache and } 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()); _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId());
return uploadJob.getId(); return uploadJob.getId();
} }
@ -3034,8 +2996,8 @@ public class ManagementServerImpl implements ManagementServer {
// Verify input parameters // Verify input parameters
InstanceGroupVO group = _vmGroupDao.findById(groupId.longValue()); InstanceGroupVO group = _vmGroupDao.findById(groupId.longValue());
if (group == null) { if (group == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId");
ex.addProxyObject(group, groupId, "groupId"); ex.addProxyObject(group, groupId, "groupId");
throw ex; throw ex;
} }
@ -3055,8 +3017,6 @@ public class ManagementServerImpl implements ManagementServer {
return _vmGroupDao.findById(groupId); return _vmGroupDao.findById(groupId);
} }
@Override @Override
public String getVersion() { public String getVersion() {
final Class<?> c = ManagementServer.class; final Class<?> c = ManagementServer.class;
@ -3192,7 +3152,7 @@ public class ManagementServerImpl implements ManagementServer {
if (s == null) { if (s == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName()
+ "' does not exist for account " + owner.getAccountName() + " in specified domain id"); + "' 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; throw ex;
} }
@ -3277,8 +3237,8 @@ public class ManagementServerImpl implements ManagementServer {
UserVmVO vm = _userVmDao.findById(cmd.getId()); UserVmVO vm = _userVmDao.findById(cmd.getId());
if (vm == null) { if (vm == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found.");
ex.addProxyObject(vm, cmd.getId(), "vmId"); ex.addProxyObject(vm, cmd.getId(), "vmId");
throw ex; throw ex;
} }
@ -3288,8 +3248,8 @@ public class ManagementServerImpl implements ManagementServer {
_userVmDao.loadDetails(vm); _userVmDao.loadDetails(vm);
String password = vm.getDetail("Encrypted.Password"); String password = vm.getDetail("Encrypted.Password");
if (password == null || password.equals("")) { if (password == null || password.equals("")) {
InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found."); InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found.");
ex.addProxyObject(vm, cmd.getId(), "vmId"); ex.addProxyObject(vm, cmd.getId(), "vmId");
throw ex; throw ex;
} }
@ -3398,8 +3358,8 @@ public class ManagementServerImpl implements ManagementServer {
HypervisorCapabilitiesVO hpvCapabilities = _hypervisorCapabilitiesDao.findById(id, true); HypervisorCapabilitiesVO hpvCapabilities = _hypervisorCapabilitiesDao.findById(id, true);
if (hpvCapabilities == null) { if (hpvCapabilities == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id"); InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id");
ex.addProxyObject(hpvCapabilities, id, "Id"); ex.addProxyObject(hpvCapabilities, id, "Id");
throw ex; throw ex;
} }
@ -3453,6 +3413,7 @@ public class ManagementServerImpl implements ManagementServer {
} }
@Override
public void enableAdminUser(String password) { public void enableAdminUser(String password) {
String encodedPassword = null; String encodedPassword = null;
@ -3461,8 +3422,8 @@ public class ManagementServerImpl implements ManagementServer {
// This means its a new account, set the password using the // This means its a new account, set the password using the
// authenticator // authenticator
for (Enumeration<UserAuthenticator> en = _userAuthenticators.enumeration(); en.hasMoreElements();) { for (Iterator<UserAuthenticator> en = _userAuthenticators.iterator(); en.hasNext();) {
UserAuthenticator authenticator = en.nextElement(); UserAuthenticator authenticator = en.next();
encodedPassword = authenticator.encode(password); encodedPassword = authenticator.encode(password);
if (encodedPassword != null) { if (encodedPassword != null) {
break; break;

View File

@ -36,46 +36,47 @@ import com.cloud.utils.SerialVersionUID;
import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentContext;
public class CloudStartupServlet extends HttpServlet implements ServletContextListener { public class CloudStartupServlet extends HttpServlet implements ServletContextListener {
public static final Logger s_logger = Logger.getLogger(CloudStartupServlet.class.getName()); public static final Logger s_logger = Logger.getLogger(CloudStartupServlet.class.getName());
static final long serialVersionUID = SerialVersionUID.CloudStartupServlet; static final long serialVersionUID = SerialVersionUID.CloudStartupServlet;
@Override @Override
public void init() throws ServletException { public void init() throws ServletException {
initLog4j(); initLog4j();
// Save Configuration Values // Save Configuration Values
ConfigurationServer c = (ConfigurationServer)ComponentContext.getCompanent(ConfigurationServer.class); ConfigurationServer c = ComponentContext.getCompanent(ConfigurationServer.class);
try { try {
c.persistDefaultValues(); 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 ManagementServer ms = ComponentContext.getCompanent(ManagementServer.class);
public void contextInitialized(ServletContextEvent sce) { ms.startup();
try { ms.enableAdminUser("password");
init(); ApiServer.initApiServer(ms.getPropertiesFiles());
} catch (ServletException e) { } catch (InvalidParameterValueException ipve) {
s_logger.error("Exception starting management server ", e); s_logger.error("Exception starting management server ", ipve);
throw new RuntimeException(e); throw new ServletException (ipve.getMessage());
} } catch (Exception e) {
} s_logger.error("Exception starting management server ", e);
throw new ServletException (e.getMessage());
}
}
@Override @Override
public void contextDestroyed(ServletContextEvent sce) { public void contextInitialized(ServletContextEvent sce) {
} try {
init();
} catch (ServletException e) {
s_logger.error("Exception starting management server ", e);
throw new RuntimeException(e);
}
}
private void initLog4j() { @Override
public void contextDestroyed(ServletContextEvent sce) {
}
private void initLog4j() {
File file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); File file = PropertiesUtil.findConfigFile("log4j-cloud.xml");
if (file != null) { if (file != null) {
s_logger.info("log4j configuration found at " + file.getAbsolutePath()); s_logger.info("log4j configuration found at " + file.getAbsolutePath());
@ -87,5 +88,5 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi
PropertyConfigurator.configureAndWatch(file.getAbsolutePath()); PropertyConfigurator.configureAndWatch(file.getAbsolutePath());
} }
} }
} }
} }

View File

@ -20,6 +20,8 @@ import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import org.springframework.stereotype.Component;
import com.cloud.storage.VolumeHostVO; import com.cloud.storage.VolumeHostVO;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
@ -29,85 +31,85 @@ import com.cloud.utils.db.SearchCriteria;
@Local(value={VolumeHostDao.class}) @Local(value={VolumeHostDao.class})
public class VolumeHostDaoImpl extends GenericDaoBase<VolumeHostVO, Long> implements VolumeHostDao { public class VolumeHostDaoImpl extends GenericDaoBase<VolumeHostVO, Long> implements VolumeHostDao {
protected final SearchBuilder<VolumeHostVO> HostVolumeSearch; protected final SearchBuilder<VolumeHostVO> HostVolumeSearch;
protected final SearchBuilder<VolumeHostVO> ZoneVolumeSearch; protected final SearchBuilder<VolumeHostVO> ZoneVolumeSearch;
protected final SearchBuilder<VolumeHostVO> VolumeSearch; protected final SearchBuilder<VolumeHostVO> VolumeSearch;
protected final SearchBuilder<VolumeHostVO> HostSearch; protected final SearchBuilder<VolumeHostVO> HostSearch;
protected final SearchBuilder<VolumeHostVO> HostDestroyedSearch; protected final SearchBuilder<VolumeHostVO> HostDestroyedSearch;
VolumeHostDaoImpl(){ VolumeHostDaoImpl(){
HostVolumeSearch = createSearchBuilder(); HostVolumeSearch = createSearchBuilder();
HostVolumeSearch.and("host_id", HostVolumeSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostVolumeSearch.and("host_id", HostVolumeSearch.entity().getHostId(), SearchCriteria.Op.EQ);
HostVolumeSearch.and("volume_id", HostVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); HostVolumeSearch.and("volume_id", HostVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
HostVolumeSearch.and("destroyed", HostVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); HostVolumeSearch.and("destroyed", HostVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
HostVolumeSearch.done(); HostVolumeSearch.done();
ZoneVolumeSearch = createSearchBuilder(); ZoneVolumeSearch = createSearchBuilder();
ZoneVolumeSearch.and("zone_id", ZoneVolumeSearch.entity().getZoneId(), SearchCriteria.Op.EQ); ZoneVolumeSearch.and("zone_id", ZoneVolumeSearch.entity().getZoneId(), SearchCriteria.Op.EQ);
ZoneVolumeSearch.and("volume_id", ZoneVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); ZoneVolumeSearch.and("volume_id", ZoneVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
ZoneVolumeSearch.and("destroyed", ZoneVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); ZoneVolumeSearch.and("destroyed", ZoneVolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
ZoneVolumeSearch.done(); ZoneVolumeSearch.done();
HostSearch = createSearchBuilder(); HostSearch = createSearchBuilder();
HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
HostSearch.and("destroyed", HostSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); HostSearch.and("destroyed", HostSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
HostSearch.done(); HostSearch.done();
VolumeSearch = createSearchBuilder(); VolumeSearch = createSearchBuilder();
VolumeSearch.and("volume_id", VolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); VolumeSearch.and("volume_id", VolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
VolumeSearch.and("destroyed", VolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); VolumeSearch.and("destroyed", VolumeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
VolumeSearch.done(); VolumeSearch.done();
HostDestroyedSearch = createSearchBuilder(); HostDestroyedSearch = createSearchBuilder();
HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ);
HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
HostDestroyedSearch.done(); HostDestroyedSearch.done();
} }
@Override @Override
public VolumeHostVO findByHostVolume(long hostId, long volumeId) { public VolumeHostVO findByHostVolume(long hostId, long volumeId) {
SearchCriteria<VolumeHostVO> sc = HostVolumeSearch.create(); SearchCriteria<VolumeHostVO> sc = HostVolumeSearch.create();
sc.setParameters("host_id", hostId); sc.setParameters("host_id", hostId);
sc.setParameters("volume_id", volumeId); sc.setParameters("volume_id", volumeId);
sc.setParameters("destroyed", false); sc.setParameters("destroyed", false);
return findOneIncludingRemovedBy(sc); return findOneIncludingRemovedBy(sc);
} }
@Override @Override
public VolumeHostVO findVolumeByZone(long volumeId, long zoneId) { public VolumeHostVO findVolumeByZone(long volumeId, long zoneId) {
SearchCriteria<VolumeHostVO> sc = ZoneVolumeSearch.create(); SearchCriteria<VolumeHostVO> sc = ZoneVolumeSearch.create();
sc.setParameters("zone_id", zoneId); sc.setParameters("zone_id", zoneId);
sc.setParameters("volume_id", volumeId); sc.setParameters("volume_id", volumeId);
sc.setParameters("destroyed", false); sc.setParameters("destroyed", false);
return findOneIncludingRemovedBy(sc); return findOneIncludingRemovedBy(sc);
} }
@Override @Override
public VolumeHostVO findByVolumeId(long volumeId) { public VolumeHostVO findByVolumeId(long volumeId) {
SearchCriteria<VolumeHostVO> sc = VolumeSearch.create(); SearchCriteria<VolumeHostVO> sc = VolumeSearch.create();
sc.setParameters("volume_id", volumeId); sc.setParameters("volume_id", volumeId);
sc.setParameters("destroyed", false); sc.setParameters("destroyed", false);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public List<VolumeHostVO> listBySecStorage(long ssHostId) { public List<VolumeHostVO> listBySecStorage(long ssHostId) {
SearchCriteria<VolumeHostVO> sc = HostSearch.create(); SearchCriteria<VolumeHostVO> sc = HostSearch.create();
sc.setParameters("host_id", ssHostId); sc.setParameters("host_id", ssHostId);
sc.setParameters("destroyed", false); sc.setParameters("destroyed", false);
return listAll(); return listAll();
} }
@Override @Override
public List<VolumeHostVO> listDestroyed(long hostId){ public List<VolumeHostVO> listDestroyed(long hostId){
SearchCriteria<VolumeHostVO> sc = HostDestroyedSearch.create(); SearchCriteria<VolumeHostVO> sc = HostDestroyedSearch.create();
sc.setParameters("host_id", hostId); sc.setParameters("host_id", hostId);
sc.setParameters("destroyed", true); sc.setParameters("destroyed", true);
return listIncludingRemovedBy(sc); return listIncludingRemovedBy(sc);
} }
} }

View File

@ -20,8 +20,8 @@ import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -39,20 +39,18 @@ import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.SecurityChecker; 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.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.RegisterCmd;
import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.dao.UserAccountJoinDao; import com.cloud.api.query.dao.UserAccountJoinDao;
import com.cloud.api.query.vo.ControlledViewEntity; 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.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.ResourceLimit;
@ -115,7 +113,6 @@ import com.cloud.user.dao.UserDao;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
@ -285,6 +282,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return true; return true;
} }
@Override
public AccountVO getSystemAccount() { public AccountVO getSystemAccount() {
if (_systemAccount == null) { if (_systemAccount == null) {
_systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
@ -382,7 +380,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (!granted) { if (!granted) {
assert false : "How can all of the security checkers pass on checking this check: " + entity; 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()); user.setState(State.disabled.toString());
} }
_userAccountDao.update(id, user); _userAccountDao.update(id, user);
txn.commit(); txn.commit();
} catch (Exception e) { } catch (Exception e) {
s_logger.error("Failed to update login attempts for user with id " + id ); s_logger.error("Failed to update login attempts for user with id " + id );
} }
@ -646,8 +644,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
for (IpAddress ip : ipsToRelease) { for (IpAddress ip : ipsToRelease) {
s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
accountCleanupNeeded = true; accountCleanupNeeded = true;
} }
} }
} }
@ -936,15 +934,15 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (password != null) { if (password != null) {
String encodedPassword = null; String encodedPassword = null;
for (Enumeration<UserAuthenticator> en = _userAuthenticators.enumeration(); en.hasMoreElements();) { for (Iterator<UserAuthenticator> en = _userAuthenticators.iterator(); en.hasNext();) {
UserAuthenticator authenticator = en.nextElement(); UserAuthenticator authenticator = en.next();
encodedPassword = authenticator.encode(password); encodedPassword = authenticator.encode(password);
if (encodedPassword != null) { if (encodedPassword != null) {
break; break;
} }
} }
if (encodedPassword == null) { if (encodedPassword == null) {
throw new CloudRuntimeException("Failed to encode password"); throw new CloudRuntimeException("Failed to encode password");
} }
user.setPassword(encodedPassword); 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 // check if the given account name is unique in this domain for updating
Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId); Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId);
if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow
// same // same
// account // account
// to // to
// update // update
// itself // itself
throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:" throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:"
+ duplicateAcccount.getId()); + duplicateAcccount.getId());
} }
@ -1697,15 +1695,15 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
String encodedPassword = null; String encodedPassword = null;
for (Enumeration<UserAuthenticator> en = _userAuthenticators.enumeration(); en.hasMoreElements();) { for (Iterator<UserAuthenticator> en = _userAuthenticators.iterator(); en.hasNext();) {
UserAuthenticator authenticator = en.nextElement(); UserAuthenticator authenticator = en.next();
encodedPassword = authenticator.encode(password); encodedPassword = authenticator.encode(password);
if (encodedPassword != null) { if (encodedPassword != null) {
break; break;
} }
} }
if (encodedPassword == null) { 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)); 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 @Override
public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long> public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long>
permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject,
boolean listAll, boolean forProjectInvitation) { boolean listAll, boolean forProjectInvitation) {
Long domainId = domainIdRecursiveListProject.first(); Long domainId = domainIdRecursiveListProject.first();
if (domainId != null) { if (domainId != null) {
@ -2166,7 +2164,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
} }
@Override @Override
public void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId, public void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId,
boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) {
@ -2210,7 +2208,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
@Override @Override
public UserAccount getUserByApiKey(String apiKey) { public UserAccount getUserByApiKey(String apiKey) {
return _userAccountDao.getUserByApiKey(apiKey); return _userAccountDao.getUserByApiKey(apiKey);
} }
} }

View File

@ -50,7 +50,6 @@ import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;

View File

@ -23,7 +23,8 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.api.IdentityService; 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.utils.component.Manager;
import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDao;
@ -32,36 +33,38 @@ import com.cloud.uuididentity.dao.IdentityDao;
public class IdentityServiceImpl implements Manager, IdentityService { public class IdentityServiceImpl implements Manager, IdentityService {
private String _name; private String _name;
@Inject private IdentityDao _identityDao; @Inject private IdentityDao _identityDao;
@Override
public Long getIdentityId(String tableName, String identityString) { public Long getIdentityId(String tableName, String identityString) {
return _identityDao.getIdentityId(tableName, identityString); return _identityDao.getIdentityId(tableName, identityString);
} }
public String getIdentityUuid(String tableName, String identityString) { @Override
return _identityDao.getIdentityUuid(tableName, identityString); public String getIdentityUuid(String tableName, String identityString) {
} return _identityDao.getIdentityUuid(tableName, identityString);
}
@Override @Override
public boolean configure(String name, Map<String, Object> params) public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException { throws ConfigurationException {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public String getName() { public String getName() {
return _name; return _name;
} }
@Override @Override
public boolean start() { public boolean start() {
return true; return true;
} }
@Override @Override
public boolean stop() { public boolean stop() {
return true; return true;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -156,6 +156,7 @@ DROP TABLE IF EXISTS `cloud`.`autoscale_vmprofiles`;
DROP TABLE IF EXISTS `cloud`.`autoscale_policies`; DROP TABLE IF EXISTS `cloud`.`autoscale_policies`;
DROP TABLE IF EXISTS `cloud`.`counter`; DROP TABLE IF EXISTS `cloud`.`counter`;
DROP TABLE IF EXISTS `cloud`.`conditions`; DROP TABLE IF EXISTS `cloud`.`conditions`;
DROP TABLE IF EXISTS `cloud`.`inline_load_balancer_nic_map`;
CREATE TABLE `cloud`.`version` ( CREATE TABLE `cloud`.`version` (
`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id',

View File

@ -16,7 +16,7 @@
// under the License. // under the License.
package com.cloud.utils; package com.cloud.utils;
import static java.util.Arrays.*; import static java.util.Arrays.asList;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; 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;
}
} }