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

@ -1,4 +1,4 @@
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. The ASF licenses this file to information regarding copyright ownership. The ASF licenses this file to
you under the Apache License, Version 2.0 (the "License"); you may not use you under the Apache License, Version 2.0 (the "License"); you may not use
@ -430,21 +430,6 @@
'${db.cloud.password}';</sqlCommand> '${db.cloud.password}';</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>grant-user-cloud-usage-all</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<username>root</username>
<password>${db.root.password}</password>
<url>jdbc:mysql://${db.cloud.host}:${db.cloud.port}</url>
<sqlCommand>GRANT ALL ON cloud_usage.* to
${db.cloud.username}@`%` identified by
'${db.cloud.password}';</sqlCommand>
</configuration>
</execution>
<execution> <execution>
<id>grant-user-cloud-bridge</id> <id>grant-user-cloud-bridge</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
@ -507,9 +492,9 @@
</goals> </goals>
<configuration> <configuration>
<autocommit>true</autocommit> <autocommit>true</autocommit>
<srcFiles> <srcFiles>
<srcFile>${basedir}/developer-prefill.sql</srcFile> <srcFile>${basedir}/developer-prefill.sql</srcFile>
</srcFiles> </srcFiles>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
@ -518,56 +503,58 @@
</build> </build>
</profile> </profile>
<!-- Simulator profile --> <!-- Simulator profile -->
<profile> <profile>
<id>simulator</id> <id>simulator</id>
<activation> <activation>
<property><name>deploydb-simulator</name></property> <property>
</activation> <name>deploydb-simulator</name>
<build> </property>
<plugins> </activation>
<plugin> <build>
<groupId>org.codehaus.mojo</groupId> <plugins>
<artifactId>properties-maven-plugin</artifactId> <plugin>
<version>1.0-alpha-2</version> <groupId>org.codehaus.mojo</groupId>
<executions> <artifactId>properties-maven-plugin</artifactId>
<execution> <version>1.0-alpha-2</version>
<phase>initialize</phase> <executions>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${project.parent.basedir}/utils/conf/db.properties</file>
<file>${project.parent.basedir}/utils/conf/db.properties.override</file>
</files>
<quiet>true</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${cs.mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<driver>org.gjt.mm.mysql.Driver</driver>
<url>jdbc:mysql://${db.simulator.host}:3306/simulator</url>
<username>${db.simulator.username}</username>
<password>${db.simulator.password}</password>
<skip>${maven.test.skip}</skip>
<forceMojoExecution>true</forceMojoExecution>
</configuration>
<executions>
<execution> <execution>
<id>drop-database</id> <phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${project.parent.basedir}/utils/conf/db.properties</file>
<file>${project.parent.basedir}/utils/conf/db.properties.override</file>
</files>
<quiet>true</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${cs.mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<driver>org.gjt.mm.mysql.Driver</driver>
<url>jdbc:mysql://${db.simulator.host}:3306/simulator</url>
<username>${db.simulator.username}</username>
<password>${db.simulator.password}</password>
<skip>${maven.test.skip}</skip>
<forceMojoExecution>true</forceMojoExecution>
</configuration>
<executions>
<execution>
<id>drop-database</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
@ -575,12 +562,12 @@
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>drop database if exists `simulator`</sqlCommand> <sqlCommand>drop database if exists `simulator`</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>create-database</id> <id>create-database</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
@ -588,51 +575,51 @@
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>create database `simulator`</sqlCommand> <sqlCommand>create database `simulator`</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>grant-user-cloud</id> <id>grant-user-cloud</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to <sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`localhost` identified by ${db.simulator.username}@`localhost` identified by
'${db.simulator.password}';</sqlCommand> '${db.simulator.password}';</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>grant-user-cloud-all</id> <id>grant-user-cloud-all</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<username>root</username> <username>root</username>
<password>${db.root.password}</password> <password>${db.root.password}</password>
<url>jdbc:mysql://${db.simulator.host}:3306</url> <url>jdbc:mysql://${db.simulator.host}:3306</url>
<sqlCommand>GRANT ALL ON simulator.* to <sqlCommand>GRANT ALL ON simulator.* to
${db.simulator.username}@`%` identified by ${db.simulator.username}@`%` identified by
'${db.simulator.password}';</sqlCommand> '${db.simulator.password}';</sqlCommand>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>create-schema</id> <id>create-schema</id>
<phase>process-test-resources</phase> <phase>process-test-resources</phase>
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<srcFiles> <srcFiles>
<srcFile>${basedir}/target/db/create-schema-simulator.sql</srcFile> <srcFile>${basedir}/target/db/create-schema-simulator.sql</srcFile>
<srcFile>${basedir}/target/db/templates.simulator.sql</srcFile> <srcFile>${basedir}/target/db/templates.simulator.sql</srcFile>
</srcFiles> </srcFiles>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>

View File

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

View File

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

View File

@ -159,30 +159,30 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject<State, Virt
@Column(name="uuid") @Column(name="uuid")
protected String uuid = UUID.randomUUID().toString(); protected String uuid = UUID.randomUUID().toString();
//orchestration columns //orchestration columns
@Column(name="owner") @Column(name="owner")
private String owner = null; private String owner = null;
@Column(name="speed") @Column(name="speed")
private int speed; private int speed;
@Transient @Transient
List<String> computeTags; List<String> computeTags;
@Transient @Transient
List<String> rootDiskTags; List<String> rootDiskTags;
@Column(name="hostname") @Column(name="hostname")
private String hostname = null; private String hostname = null;
@Column(name="displayname") @Column(name="displayname")
private String displayname = null; private String displayname = null;
@Transient @Transient
List<String> networkIds; List<String> networkIds;
public VMEntityVO(long id, public VMEntityVO(long id,
long serviceOfferingId, long serviceOfferingId,
String name, String name,
@ -227,8 +227,8 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject<State, Virt
this(id, serviceOfferingId, name, instanceName, type, vmTemplateId, hypervisorType, guestOSId, domainId, accountId, haEnabled); this(id, serviceOfferingId, name, instanceName, type, vmTemplateId, hypervisorType, guestOSId, domainId, accountId, haEnabled);
this.limitCpuUse = limitResourceUse; this.limitCpuUse = limitResourceUse;
} }
protected VMEntityVO() { protected VMEntityVO() {
} }
@ -501,60 +501,66 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject<State, Virt
this.serviceOfferingId = serviceOfferingId; this.serviceOfferingId = serviceOfferingId;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public int getSpeed() { public int getSpeed() {
return speed; return speed;
} }
public void setSpeed(int speed) { public void setSpeed(int speed) {
this.speed = speed; this.speed = speed;
} }
public List<String> getComputeTags() { public List<String> getComputeTags() {
return computeTags; return computeTags;
} }
public void setComputeTags(List<String> computeTags) { public void setComputeTags(List<String> computeTags) {
this.computeTags = computeTags; this.computeTags = computeTags;
} }
public List<String> getRootDiskTags() { public List<String> getRootDiskTags() {
return rootDiskTags; return rootDiskTags;
} }
public void setRootDiskTags(List<String> rootDiskTags) { public void setRootDiskTags(List<String> rootDiskTags) {
this.rootDiskTags = rootDiskTags; this.rootDiskTags = rootDiskTags;
} }
public String getHostname() { public String getHostname() {
return hostname; return hostname;
} }
public void setHostname(String hostname) { public void setHostname(String hostname) {
this.hostname = hostname; this.hostname = hostname;
} }
public String getDisplayname() { public String getDisplayname() {
return displayname; return displayname;
} }
public void setDisplayname(String displayname) { public void setDisplayname(String displayname) {
this.displayname = displayname; this.displayname = displayname;
} }
public List<String> getNetworkIds() { public List<String> getNetworkIds() {
return networkIds; return networkIds;
} }
public void setNetworkIds(List<String> networkIds) { public void setNetworkIds(List<String> networkIds) {
this.networkIds = networkIds; this.networkIds = networkIds;
} }
@Override
public long getDiskOfferingId() {
// TODO Auto-generated method stub
return 0;
}
} }

View File

@ -26,14 +26,14 @@ import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event;
import com.cloud.api.Identity;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.org.Cluster; import com.cloud.org.Cluster;
import com.cloud.org.Managed.ManagedState;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
import com.cloud.org.Managed.ManagedState;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.StateMachine; import com.cloud.utils.db.StateMachine;
@ -46,52 +46,52 @@ public class ClusterVO implements Cluster, Identity {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") @Column(name="id")
long id; long id;
@Column(name="name") @Column(name="name")
String name; String name;
@Column(name="guid") @Column(name="guid")
String guid; String guid;
@Column(name="data_center_id") @Column(name="data_center_id")
long dataCenterId; long dataCenterId;
@Column(name="pod_id") @Column(name="pod_id")
long podId; long podId;
@Column(name="hypervisor_type") @Column(name="hypervisor_type")
String hypervisorType; String hypervisorType;
@Column(name="cluster_type") @Column(name="cluster_type")
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
Cluster.ClusterType clusterType; Cluster.ClusterType clusterType;
@Column(name="allocation_state") @Column(name="allocation_state")
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
AllocationState allocationState; AllocationState allocationState;
@Column(name="managed_state") @Column(name="managed_state")
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
ManagedState managedState; ManagedState managedState;
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name=GenericDao.REMOVED_COLUMN)
private Date removed; private Date removed;
@Column(name="uuid") @Column(name="uuid")
String uuid; String uuid;
//orchestration //orchestration
@Column(name="owner") @Column(name="owner")
private String owner = null; private String owner = null;
@Column(name=GenericDao.CREATED_COLUMN) @Column(name=GenericDao.CREATED_COLUMN)
protected Date created; protected Date created;
@Column(name="lastUpdated", updatable=true) @Column(name="lastUpdated", updatable=true)
@Temporal(value=TemporalType.TIMESTAMP) @Temporal(value=TemporalType.TIMESTAMP)
protected Date lastUpdated; protected Date lastUpdated;
/** /**
* Note that state is intentionally missing the setter. Any updates to * Note that state is intentionally missing the setter. Any updates to
* the state machine needs to go through the DAO object because someone * the state machine needs to go through the DAO object because someone
@ -101,59 +101,66 @@ public class ClusterVO implements Cluster, Identity {
@StateMachine(state=State.class, event=Event.class) @StateMachine(state=State.class, event=Event.class)
@Column(name="state", updatable=true, nullable=false, length=32) @Column(name="state", updatable=true, nullable=false, length=32)
protected State state = null; protected State state = null;
public ClusterVO() { public ClusterVO() {
clusterType = Cluster.ClusterType.CloudManaged; clusterType = Cluster.ClusterType.CloudManaged;
allocationState = Grouping.AllocationState.Enabled; allocationState = Grouping.AllocationState.Enabled;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled; this.state = State.Disabled;
} }
public ClusterVO(long dataCenterId, long podId, String name) { public ClusterVO(long dataCenterId, long podId, String name) {
this.dataCenterId = dataCenterId; this.dataCenterId = dataCenterId;
this.podId = podId; this.podId = podId;
this.name = name; this.name = name;
this.clusterType = Cluster.ClusterType.CloudManaged; this.clusterType = Cluster.ClusterType.CloudManaged;
this.allocationState = Grouping.AllocationState.Enabled; this.allocationState = Grouping.AllocationState.Enabled;
this.managedState = ManagedState.Managed; this.managedState = ManagedState.Managed;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled; this.state = State.Disabled;
} }
@Override
public long getId() { public long getId() {
return id; return id;
} }
@Override
public String getName() { public String getName() {
return name; return name;
} }
@Override
public long getDataCenterId() { public long getDataCenterId() {
return dataCenterId; return dataCenterId;
} }
@Override
public long getPodId() { public long getPodId() {
return podId; return podId;
} }
@Override
public Cluster.ClusterType getClusterType() { public Cluster.ClusterType getClusterType() {
return clusterType; return clusterType;
} }
public void setClusterType(Cluster.ClusterType clusterType) { public void setClusterType(Cluster.ClusterType clusterType) {
this.clusterType = clusterType; this.clusterType = clusterType;
} }
@Override
public AllocationState getAllocationState() { public AllocationState getAllocationState() {
return allocationState; return allocationState;
} }
public void setAllocationState(AllocationState allocationState) { public void setAllocationState(AllocationState allocationState) {
this.allocationState = allocationState; this.allocationState = allocationState;
} }
@Override
public ManagedState getManagedState() { public ManagedState getManagedState() {
return managedState; return managedState;
} }
@ -170,7 +177,7 @@ public class ClusterVO implements Cluster, Identity {
public int hashCode() { public int hashCode() {
return NumbersUtil.hash(id); return NumbersUtil.hash(id);
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof ClusterVO)) { if (!(obj instanceof ClusterVO)) {
@ -179,19 +186,20 @@ public class ClusterVO implements Cluster, Identity {
ClusterVO that = (ClusterVO)obj; ClusterVO that = (ClusterVO)obj;
return this.id == that.id; return this.id == that.id;
} }
@Override
public HypervisorType getHypervisorType() { public HypervisorType getHypervisorType() {
return HypervisorType.getType(hypervisorType); return HypervisorType.getType(hypervisorType);
} }
public void setHypervisorType(String hy) { public void setHypervisorType(String hy) {
hypervisorType = hy; hypervisorType = hy;
} }
public String getGuid() { public String getGuid() {
return guid; return guid;
} }
public void setGuid(String guid) { public void setGuid(String guid) {
this.guid = guid; this.guid = guid;
} }
@ -203,33 +211,33 @@ public class ClusterVO implements Cluster, Identity {
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public String getOwner() {
return owner;
}
public void setOwner(String owner) { public String getOwner() {
this.owner = owner; return owner;
} }
public Date getCreated() { public void setOwner(String owner) {
return created; this.owner = owner;
} }
public Date getLastUpdated() { public Date getCreated() {
return lastUpdated; return created;
} }
public State getState() { public Date getLastUpdated() {
return state; return lastUpdated;
} }
public State getState() {
return state;
}
} }

View File

@ -29,10 +29,10 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event;
import com.cloud.api.Identity;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
@ -43,107 +43,107 @@ import com.cloud.utils.db.StateMachine;
@Entity @Entity
@Table(name="data_center") @Table(name="data_center")
public class DataCenterVO implements DataCenter, Identity { public class DataCenterVO implements DataCenter, Identity {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id") @Column(name="id")
private long id; private long id;
@Column(name="name") @Column(name="name")
private String name = null; private String name = null;
@Column(name="description") @Column(name="description")
private String description = null; private String description = null;
@Column(name="dns1") @Column(name="dns1")
private String dns1 = null; private String dns1 = null;
@Column(name="dns2") @Column(name="dns2")
private String dns2 = null; private String dns2 = null;
@Column(name="internal_dns1") @Column(name="internal_dns1")
private String internalDns1 = null; private String internalDns1 = null;
@Column(name="internal_dns2") @Column(name="internal_dns2")
private String internalDns2 = null; private String internalDns2 = null;
@Column(name="router_mac_address", updatable = false, nullable=false) @Column(name="router_mac_address", updatable = false, nullable=false)
private String routerMacAddress = "02:00:00:00:00:01"; private String routerMacAddress = "02:00:00:00:00:01";
@Column(name="guest_network_cidr") @Column(name="guest_network_cidr")
private String guestNetworkCidr = null; private String guestNetworkCidr = null;
@Column(name="domain_id") @Column(name="domain_id")
private Long domainId = null; private Long domainId = null;
@Column(name="domain") @Column(name="domain")
private String domain; private String domain;
@Column(name="networktype") @Column(name="networktype")
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
NetworkType networkType; NetworkType networkType;
@Column(name="dns_provider") @Column(name="dns_provider")
private String dnsProvider; private String dnsProvider;
@Column(name="dhcp_provider") @Column(name="dhcp_provider")
private String dhcpProvider; private String dhcpProvider;
@Column(name="gateway_provider") @Column(name="gateway_provider")
private String gatewayProvider; private String gatewayProvider;
@Column(name="vpn_provider") @Column(name="vpn_provider")
private String vpnProvider; private String vpnProvider;
@Column(name="userdata_provider") @Column(name="userdata_provider")
private String userDataProvider; private String userDataProvider;
@Column(name="lb_provider") @Column(name="lb_provider")
private String loadBalancerProvider; private String loadBalancerProvider;
@Column(name="firewall_provider") @Column(name="firewall_provider")
private String firewallProvider; private String firewallProvider;
@Column(name="mac_address", nullable=false) @Column(name="mac_address", nullable=false)
@TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1) @TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1)
private long macAddress = 1; private long macAddress = 1;
@Column(name="zone_token") @Column(name="zone_token")
private String zoneToken; private String zoneToken;
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name=GenericDao.REMOVED_COLUMN)
private Date removed; private Date removed;
// This is a delayed load value. If the value is null, // This is a delayed load value. If the value is null,
// then this field has not been loaded yet. // then this field has not been loaded yet.
// Call the dao to load it. // Call the dao to load it.
@Transient @Transient
Map<String, String> details; Map<String, String> details;
@Column(name="allocation_state") @Column(name="allocation_state")
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
AllocationState allocationState; AllocationState allocationState;
@Column(name="uuid") @Column(name="uuid")
private String uuid; private String uuid;
@Column(name="is_security_group_enabled") @Column(name="is_security_group_enabled")
boolean securityGroupEnabled; boolean securityGroupEnabled;
@Column(name="is_local_storage_enabled") @Column(name="is_local_storage_enabled")
boolean localStorageEnabled; boolean localStorageEnabled;
//orchestration //orchestration
@Column(name="owner") @Column(name="owner")
private String owner = null; private String owner = null;
@Column(name=GenericDao.CREATED_COLUMN) @Column(name=GenericDao.CREATED_COLUMN)
protected Date created; protected Date created;
@Column(name="lastUpdated", updatable=true) @Column(name="lastUpdated", updatable=true)
@Temporal(value=TemporalType.TIMESTAMP) @Temporal(value=TemporalType.TIMESTAMP)
protected Date lastUpdated; protected Date lastUpdated;
/** /**
* Note that state is intentionally missing the setter. Any updates to * Note that state is intentionally missing the setter. Any updates to
* the state machine needs to go through the DAO object because someone * the state machine needs to go through the DAO object because someone
@ -199,13 +199,13 @@ public class DataCenterVO implements DataCenter, Identity {
public void setFirewallProvider(String firewallProvider) { public void setFirewallProvider(String firewallProvider) {
this.firewallProvider = firewallProvider; this.firewallProvider = firewallProvider;
} }
public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) {
this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false); this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false);
this.id = id; this.id = id;
this.allocationState = Grouping.AllocationState.Enabled; this.allocationState = Grouping.AllocationState.Enabled;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
} }
public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled, boolean localStorageEnabled) { public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled, boolean localStorageEnabled) {
this.name = name; this.name = name;
@ -221,7 +221,7 @@ public class DataCenterVO implements DataCenter, Identity {
this.allocationState = Grouping.AllocationState.Enabled; this.allocationState = Grouping.AllocationState.Enabled;
this.securityGroupEnabled = securityGroupEnabled; this.securityGroupEnabled = securityGroupEnabled;
this.localStorageEnabled = localStorageEnabled; this.localStorageEnabled = localStorageEnabled;
if (zoneType == NetworkType.Advanced) { if (zoneType == NetworkType.Advanced) {
loadBalancerProvider = Provider.VirtualRouter.getName(); loadBalancerProvider = Provider.VirtualRouter.getName();
firewallProvider = Provider.VirtualRouter.getName(); firewallProvider = Provider.VirtualRouter.getName();
@ -242,7 +242,7 @@ public class DataCenterVO implements DataCenter, Identity {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
this.state = State.Disabled; this.state = State.Disabled;
} }
@Override @Override
public String getVpnProvider() { public String getVpnProvider() {
return vpnProvider; return vpnProvider;
@ -260,27 +260,27 @@ public class DataCenterVO implements DataCenter, Identity {
public void setUserDataProvider(String userDataProvider) { public void setUserDataProvider(String userDataProvider) {
this.userDataProvider = userDataProvider; this.userDataProvider = userDataProvider;
} }
@Override @Override
public String getGuestNetworkCidr() public String getGuestNetworkCidr()
{ {
return guestNetworkCidr; return guestNetworkCidr;
} }
public void setGuestNetworkCidr(String guestNetworkCidr) public void setGuestNetworkCidr(String guestNetworkCidr)
{ {
this.guestNetworkCidr = guestNetworkCidr; this.guestNetworkCidr = guestNetworkCidr;
} }
@Override @Override
public Long getDomainId() { public Long getDomainId() {
return domainId; return domainId;
} }
public void setDomainId(Long domainId) { public void setDomainId(Long domainId) {
this.domainId = domainId; this.domainId = domainId;
} }
@Override @Override
public String getDescription() { public String getDescription() {
return description; return description;
@ -289,12 +289,12 @@ public class DataCenterVO implements DataCenter, Identity {
public String getRouterMacAddress() { public String getRouterMacAddress() {
return routerMacAddress; return routerMacAddress;
} }
@Override @Override
public String getDns1() { public String getDns1() {
return dns1; return dns1;
} }
@Override @Override
public String getDns2() { public String getDns2() {
return dns2; return dns2;
@ -310,43 +310,43 @@ public class DataCenterVO implements DataCenter, Identity {
return internalDns2; return internalDns2;
} }
protected DataCenterVO() { protected DataCenterVO() {
} }
@Override @Override
public long getId() { public long getId() {
return id; return id;
} }
@Override @Override
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public void setDns1(String dns1) { public void setDns1(String dns1) {
this.dns1 = dns1; this.dns1 = dns1;
} }
public void setDns2(String dns2) { public void setDns2(String dns2) {
this.dns2 = dns2; this.dns2 = dns2;
} }
public void setInternalDns1(String dns3) { public void setInternalDns1(String dns3) {
this.internalDns1 = dns3; this.internalDns1 = dns3;
} }
public void setInternalDns2(String dns4) { public void setInternalDns2(String dns4) {
this.internalDns2 = dns4; this.internalDns2 = dns4;
} }
public void setRouterMacAddress(String routerMacAddress) { public void setRouterMacAddress(String routerMacAddress) {
this.routerMacAddress = routerMacAddress; this.routerMacAddress = routerMacAddress;
} }
@Override @Override
public String getDomain() { public String getDomain() {
return domain; return domain;
@ -355,7 +355,7 @@ public class DataCenterVO implements DataCenter, Identity {
public void setDomain(String domain) { public void setDomain(String domain) {
this.domain = domain; this.domain = domain;
} }
public void setNetworkType(NetworkType zoneNetworkType) { public void setNetworkType(NetworkType zoneNetworkType) {
this.networkType = zoneNetworkType; this.networkType = zoneNetworkType;
} }
@ -364,16 +364,16 @@ public class DataCenterVO implements DataCenter, Identity {
public NetworkType getNetworkType() { public NetworkType getNetworkType() {
return networkType; return networkType;
} }
@Override @Override
public boolean isSecurityGroupEnabled() { public boolean isSecurityGroupEnabled() {
return securityGroupEnabled; return securityGroupEnabled;
} }
public void setSecurityGroupEnabled(boolean enabled) { public void setSecurityGroupEnabled(boolean enabled) {
this.securityGroupEnabled = enabled; this.securityGroupEnabled = enabled;
} }
@Override @Override
public boolean isLocalStorageEnabled() { public boolean isLocalStorageEnabled() {
return localStorageEnabled; return localStorageEnabled;
@ -392,32 +392,33 @@ public class DataCenterVO implements DataCenter, Identity {
public void setDetails(Map<String, String> details2) { public void setDetails(Map<String, String> details2) {
details = details2; details = details2;
} }
public String getDetail(String name) { public String getDetail(String name) {
assert (details != null) : "Did you forget to load the details?"; assert (details != null) : "Did you forget to load the details?";
return details != null ? details.get(name) : null; return details != null ? details.get(name) : null;
} }
public void setDetail(String name, String value) { public void setDetail(String name, String value) {
assert (details != null) : "Did you forget to load the details?"; assert (details != null) : "Did you forget to load the details?";
details.put(name, value); details.put(name, value);
} }
@Override
public AllocationState getAllocationState() { public AllocationState getAllocationState() {
return allocationState; return allocationState;
} }
public void setAllocationState(AllocationState allocationState) { public void setAllocationState(AllocationState allocationState) {
this.allocationState = allocationState; this.allocationState = allocationState;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return NumbersUtil.hash(id); return NumbersUtil.hash(id);
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof DataCenterVO)) { if (!(obj instanceof DataCenterVO)) {
@ -429,25 +430,25 @@ public class DataCenterVO implements DataCenter, Identity {
@Override @Override
public String getZoneToken() { public String getZoneToken() {
return zoneToken; return zoneToken;
} }
public void setZoneToken(String zoneToken) { public void setZoneToken(String zoneToken) {
this.zoneToken = zoneToken; this.zoneToken = zoneToken;
} }
public Date getRemoved() { public Date getRemoved() {
return removed; return removed;
} }
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public long getMacAddress() { public long getMacAddress() {
return macAddress; return macAddress;
@ -457,23 +458,23 @@ public class DataCenterVO implements DataCenter, Identity {
this.macAddress = macAddress; this.macAddress = macAddress;
} }
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
public void setOwner(String owner) { public void setOwner(String owner) {
this.owner = owner; this.owner = owner;
} }
public Date getCreated() { public Date getCreated() {
return created; return created;
} }
public Date getLastUpdated() { public Date getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public State getState() { public State getState() {
return state; return state;
} }
} }

View File

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

View File

@ -37,10 +37,10 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State;
import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event;
import com.cloud.api.Identity;
import com.cloud.host.Host; import com.cloud.host.Host;
import com.cloud.host.Status; import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
@ -134,20 +134,20 @@ public class HostVO implements Host, Identity {
@Column(name="setup") @Column(name="setup")
private boolean setup = false; private boolean setup = false;
@Column(name="resource_state", nullable=false) @Column(name="resource_state", nullable=false)
@Enumerated(value=EnumType.STRING) @Enumerated(value=EnumType.STRING)
private ResourceState resourceState; private ResourceState resourceState;
@Column(name="hypervisor_version") @Column(name="hypervisor_version")
private String hypervisorVersion; private String hypervisorVersion;
@Column(name="update_count", updatable = true, nullable=false) @Column(name="update_count", updatable = true, nullable=false)
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code. protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
@Column(name="uuid") @Column(name="uuid")
private String uuid; private String uuid;
// This is a delayed load value. If the value is null, // This is a delayed load value. If the value is null,
// then this field has not been loaded yet. // then this field has not been loaded yet.
// Call host dao to load it. // Call host dao to load it.
@ -367,15 +367,15 @@ public class HostVO implements Host, Identity {
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name=GenericDao.REMOVED_COLUMN)
private Date removed; private Date removed;
//orchestration //orchestration
@Column(name="owner") @Column(name="owner")
private String owner = null; private String owner = null;
@Column(name="lastUpdated", updatable=true) @Column(name="lastUpdated", updatable=true)
@Temporal(value=TemporalType.TIMESTAMP) @Temporal(value=TemporalType.TIMESTAMP)
protected Date lastUpdated; protected Date lastUpdated;
/** /**
* Note that state is intentionally missing the setter. Any updates to * Note that state is intentionally missing the setter. Any updates to
* the state machine needs to go through the DAO object because someone * the state machine needs to go through the DAO object because someone
@ -719,61 +719,61 @@ public class HostVO implements Host, Identity {
return hypervisorVersion; return hypervisorVersion;
} }
@Override @Override
// TODO, I tempoerary disable it as it breaks GenericSearchBuild when @Transient is applied // TODO, I tempoerary disable it as it breaks GenericSearchBuild when @Transient is applied
// @Transient // @Transient
public Status getState() { public Status getState() {
return status; return status;
} }
@Override @Override
public ResourceState getResourceState() { public ResourceState getResourceState() {
return resourceState; return resourceState;
} }
public void setResourceState(ResourceState state) { public void setResourceState(ResourceState state) {
resourceState = state; resourceState = state;
} }
@Override @Override
public boolean isInMaintenanceStates() { public boolean isInMaintenanceStates() {
return (getResourceState() == ResourceState.Maintenance || getResourceState() == ResourceState.ErrorInMaintenance return (getResourceState() == ResourceState.Maintenance || getResourceState() == ResourceState.ErrorInMaintenance
|| getResourceState() == ResourceState.PrepareForMaintenance); || getResourceState() == ResourceState.PrepareForMaintenance);
} }
public long getUpdated() { public long getUpdated() {
return updated; return updated;
} }
public long incrUpdated() {
updated++;
return updated;
}
@Override
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) { public long incrUpdated() {
this.owner = owner; updated++;
} return updated;
}
@Override
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getLastUpdated() { public Date getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public State getOrchestrationState() { public State getOrchestrationState() {
return state; return state;
} }
} }

View File

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

View File

@ -33,11 +33,12 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import com.cloud.api.Identity; import org.apache.cloudstack.api.Identity;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.Storage; import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Storage.TemplateType; import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateVO;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
@Entity @Entity
@ -77,7 +78,7 @@ public class ImageDataVO implements Identity {
@Temporal(value = TemporalType.TIMESTAMP) @Temporal(value = TemporalType.TIMESTAMP)
@Column(name = GenericDao.CREATED_COLUMN) @Column(name = GenericDao.CREATED_COLUMN)
private Date created = null; private final Date created = null;
@Column(name = GenericDao.REMOVED) @Column(name = GenericDao.REMOVED)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
@ -178,7 +179,7 @@ public class ImageDataVO implements Identity {
public boolean requiresHvm() { public boolean requiresHvm() {
return requiresHvm; return requiresHvm;
} }
public void setRequireHvm(boolean hvm) { public void setRequireHvm(boolean hvm) {
this.requiresHvm = hvm; this.requiresHvm = hvm;
} }
@ -234,7 +235,7 @@ public class ImageDataVO implements Identity {
public long getAccountId() { public long getAccountId() {
return accountId; return accountId;
} }
public void setAccountId(long accountId) { public void setAccountId(long accountId) {
this.accountId = accountId; this.accountId = accountId;
} }

View File

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

View File

@ -19,7 +19,6 @@
package org.apache.cloudstack.storage.datastore.db; package org.apache.cloudstack.storage.datastore.db;
import java.util.Date; import java.util.Date;
import java.util.UUID;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -30,12 +29,10 @@ import javax.persistence.Table;
import javax.persistence.TableGenerator; import javax.persistence.TableGenerator;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.storage.datastore.DataStoreStatus; import org.apache.cloudstack.storage.datastore.DataStoreStatus;
import com.cloud.api.Identity;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
@Entity @Entity
@ -98,7 +95,7 @@ public class PrimaryDataStoreVO implements Identity {
@Column(name = "cluster_id") @Column(name = "cluster_id")
private Long clusterId; private Long clusterId;
@Column(name = "configurator_key") @Column(name = "configurator_key")
private String key; private String key;
@ -118,6 +115,7 @@ public class PrimaryDataStoreVO implements Identity {
return name; return name;
} }
@Override
public String getUuid() { public String getUuid() {
return uuid; return uuid;
} }
@ -125,7 +123,7 @@ public class PrimaryDataStoreVO implements Identity {
public String getPoolType() { public String getPoolType() {
return poolType; return poolType;
} }
public void setPoolType(String protocol) { public void setPoolType(String protocol) {
this.poolType = protocol; this.poolType = protocol;
} }
@ -181,7 +179,7 @@ public class PrimaryDataStoreVO implements Identity {
public String getHostAddress() { public String getHostAddress() {
return hostAddress; return hostAddress;
} }
public void setHostAddress(String host) { public void setHostAddress(String host) {
this.hostAddress = host; this.hostAddress = host;
} }
@ -225,7 +223,7 @@ public class PrimaryDataStoreVO implements Identity {
public int getPort() { public int getPort() {
return port; return port;
} }
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
@ -237,13 +235,13 @@ public class PrimaryDataStoreVO implements Identity {
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public void setKey(String key) { public void setKey(String key) {
this.key = key; this.key = key;
} }
public String getKey() { public String getKey() {
return this.key; return this.key;
} }
@Override @Override

View File

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

View File

@ -30,10 +30,11 @@ import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult; import javax.naming.directory.SearchResult;
import org.apache.cloudstack.api.ApiConstants.LDAPParams;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.ApiConstants.LDAPParams;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
@ -49,7 +50,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private UserAccountDao _userAccountDao; private UserAccountDao _userAccountDao;
@Override @Override
public boolean authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters ) { public boolean authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters ) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
@ -74,14 +75,14 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
String bindPasswd = _configDao.getValue(LDAPParams.passwd.toString()); String bindPasswd = _configDao.getValue(LDAPParams.passwd.toString());
String trustStore = _configDao.getValue(LDAPParams.truststore.toString()); String trustStore = _configDao.getValue(LDAPParams.truststore.toString());
String trustStorePassword = _configDao.getValue(LDAPParams.truststorepass.toString()); String trustStorePassword = _configDao.getValue(LDAPParams.truststorepass.toString());
try { try {
// get all params // get all params
Hashtable<String, String> env = new Hashtable<String, String>(11); Hashtable<String, String> env = new Hashtable<String, String>(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
String protocol = "ldap://" ; String protocol = "ldap://" ;
if (new Boolean(useSSL)){ if (new Boolean(useSSL)){
env.put(Context.SECURITY_PROTOCOL, "ssl"); env.put(Context.SECURITY_PROTOCOL, "ssl");
protocol="ldaps://" ; protocol="ldaps://" ;
System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStore", trustStore);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
@ -93,10 +94,10 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
env.put(Context.SECURITY_CREDENTIALS, bindPasswd); env.put(Context.SECURITY_CREDENTIALS, bindPasswd);
} }
else { else {
// Use anonymous authentication // Use anonymous authentication
env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.SECURITY_AUTHENTICATION, "none");
} }
// Create the initial context // Create the initial context
DirContext ctx = new InitialDirContext(env); DirContext ctx = new InitialDirContext(env);
// use this context to search // use this context to search
@ -104,7 +105,7 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
queryFilter = queryFilter.replaceAll("\\%u", username); queryFilter = queryFilter.replaceAll("\\%u", username);
queryFilter = queryFilter.replaceAll("\\%n", user.getFirstname() + " " + user.getLastname()); queryFilter = queryFilter.replaceAll("\\%n", user.getFirstname() + " " + user.getLastname());
queryFilter = queryFilter.replaceAll("\\%e", user.getEmail()); queryFilter = queryFilter.replaceAll("\\%e", user.getEmail());
SearchControls sc = new SearchControls(); SearchControls sc = new SearchControls();
String[] searchFilter = { "dn" }; String[] searchFilter = { "dn" };
@ -112,22 +113,22 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
sc.setReturningAttributes(searchFilter); sc.setReturningAttributes(searchFilter);
sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setCountLimit(1); sc.setCountLimit(1);
// Search for objects with those matching attributes // Search for objects with those matching attributes
NamingEnumeration<SearchResult> answer = ctx.search(searchBase, queryFilter, sc); NamingEnumeration<SearchResult> answer = ctx.search(searchBase, queryFilter, sc);
SearchResult sr = (SearchResult)answer.next(); SearchResult sr = answer.next();
String cn = sr.getName(); String cn = sr.getName();
answer.close(); answer.close();
ctx.close(); ctx.close();
s_logger.info("DN from LDAP =" + cn); s_logger.info("DN from LDAP =" + cn);
// check the password // check the password
env = new Hashtable<String, String>(11); env = new Hashtable<String, String>(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
protocol = "ldap://" ; protocol = "ldap://" ;
if (new Boolean(useSSL)){ if (new Boolean(useSSL)){
env.put(Context.SECURITY_PROTOCOL, "ssl"); env.put(Context.SECURITY_PROTOCOL, "ssl");
protocol="ldaps://" ; protocol="ldaps://" ;
} }
env.put(Context.PROVIDER_URL, protocol + url + ":" + port); env.put(Context.PROVIDER_URL, protocol + url + ":" + port);
@ -136,22 +137,23 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
// Create the initial context // Create the initial context
ctx = new InitialDirContext(env); ctx = new InitialDirContext(env);
ctx.close(); ctx.close();
} catch (NamingException ne) { } catch (NamingException ne) {
ne.printStackTrace(); ne.printStackTrace();
s_logger.warn("Authentication failed due to " + ne.getMessage()); s_logger.warn("Authentication failed due to " + ne.getMessage());
return false; return false;
} }
catch (Exception e){ catch (Exception e){
e.printStackTrace(); e.printStackTrace();
s_logger.warn("Unknown error encountered " + e.getMessage()); s_logger.warn("Unknown error encountered " + e.getMessage());
return false; return false;
} }
// authenticate // authenticate
return true; return true;
} }
@Override
public boolean configure(String name, Map<String, Object> params) public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException { throws ConfigurationException {
super.configure(name, params); super.configure(name, params);
@ -161,16 +163,16 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator {
return true; return true;
} }
@Override @Override
public String encode(String password) { public String encode(String password) {
// Password is not used, so set to a random string // Password is not used, so set to a random string
try { try {
SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
byte bytes[] = new byte[20]; byte bytes[] = new byte[20];
randomGen.nextBytes(bytes); randomGen.nextBytes(bytes);
return Base64.encode(bytes).toString(); return Base64.encode(bytes).toString();
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Failed to generate random password",e); throw new CloudRuntimeException("Failed to generate random password",e);
} }
} }
} }

View File

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

View File

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

View File

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

View File

@ -22,10 +22,11 @@ import java.util.Random;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import javax.persistence.TableGenerator; import javax.persistence.TableGenerator;
import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.springframework.stereotype.Component;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.GuestType; import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
@ -61,21 +62,21 @@ import com.cloud.utils.net.NetUtils;
@Local(value = NetworkDao.class) @Local(value = NetworkDao.class)
@DB(txn = false) @DB(txn = false)
public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao { public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao {
final SearchBuilder<NetworkVO> AllFieldsSearch; SearchBuilder<NetworkVO> AllFieldsSearch;
final SearchBuilder<NetworkVO> AccountSearch; SearchBuilder<NetworkVO> AccountSearch;
final SearchBuilder<NetworkVO> RelatedConfigSearch; SearchBuilder<NetworkVO> RelatedConfigSearch;
final SearchBuilder<NetworkVO> AccountNetworkSearch; SearchBuilder<NetworkVO> AccountNetworkSearch;
final SearchBuilder<NetworkVO> ZoneBroadcastUriSearch; SearchBuilder<NetworkVO> ZoneBroadcastUriSearch;
final SearchBuilder<NetworkVO> ZoneSecurityGroupSearch; SearchBuilder<NetworkVO> ZoneSecurityGroupSearch;
final GenericSearchBuilder<NetworkVO, Integer> CountBy; GenericSearchBuilder<NetworkVO, Integer> CountBy;
final SearchBuilder<NetworkVO> PhysicalNetworkSearch; SearchBuilder<NetworkVO> PhysicalNetworkSearch;
final SearchBuilder<NetworkVO> SecurityGroupSearch; SearchBuilder<NetworkVO> SecurityGroupSearch;
final GenericSearchBuilder<NetworkVO, Long> NetworksRegularUserCanCreateSearch; GenericSearchBuilder<NetworkVO, Long> NetworksRegularUserCanCreateSearch;
private final GenericSearchBuilder<NetworkVO, Integer> NetworksCount; GenericSearchBuilder<NetworkVO, Integer> NetworksCount;
final SearchBuilder<NetworkVO> SourceNATSearch; SearchBuilder<NetworkVO> SourceNATSearch;
final GenericSearchBuilder<NetworkVO, Long> CountByZoneAndURI; GenericSearchBuilder<NetworkVO, Long> CountByZoneAndURI;
final GenericSearchBuilder<NetworkVO, Long> VpcNetworksCount; GenericSearchBuilder<NetworkVO, Long> VpcNetworksCount;
final SearchBuilder<NetworkVO> OfferingAccountNetworkSearch; SearchBuilder<NetworkVO> OfferingAccountNetworkSearch;
ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class);
@ -85,13 +86,13 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
NetworkOfferingDaoImpl _ntwkOffDao = ComponentLocator.inject(NetworkOfferingDaoImpl.class); NetworkOfferingDaoImpl _ntwkOffDao = ComponentLocator.inject(NetworkOfferingDaoImpl.class);
final TableGenerator _tgMacAddress; TableGenerator _tgMacAddress;
Random _rand = new Random(System.currentTimeMillis()); Random _rand = new Random(System.currentTimeMillis());
long _prefix = 0x2; long _prefix = 0x2;
public NetworkDaoImpl() { public NetworkDaoImpl() {
} }
@PostConstruct @PostConstruct
protected void init() { protected void init() {
AllFieldsSearch = createSearchBuilder(); AllFieldsSearch = createSearchBuilder();
@ -150,7 +151,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
CountByZoneAndURI.and("guestType", CountByZoneAndURI.entity().getGuestType(), Op.EQ); CountByZoneAndURI.and("guestType", CountByZoneAndURI.entity().getGuestType(), Op.EQ);
CountByZoneAndURI.done(); CountByZoneAndURI.done();
ZoneSecurityGroupSearch = createSearchBuilder(); ZoneSecurityGroupSearch = createSearchBuilder();
ZoneSecurityGroupSearch.and("dataCenterId", ZoneSecurityGroupSearch.entity().getDataCenterId(), Op.EQ); ZoneSecurityGroupSearch.and("dataCenterId", ZoneSecurityGroupSearch.entity().getDataCenterId(), Op.EQ);
SearchBuilder<NetworkServiceMapVO> offJoin = _ntwkSvcMap.createSearchBuilder(); SearchBuilder<NetworkServiceMapVO> offJoin = _ntwkSvcMap.createSearchBuilder();
@ -174,12 +175,12 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
join3.and("service", join3.entity().getService(), Op.EQ); join3.and("service", join3.entity().getService(), Op.EQ);
SecurityGroupSearch.join("services", join3, SecurityGroupSearch.entity().getId(), join3.entity().getNetworkId(), JoinBuilder.JoinType.INNER); SecurityGroupSearch.join("services", join3, SecurityGroupSearch.entity().getId(), join3.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
SecurityGroupSearch.done(); SecurityGroupSearch.done();
NetworksCount = createSearchBuilder(Integer.class); NetworksCount = createSearchBuilder(Integer.class);
NetworksCount.select(null, Func.COUNT, NetworksCount.entity().getId()); NetworksCount.select(null, Func.COUNT, NetworksCount.entity().getId());
NetworksCount.and("networkOfferingId", NetworksCount.entity().getNetworkOfferingId(), SearchCriteria.Op.EQ); NetworksCount.and("networkOfferingId", NetworksCount.entity().getNetworkOfferingId(), SearchCriteria.Op.EQ);
NetworksCount.done(); NetworksCount.done();
NetworksRegularUserCanCreateSearch = createSearchBuilder(Long.class); NetworksRegularUserCanCreateSearch = createSearchBuilder(Long.class);
NetworksRegularUserCanCreateSearch.and("aclType", NetworksRegularUserCanCreateSearch.entity().getAclType(), Op.EQ); NetworksRegularUserCanCreateSearch.and("aclType", NetworksRegularUserCanCreateSearch.entity().getAclType(), Op.EQ);
NetworksRegularUserCanCreateSearch.select(null, Func.COUNT, NetworksRegularUserCanCreateSearch.entity().getId()); NetworksRegularUserCanCreateSearch.select(null, Func.COUNT, NetworksRegularUserCanCreateSearch.entity().getId());
@ -193,7 +194,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
NetworksRegularUserCanCreateSearch.done(); NetworksRegularUserCanCreateSearch.done();
_tgMacAddress = _tgs.get("macAddress"); _tgMacAddress = _tgs.get("macAddress");
SourceNATSearch = createSearchBuilder(); SourceNATSearch = createSearchBuilder();
SourceNATSearch.and("account", SourceNATSearch.entity().getAccountId(), Op.EQ); SourceNATSearch.and("account", SourceNATSearch.entity().getAccountId(), Op.EQ);
SourceNATSearch.and("datacenter", SourceNATSearch.entity().getDataCenterId(), Op.EQ); SourceNATSearch.and("datacenter", SourceNATSearch.entity().getDataCenterId(), Op.EQ);
@ -202,7 +203,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
join6.and("service", join6.entity().getService(), Op.EQ); join6.and("service", join6.entity().getService(), Op.EQ);
SourceNATSearch.join("services", join6, SourceNATSearch.entity().getId(), join6.entity().getNetworkId(), JoinBuilder.JoinType.INNER); SourceNATSearch.join("services", join6, SourceNATSearch.entity().getId(), join6.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
SourceNATSearch.done(); SourceNATSearch.done();
VpcNetworksCount = createSearchBuilder(Long.class); VpcNetworksCount = createSearchBuilder(Long.class);
VpcNetworksCount.and("vpcId", VpcNetworksCount.entity().getVpcId(), Op.EQ); VpcNetworksCount.and("vpcId", VpcNetworksCount.entity().getVpcId(), Op.EQ);
VpcNetworksCount.select(null, Func.COUNT, VpcNetworksCount.entity().getId()); VpcNetworksCount.select(null, Func.COUNT, VpcNetworksCount.entity().getId());
@ -229,11 +230,11 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
if (type != null) { if (type != null) {
sc.setParameters("guestType", type); sc.setParameters("guestType", type);
} }
if (isSystem != null) { if (isSystem != null) {
sc.setJoinParameters("offerings", "isSystem", isSystem); sc.setJoinParameters("offerings", "isSystem", isSystem);
} }
return listBy(sc, null); return listBy(sc, null);
} }
@ -360,7 +361,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
SearchCriteria<Long> sc = CountByZoneAndURI.create(); SearchCriteria<Long> sc = CountByZoneAndURI.create();
sc.setParameters("dataCenterId", zoneId); sc.setParameters("dataCenterId", zoneId);
sc.setParameters("broadcastUri", broadcastUri); sc.setParameters("broadcastUri", broadcastUri);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
@ -409,7 +410,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
public void clearCheckForGc(long networkId) { public void clearCheckForGc(long networkId) {
_opDao.clearCheckForGc(networkId); _opDao.clearCheckForGc(networkId);
} }
@Override @Override
public void setCheckForGc(long networkId) { public void setCheckForGc(long networkId) {
_opDao.setCheckForGc(networkId); _opDao.setCheckForGc(networkId);
@ -431,8 +432,8 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
NetworkDomainVO domain = new NetworkDomainVO(networkId, domainId, subdomainAccess); NetworkDomainVO domain = new NetworkDomainVO(networkId, domainId, subdomainAccess);
_domainsDao.persist(domain); _domainsDao.persist(domain);
} }
@Override @Override
public int getNetworkCountByVpcId(long vpcId) { public int getNetworkCountByVpcId(long vpcId) {
SearchCriteria<Integer> sc = CountBy.create(); SearchCriteria<Integer> sc = CountBy.create();
@ -440,7 +441,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
List<Integer> results = customSearch(sc, null); List<Integer> results = customSearch(sc, null);
return results.get(0); return results.get(0);
} }
@Override @Override
public List<NetworkVO> listSecurityGroupEnabledNetworks() { public List<NetworkVO> listSecurityGroupEnabledNetworks() {
@ -500,7 +501,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return listBy(sc, null); return listBy(sc, null);
} }
@Override @Override
public int getNetworkCountByNetworkOffId(long networkOfferingId) { public int getNetworkCountByNetworkOffId(long networkOfferingId) {
SearchCriteria<Integer> sc = NetworksCount.create(); SearchCriteria<Integer> sc = NetworksCount.create();
@ -508,7 +509,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
List<Integer> count = customSearch(sc, null); List<Integer> count = customSearch(sc, null);
return count.get(0); return count.get(0);
} }
@Override @Override
public long countNetworksUserCanCreate(long ownerId) { public long countNetworksUserCanCreate(long ownerId) {
SearchCriteria<Long> sc = NetworksRegularUserCanCreateSearch.create(); SearchCriteria<Long> sc = NetworksRegularUserCanCreateSearch.create();
@ -517,8 +518,8 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
sc.setJoinParameters("ntwkOff", "specifyVlan", false); sc.setJoinParameters("ntwkOff", "specifyVlan", false);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
@Override @Override
public List<NetworkVO> listSourceNATEnabledNetworks(long accountId, long dataCenterId, Network.GuestType type) { public List<NetworkVO> listSourceNATEnabledNetworks(long accountId, long dataCenterId, Network.GuestType type) {
SearchCriteria<NetworkVO> sc = SourceNATSearch.create(); SearchCriteria<NetworkVO> sc = SourceNATSearch.create();
@ -528,7 +529,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
sc.setJoinParameters("services", "service", Service.SourceNat.getName()); sc.setJoinParameters("services", "service", Service.SourceNat.getName());
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<NetworkVO> listByVpc(long vpcId) { public List<NetworkVO> listByVpc(long vpcId) {
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
@ -549,6 +550,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return findOneBy(sc); return findOneBy(sc);
} }
@Override
@DB @DB
public boolean remove(Long id) { public boolean remove(Long id) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -585,7 +587,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
public List<NetworkVO> listRedundantNetworks() { public List<NetworkVO> listRedundantNetworks() {
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
sc.setJoinParameters("offerings", "isRedundant", true); sc.setJoinParameters("offerings", "isRedundant", true);
return listBy(sc, null); return listBy(sc, null);
} }
} }

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -16,6 +16,35 @@
// under the License. // under the License.
package com.cloud.server; package com.cloud.server;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.inject.Inject;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.Resource; import com.cloud.configuration.Resource;
@ -45,7 +74,11 @@ import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkDao;
import com.cloud.network.guru.*; import com.cloud.network.guru.ControlNetworkGuru;
import com.cloud.network.guru.DirectPodBasedNetworkGuru;
import com.cloud.network.guru.PodBasedNetworkGuru;
import com.cloud.network.guru.PublicNetworkGuru;
import com.cloud.network.guru.StorageNetworkGuru;
import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offering.NetworkOffering.Availability;
import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingServiceMapVO;
@ -63,7 +96,6 @@ import com.cloud.user.User;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@ -71,20 +103,6 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDao;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;
@Component @Component
public class ConfigurationServerImpl implements ConfigurationServer { public class ConfigurationServerImpl implements ConfigurationServer {
@ -230,7 +248,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// store the public and private keys in the database // store the public and private keys in the database
updateKeyPairs(); updateKeyPairs();
// generate a random password for system vm // generate a random password for system vm
updateSystemvmPassword(); updateSystemvmPassword();
@ -504,29 +522,29 @@ public class ConfigurationServerImpl implements ConfigurationServer {
if (!userid.startsWith("cloud")) { if (!userid.startsWith("cloud")) {
return; return;
} }
if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) { if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) {
return; return;
} }
String already = _configDao.getValue("system.vm.password"); String already = _configDao.getValue("system.vm.password");
if (already == null) { if (already == null) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
String rpassword = PasswordGenerator.generatePresharedKey(8); String rpassword = PasswordGenerator.generatePresharedKey(8);
String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) "
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')"; + "','randmon password generated each management server starts for system vm')";
PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql);
stmt.executeUpdate(wSql); stmt.executeUpdate(wSql);
s_logger.info("Updated systemvm password in database"); s_logger.info("Updated systemvm password in database");
} catch (SQLException e) { } catch (SQLException e) {
s_logger.error("Cannot retrieve systemvm password", e); s_logger.error("Cannot retrieve systemvm password", e);
} }
} }
}
}
@Override @Override
@DB @DB
public void updateKeyPairs() { public void updateKeyPairs() {
@ -541,10 +559,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String already = _configDao.getValue("ssh.privatekey"); String already = _configDao.getValue("ssh.privatekey");
String homeDir = null; String homeDir = null;
homeDir = Script.runSimpleBashScript("echo ~" + username); homeDir = Script.runSimpleBashScript("echo ~" + username);
if (homeDir == null) { if (homeDir == null) {
throw new CloudRuntimeException("Cannot get home directory for account: " + username); throw new CloudRuntimeException("Cannot get home directory for account: " + username);
} }
if (s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
s_logger.info("Processing updateKeyPairs"); s_logger.info("Processing updateKeyPairs");
} }
@ -622,11 +640,11 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
s_logger.info("Going to update systemvm iso with generated keypairs if needed"); s_logger.info("Going to update systemvm iso with generated keypairs if needed");
try { try {
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
} catch (CloudRuntimeException e) { } catch (CloudRuntimeException e) {
if (!devel) { if (!devel) {
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
} }
} }
@ -892,7 +910,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
defaultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedSGNetworkOffering); defaultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedSGNetworkOffering);
for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) { for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service)); NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
@ -967,7 +985,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
// Offering #6 // Offering #6
NetworkOfferingVO defaultNetworkOfferingForVpcNetworks = new NetworkOfferingVO( NetworkOfferingVO defaultNetworkOfferingForVpcNetworks = new NetworkOfferingVO(
NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks,
@ -978,7 +996,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
defaultNetworkOfferingForVpcNetworks.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworks.setState(NetworkOffering.State.Enabled);
defaultNetworkOfferingForVpcNetworks = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworks); defaultNetworkOfferingForVpcNetworks = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworks);
Map<Network.Service, Network.Provider> defaultVpcNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>(); Map<Network.Service, Network.Provider> defaultVpcNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultVpcNetworkOfferingProviders.put(Service.Dhcp, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Dhcp, Provider.VPCVirtualRouter);
defaultVpcNetworkOfferingProviders.put(Service.Dns, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Dns, Provider.VPCVirtualRouter);
@ -990,14 +1008,14 @@ public class ConfigurationServerImpl implements ConfigurationServer {
defaultVpcNetworkOfferingProviders.put(Service.StaticNat, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.StaticNat, Provider.VPCVirtualRouter);
defaultVpcNetworkOfferingProviders.put(Service.PortForwarding, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.PortForwarding, Provider.VPCVirtualRouter);
defaultVpcNetworkOfferingProviders.put(Service.Vpn, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Vpn, Provider.VPCVirtualRouter);
for (Service service : defaultVpcNetworkOfferingProviders.keySet()) { for (Service service : defaultVpcNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); (defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
// Offering #7 // Offering #7
NetworkOfferingVO defaultNetworkOfferingForVpcNetworksNoLB = new NetworkOfferingVO( NetworkOfferingVO defaultNetworkOfferingForVpcNetworksNoLB = new NetworkOfferingVO(
NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB,
@ -1008,7 +1026,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
defaultNetworkOfferingForVpcNetworksNoLB.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworksNoLB.setState(NetworkOffering.State.Enabled);
defaultNetworkOfferingForVpcNetworksNoLB = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworksNoLB); defaultNetworkOfferingForVpcNetworksNoLB = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworksNoLB);
Map<Network.Service, Network.Provider> defaultVpcNetworkOfferingProvidersNoLB = new HashMap<Network.Service, Network.Provider>(); Map<Network.Service, Network.Provider> defaultVpcNetworkOfferingProvidersNoLB = new HashMap<Network.Service, Network.Provider>();
defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dhcp, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dhcp, Provider.VPCVirtualRouter);
defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dns, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dns, Provider.VPCVirtualRouter);
@ -1019,16 +1037,16 @@ public class ConfigurationServerImpl implements ConfigurationServer {
defaultVpcNetworkOfferingProvidersNoLB.put(Service.StaticNat, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.StaticNat, Provider.VPCVirtualRouter);
defaultVpcNetworkOfferingProvidersNoLB.put(Service.PortForwarding, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.PortForwarding, Provider.VPCVirtualRouter);
defaultVpcNetworkOfferingProvidersNoLB.put(Service.Vpn, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Vpn, Provider.VPCVirtualRouter);
for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) { for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); (defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
txn.commit(); txn.commit();
} }

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -20,8 +20,8 @@ import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -39,20 +39,18 @@ import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.SecurityChecker; import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd;
import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.cloudstack.api.command.admin.user.RegisterCmd;
import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.dao.UserAccountJoinDao; import com.cloud.api.query.dao.UserAccountJoinDao;
import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.api.query.vo.ControlledViewEntity;
import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.ResourceLimit;
@ -115,7 +113,6 @@ import com.cloud.user.dao.UserDao;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
@ -232,7 +229,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
UserVO _systemUser; UserVO _systemUser;
AccountVO _systemAccount; AccountVO _systemAccount;
@Inject @Inject
List<SecurityChecker> _securityCheckers; List<SecurityChecker> _securityCheckers;
int _cleanupInterval; int _cleanupInterval;
@ -285,6 +282,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return true; return true;
} }
@Override
public AccountVO getSystemAccount() { public AccountVO getSystemAccount() {
if (_systemAccount == null) { if (_systemAccount == null) {
_systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
@ -382,7 +380,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (!granted) { if (!granted) {
assert false : "How can all of the security checkers pass on checking this check: " + entity; assert false : "How can all of the security checkers pass on checking this check: " + entity;
throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity);
} }
} }
@ -444,7 +442,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
user.setState(State.disabled.toString()); user.setState(State.disabled.toString());
} }
_userAccountDao.update(id, user); _userAccountDao.update(id, user);
txn.commit(); txn.commit();
} catch (Exception e) { } catch (Exception e) {
s_logger.error("Failed to update login attempts for user with id " + id ); s_logger.error("Failed to update login attempts for user with id " + id );
} }
@ -492,7 +490,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
@Override @Override
public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) { public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId(); long accountId = account.getId();
//delete the account record //delete the account record
if (!_accountDao.remove(accountId)) { if (!_accountDao.remove(accountId)) {
s_logger.error("Unable to delete account " + accountId); s_logger.error("Unable to delete account " + accountId);
@ -510,7 +508,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) { public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId(); long accountId = account.getId();
boolean accountCleanupNeeded = false; boolean accountCleanupNeeded = false;
try { try {
//cleanup the users from the account //cleanup the users from the account
List<UserVO> users = _userDao.listByAccount(accountId); List<UserVO> users = _userDao.listByAccount(accountId);
@ -520,10 +518,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
accountCleanupNeeded = true; accountCleanupNeeded = true;
} }
} }
//delete the account from project accounts //delete the account from project accounts
_projectAccountDao.removeAccountFromProjects(accountId); _projectAccountDao.removeAccountFromProjects(accountId);
// delete all vm groups belonging to accont // delete all vm groups belonging to accont
List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId); List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (InstanceGroupVO group : groups) { for (InstanceGroupVO group : groups) {
@ -601,7 +599,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex); s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true; accountCleanupNeeded = true;
} }
// Cleanup security groups // Cleanup security groups
int numRemoved = _securityGroupDao.removeByAccountId(accountId); int numRemoved = _securityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId); s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId);
@ -624,7 +622,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
} }
} }
//Delete all VPCs //Delete all VPCs
boolean vpcsDeleted = true; boolean vpcsDeleted = true;
s_logger.debug("Deleting vpcs for account " + account.getId()); s_logger.debug("Deleting vpcs for account " + account.getId());
@ -646,8 +644,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
for (IpAddress ip : ipsToRelease) { for (IpAddress ip : ipsToRelease) {
s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
accountCleanupNeeded = true; accountCleanupNeeded = true;
} }
} }
} }
@ -776,7 +774,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (userName.isEmpty()) { if (userName.isEmpty()) {
throw new InvalidParameterValueException("Username is empty"); throw new InvalidParameterValueException("Username is empty");
} }
if (firstName.isEmpty()) { if (firstName.isEmpty()) {
throw new InvalidParameterValueException("Firstname is empty"); throw new InvalidParameterValueException("Firstname is empty");
} }
@ -905,21 +903,21 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (firstName.isEmpty()) { if (firstName.isEmpty()) {
throw new InvalidParameterValueException("Firstname is empty"); throw new InvalidParameterValueException("Firstname is empty");
} }
user.setFirstname(firstName); user.setFirstname(firstName);
} }
if (lastName != null) { if (lastName != null) {
if (lastName.isEmpty()) { if (lastName.isEmpty()) {
throw new InvalidParameterValueException("Lastname is empty"); throw new InvalidParameterValueException("Lastname is empty");
} }
user.setLastname(lastName); user.setLastname(lastName);
} }
if (userName != null) { if (userName != null) {
if (userName.isEmpty()) { if (userName.isEmpty()) {
throw new InvalidParameterValueException("Username is empty"); throw new InvalidParameterValueException("Username is empty");
} }
// don't allow to have same user names in the same domain // don't allow to have same user names in the same domain
List<UserVO> duplicatedUsers = _userDao.findUsersByName(userName); List<UserVO> duplicatedUsers = _userDao.findUsersByName(userName);
for (UserVO duplicatedUser : duplicatedUsers) { for (UserVO duplicatedUser : duplicatedUsers) {
@ -933,18 +931,18 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
user.setUsername(userName); user.setUsername(userName);
} }
if (password != null) { if (password != null) {
String encodedPassword = null; String encodedPassword = null;
for (Enumeration<UserAuthenticator> en = _userAuthenticators.enumeration(); en.hasMoreElements();) { for (Iterator<UserAuthenticator> en = _userAuthenticators.iterator(); en.hasNext();) {
UserAuthenticator authenticator = en.nextElement(); UserAuthenticator authenticator = en.next();
encodedPassword = authenticator.encode(password); encodedPassword = authenticator.encode(password);
if (encodedPassword != null) { if (encodedPassword != null) {
break; break;
} }
} }
if (encodedPassword == null) { if (encodedPassword == null) {
throw new CloudRuntimeException("Failed to encode password"); throw new CloudRuntimeException("Failed to encode password");
} }
user.setPassword(encodedPassword); user.setPassword(encodedPassword);
} }
@ -1293,11 +1291,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
// check if the given account name is unique in this domain for updating // check if the given account name is unique in this domain for updating
Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId); Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId);
if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow
// same // same
// account // account
// to // to
// update // update
// itself // itself
throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:" throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:"
+ duplicateAcccount.getId()); + duplicateAcccount.getId());
} }
@ -1697,15 +1695,15 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
String encodedPassword = null; String encodedPassword = null;
for (Enumeration<UserAuthenticator> en = _userAuthenticators.enumeration(); en.hasMoreElements();) { for (Iterator<UserAuthenticator> en = _userAuthenticators.iterator(); en.hasNext();) {
UserAuthenticator authenticator = en.nextElement(); UserAuthenticator authenticator = en.next();
encodedPassword = authenticator.encode(password); encodedPassword = authenticator.encode(password);
if (encodedPassword != null) { if (encodedPassword != null) {
break; break;
} }
} }
if (encodedPassword == null) { if (encodedPassword == null) {
throw new CloudRuntimeException("Failed to encode password"); throw new CloudRuntimeException("Failed to encode password");
} }
UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone)); UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone));
@ -2088,7 +2086,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
@Override @Override
public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long> public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long>
permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject,
boolean listAll, boolean forProjectInvitation) { boolean listAll, boolean forProjectInvitation) {
Long domainId = domainIdRecursiveListProject.first(); Long domainId = domainIdRecursiveListProject.first();
if (domainId != null) { if (domainId != null) {
@ -2166,7 +2164,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
} }
@Override @Override
public void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId, public void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId,
boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { boolean isRecursive, List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) {
@ -2210,7 +2208,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
@Override @Override
public UserAccount getUserByApiKey(String apiKey) { public UserAccount getUserByApiKey(String apiKey) {
return _userAccountDao.getUserByApiKey(apiKey); return _userAccountDao.getUserByApiKey(apiKey);
} }
} }

View File

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

View File

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

View File

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