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>
</configuration>
</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>
<id>grant-user-cloud-bridge</id>
<phase>process-test-resources</phase>
@ -507,9 +492,9 @@
</goals>
<configuration>
<autocommit>true</autocommit>
<srcFiles>
<srcFile>${basedir}/developer-prefill.sql</srcFile>
</srcFiles>
<srcFiles>
<srcFile>${basedir}/developer-prefill.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>
@ -518,56 +503,58 @@
</build>
</profile>
<!-- Simulator profile -->
<profile>
<id>simulator</id>
<activation>
<property><name>deploydb-simulator</name></property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<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>
<!-- Simulator profile -->
<profile>
<id>simulator</id>
<activation>
<property>
<name>deploydb-simulator</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<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>
<goals>
<goal>execute</goal>
@ -575,12 +562,12 @@
<configuration>
<username>root</username>
<password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>drop database if exists `simulator`</sqlCommand>
</configuration>
</execution>
<execution>
<id>create-database</id>
<url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>drop database if exists `simulator`</sqlCommand>
</configuration>
</execution>
<execution>
<id>create-database</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
@ -588,51 +575,51 @@
<configuration>
<username>root</username>
<password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>create database `simulator`</sqlCommand>
</configuration>
</execution>
<execution>
<id>grant-user-cloud</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<username>root</username>
<password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`localhost` identified by
'${db.simulator.password}';</sqlCommand>
</configuration>
</execution>
<execution>
<id>grant-user-cloud-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.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`%` identified by
'${db.simulator.password}';</sqlCommand>
</configuration>
</execution>
<execution>
<id>create-schema</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<srcFiles>
<srcFile>${basedir}/target/db/create-schema-simulator.sql</srcFile>
<srcFile>${basedir}/target/db/templates.simulator.sql</srcFile>
</srcFiles>
<url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>create database `simulator`</sqlCommand>
</configuration>
</execution>
<execution>
<id>grant-user-cloud</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<username>root</username>
<password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`localhost` identified by
'${db.simulator.password}';</sqlCommand>
</configuration>
</execution>
<execution>
<id>grant-user-cloud-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.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`%` identified by
'${db.simulator.password}';</sqlCommand>
</configuration>
</execution>
<execution>
<id>create-schema</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<srcFiles>
<srcFile>${basedir}/target/db/create-schema-simulator.sql</srcFile>
<srcFile>${basedir}/target/db/templates.simulator.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>

View File

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

View File

@ -21,8 +21,6 @@ package org.apache.cloudstack.engine.service.api;
import java.util.List;
import java.util.Map;
import javax.ws.rs.POST;
import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity;
import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity;
import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity;
@ -42,10 +40,8 @@ public interface ProvisioningService {
StorageEntity registerStorage(String name, List<String> tags, Map<String, String> details);
@POST
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);
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;
}
public String getOwner() {
return owner;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getSpeed() {
return speed;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public List<String> getComputeTags() {
return computeTags;
}
public List<String> getComputeTags() {
return computeTags;
}
public void setComputeTags(List<String> computeTags) {
this.computeTags = computeTags;
}
public void setComputeTags(List<String> computeTags) {
this.computeTags = computeTags;
}
public List<String> getRootDiskTags() {
return rootDiskTags;
}
public List<String> getRootDiskTags() {
return rootDiskTags;
}
public void setRootDiskTags(List<String> rootDiskTags) {
this.rootDiskTags = rootDiskTags;
}
public void setRootDiskTags(List<String> rootDiskTags) {
this.rootDiskTags = rootDiskTags;
}
public String getHostname() {
return hostname;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getDisplayname() {
return displayname;
}
public String getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public List<String> getNetworkIds() {
return networkIds;
}
public List<String> getNetworkIds() {
return networkIds;
}
public void setNetworkIds(List<String> networkIds) {
this.networkIds = networkIds;
}
public void setNetworkIds(List<String> 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.TemporalType;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event;
import com.cloud.api.Identity;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.org.Cluster;
import com.cloud.org.Managed.ManagedState;
import com.cloud.org.Grouping;
import com.cloud.org.Managed.ManagedState;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.StateMachine;
@ -104,56 +104,63 @@ public class ClusterVO implements Cluster, Identity {
public ClusterVO() {
clusterType = Cluster.ClusterType.CloudManaged;
allocationState = Grouping.AllocationState.Enabled;
clusterType = Cluster.ClusterType.CloudManaged;
allocationState = Grouping.AllocationState.Enabled;
this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled;
this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled;
}
public ClusterVO(long dataCenterId, long podId, String name) {
this.dataCenterId = dataCenterId;
this.podId = podId;
this.name = name;
this.clusterType = Cluster.ClusterType.CloudManaged;
this.allocationState = Grouping.AllocationState.Enabled;
this.managedState = ManagedState.Managed;
this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled;
this.clusterType = Cluster.ClusterType.CloudManaged;
this.allocationState = Grouping.AllocationState.Enabled;
this.managedState = ManagedState.Managed;
this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled;
}
@Override
public long getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public long getDataCenterId() {
return dataCenterId;
}
@Override
public long getPodId() {
return podId;
}
@Override
public Cluster.ClusterType getClusterType() {
return clusterType;
return clusterType;
}
public void setClusterType(Cluster.ClusterType clusterType) {
this.clusterType = clusterType;
this.clusterType = clusterType;
}
@Override
public AllocationState getAllocationState() {
return allocationState;
return allocationState;
}
public void setAllocationState(AllocationState allocationState) {
this.allocationState = allocationState;
this.allocationState = allocationState;
}
@Override
public ManagedState getManagedState() {
return managedState;
}
@ -180,12 +187,13 @@ public class ClusterVO implements Cluster, Identity {
return this.id == that.id;
}
@Override
public HypervisorType getHypervisorType() {
return HypervisorType.getType(hypervisorType);
return HypervisorType.getType(hypervisorType);
}
public void setHypervisorType(String hy) {
hypervisorType = hy;
public void setHypervisorType(String hy) {
hypervisorType = hy;
}
public String getGuid() {
@ -206,30 +214,30 @@ public class ClusterVO implements Cluster, Identity {
@Override
public String getUuid() {
return this.uuid;
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
this.uuid = uuid;
}
public String getOwner() {
return owner;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getCreated() {
return created;
}
public Date getCreated() {
return created;
}
public Date getLastUpdated() {
return lastUpdated;
}
public Date getLastUpdated() {
return lastUpdated;
}
public State getState() {
return state;
}
public State getState() {
return state;
}
}

View File

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

View File

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

View File

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

View File

@ -29,14 +29,12 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.storage.image.format.ISO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.BaseCmd;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.DomainVO;
@ -48,9 +46,9 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.VMTemplateDaoImpl;
import com.cloud.storage.dao.VMTemplateDetailsDao;
import com.cloud.storage.dao.VMTemplateZoneDao;
@ -59,8 +57,6 @@ import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentInject;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase;
@ -68,8 +64,8 @@ import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
@ -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
// revisit post 2.2RC2
if (isIso && templateZonePairList.size() < (pageSize != null ? pageSize : 500) && templateFilter != TemplateFilter.community
&& !(templateFilter == TemplateFilter.self && !BaseCmd.isRootAdmin(caller.getType()))) { // evaluates
// to
// true
// If
// root
// admin
// and
// filter=self
if (isIso &&
templateZonePairList.size() < (pageSize != null ? pageSize : 500) &&
templateFilter != TemplateFilter.community &&
!(templateFilter == TemplateFilter.self) /* TODO: Fix this! && !BaseCmd.isRootAdmin(caller.getType())*/) { // evaluates
// to
// true
// If
// root
// admin
// and
// filter=self
List<ImageDataVO> publicIsos = publicIsoSearch(bootable, false, tags);
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) {
SearchCriteria<ImageDataVO> sc = tmpltTypeHyperSearch.create();
sc.setParameters("templateType", Storage.TemplateType.SYSTEM);

View File

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

View File

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

View File

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

View File

@ -21,22 +21,23 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.APIAccessChecker;
import org.apache.log4j.Logger;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.PluggableService;
@ -60,6 +61,7 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
private static List<String> s_allCommands = null;
protected @Inject AccountManager _accountMgr;
@Inject protected List<PluggableService> _services;
protected StaticRoleBasedAPIAccessChecker() {
super();
@ -77,10 +79,10 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
boolean commandExists = s_allCommands.contains(apiCommandName);
if(commandExists && user != null){
Long accountId = user.getAccountId();
Account userAccount = _accountMgr.getAccount(accountId);
short accountType = userAccount.getType();
return isCommandAvailableForAccount(accountType, apiCommandName);
Long accountId = user.getAccountId();
Account userAccount = _accountMgr.getAccount(accountId);
short accountType = userAccount.getType();
return isCommandAvailableForAccount(accountType, apiCommandName);
}
return commandExists;
@ -109,13 +111,8 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
// Read command properties files to build the static map per role.
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
List<PluggableService> services = locator.getAllPluggableServices();
services.add((PluggableService) ComponentLocator.getComponent(ManagementServer.Name));
List<String> configFiles = new ArrayList<String>();
for (PluggableService service : services) {
for (PluggableService service : _services) {
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.SearchResult;
import org.apache.cloudstack.api.ApiConstants.LDAPParams;
import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.ApiConstants.LDAPParams;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.server.ManagementServer;
import com.cloud.user.UserAccount;
@ -81,7 +82,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
String protocol = "ldap://" ;
if (new Boolean(useSSL)){
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.SECURITY_PROTOCOL, "ssl");
protocol="ldaps://" ;
System.setProperty("javax.net.ssl.trustStore", trustStore);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
@ -93,10 +94,10 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.SECURITY_CREDENTIALS, bindPasswd);
}
else {
// Use anonymous authentication
env.put(Context.SECURITY_AUTHENTICATION, "none");
// Use anonymous authentication
env.put(Context.SECURITY_AUTHENTICATION, "none");
}
// Create the initial context
// Create the initial context
DirContext ctx = new InitialDirContext(env);
// use this context to search
@ -115,7 +116,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
// Search for objects with those matching attributes
NamingEnumeration<SearchResult> answer = ctx.search(searchBase, queryFilter, sc);
SearchResult sr = (SearchResult)answer.next();
SearchResult sr = answer.next();
String cn = sr.getName();
answer.close();
ctx.close();
@ -127,7 +128,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
protocol = "ldap://" ;
if (new Boolean(useSSL)){
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.SECURITY_PROTOCOL, "ssl");
protocol="ldaps://" ;
}
env.put(Context.PROVIDER_URL, protocol + url + ":" + port);
@ -143,7 +144,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return false;
}
catch (Exception e){
e.printStackTrace();
e.printStackTrace();
s_logger.warn("Unknown error encountered " + e.getMessage());
return false;
}
@ -152,6 +153,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
super.configure(name, params);
@ -161,16 +163,16 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return true;
}
@Override
public String encode(String password) {
// Password is not used, so set to a random string
try {
SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
byte bytes[] = new byte[20];
randomGen.nextBytes(bytes);
return Base64.encode(bytes).toString();
} catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Failed to generate random password",e);
}
}
@Override
public String encode(String password) {
// Password is not used, so set to a random string
try {
SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
byte bytes[] = new byte[20];
randomGen.nextBytes(bytes);
return Base64.encode(bytes).toString();
} catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Failed to generate random password",e);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,6 +16,35 @@
// under the License.
package com.cloud.server;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.inject.Inject;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.Resource;
@ -45,7 +74,11 @@ import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.guru.*;
import com.cloud.network.guru.ControlNetworkGuru;
import com.cloud.network.guru.DirectPodBasedNetworkGuru;
import com.cloud.network.guru.PodBasedNetworkGuru;
import com.cloud.network.guru.PublicNetworkGuru;
import com.cloud.network.guru.StorageNetworkGuru;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.Availability;
import com.cloud.offerings.NetworkOfferingServiceMapVO;
@ -63,7 +96,6 @@ import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
@ -71,20 +103,6 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script;
import com.cloud.uuididentity.dao.IdentityDao;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;
@Component
public class ConfigurationServerImpl implements ConfigurationServer {
@ -506,26 +524,26 @@ public class ConfigurationServerImpl implements ConfigurationServer {
}
if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) {
return;
return;
}
String already = _configDao.getValue("system.vm.password");
if (already == null) {
Transaction txn = Transaction.currentTxn();
try {
String rpassword = PasswordGenerator.generatePresharedKey(8);
String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) "
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')";
PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql);
stmt.executeUpdate(wSql);
s_logger.info("Updated systemvm password in database");
} catch (SQLException e) {
s_logger.error("Cannot retrieve systemvm password", e);
}
}
String already = _configDao.getValue("system.vm.password");
if (already == null) {
Transaction txn = Transaction.currentTxn();
try {
String rpassword = PasswordGenerator.generatePresharedKey(8);
String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) "
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')";
PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql);
stmt.executeUpdate(wSql);
s_logger.info("Updated systemvm password in database");
} catch (SQLException e) {
s_logger.error("Cannot retrieve systemvm password", e);
}
}
}
}
@Override
@DB
@ -541,7 +559,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String already = _configDao.getValue("ssh.privatekey");
String homeDir = null;
homeDir = Script.runSimpleBashScript("echo ~" + username);
if (homeDir == null) {
if (homeDir == null) {
throw new CloudRuntimeException("Cannot get home directory for account: " + username);
}
@ -622,11 +640,11 @@ public class ConfigurationServerImpl implements ConfigurationServer {
}
s_logger.info("Going to update systemvm iso with generated keypairs if needed");
try {
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
} catch (CloudRuntimeException e) {
if (!devel) {
throw new CloudRuntimeException(e.getMessage());
}
if (!devel) {
throw new CloudRuntimeException(e.getMessage());
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -23,7 +23,8 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.api.IdentityService;
import com.cloud.utils.component.Inject;
import org.springframework.stereotype.Component;
import com.cloud.utils.component.Manager;
import com.cloud.uuididentity.dao.IdentityDao;
@ -32,36 +33,38 @@ import com.cloud.uuididentity.dao.IdentityDao;
public class IdentityServiceImpl implements Manager, IdentityService {
private String _name;
@Inject private IdentityDao _identityDao;
@Inject private IdentityDao _identityDao;
@Override
public Long getIdentityId(String tableName, String identityString) {
return _identityDao.getIdentityId(tableName, identityString);
return _identityDao.getIdentityId(tableName, identityString);
}
public String getIdentityUuid(String tableName, String identityString) {
return _identityDao.getIdentityUuid(tableName, identityString);
}
@Override
public String getIdentityUuid(String tableName, String identityString) {
return _identityDao.getIdentityUuid(tableName, identityString);
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = name;
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = name;
return true;
}
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public boolean stop() {
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`.`counter`;
DROP TABLE IF EXISTS `cloud`.`conditions`;
DROP TABLE IF EXISTS `cloud`.`inline_load_balancer_nic_map`;
CREATE TABLE `cloud`.`version` (
`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id',

View File

@ -16,7 +16,7 @@
// under the License.
package com.cloud.utils;
import static java.util.Arrays.*;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.Iterator;
@ -151,4 +151,17 @@ public class StringUtils {
}
public static int formatForOutput(String text, int start, int columns, char separator) {
if (start >= text.length()) {
return -1;
}
int end = start + columns;
if (end > text.length()) {
end = text.length();
}
String searchable = text.substring(start, end);
int found = searchable.lastIndexOf(separator);
return found > 0 ? found : end - start;
}
}