Merge branch 'master' into ui-vpc-redesign

This commit is contained in:
Brian Federle 2013-05-21 12:30:01 -07:00
commit e35f14439a
129 changed files with 5344 additions and 1165 deletions

View File

@ -35,6 +35,7 @@ public interface AsyncJob extends Identity, InternalIdentity {
Host,
StoragePool,
IpAddress,
PortableIpAddress,
SecurityGroup,
PhysicalNetwork,
TrafficType,

View File

@ -39,6 +39,9 @@ import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd;
import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd;
import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd;
import org.apache.cloudstack.api.command.admin.region.CreatePortableIpRangeCmd;
import org.apache.cloudstack.api.command.admin.region.DeletePortableIpRangeCmd;
import org.apache.cloudstack.api.command.admin.region.ListPortableIpRangesCmd;
import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DedicatePublicIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd;
@ -56,6 +59,8 @@ import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpRange;
public interface ConfigurationService {
@ -278,4 +283,12 @@ public interface ConfigurationService {
* @return
*/
boolean isOfferingForVpc(NetworkOffering offering);
PortableIpRange createPortableIpRange(CreatePortableIpRangeCmd cmd) throws ConcurrentOperationException;
boolean deletePortableIpRange(DeletePortableIpRangeCmd cmd);
List<? extends PortableIpRange> listPortableIpRanges(ListPortableIpRangesCmd cmd);
List<? extends PortableIp> listPortableIps(long id);
}

View File

@ -102,6 +102,8 @@ public class EventTypes {
// Network Events
public static final String EVENT_NET_IP_ASSIGN = "NET.IPASSIGN";
public static final String EVENT_NET_IP_RELEASE = "NET.IPRELEASE";
public static final String EVENT_PORTABLE_IP_ASSIGN = "PORTABLE.IPASSIGN";
public static final String EVENT_PORTABLE_IP_RELEASE = "PORTABLEIPRELEASE";
public static final String EVENT_NET_RULE_ADD = "NET.RULEADD";
public static final String EVENT_NET_RULE_DELETE = "NET.RULEDELETE";
public static final String EVENT_NET_RULE_MODIFY = "NET.RULEMODIFY";
@ -432,6 +434,9 @@ public class EventTypes {
public static final String EVENT_DEDICATED_GUEST_VLAN_RANGE_RELEASE = "GUESTVLANRANGE.RELEASE";
public static final String EVENT_PORTABLE_IP_RANGE_CREATE = "PORTABLE.IP.RANGE.CREATE";
public static final String EVENT_PORTABLE_IP_RANGE_DELETE = "PORTABLE.IP.RANGE.DELETE";
static {
// TODO: need a way to force author adding event types to declare the entity details as well, with out braking

View File

@ -27,6 +27,8 @@ public class InsufficientServerCapacityException extends InsufficientCapacityExc
private static final long serialVersionUID = SerialVersionUID.InsufficientServerCapacityException;
private boolean affinityGroupsApplied = false;
public InsufficientServerCapacityException(String msg, Long clusterId) {
this(msg, Cluster.class, clusterId);
}
@ -34,4 +36,13 @@ public class InsufficientServerCapacityException extends InsufficientCapacityExc
public InsufficientServerCapacityException(String msg, Class<?> scope, Long id) {
super(msg, scope, id);
}
public InsufficientServerCapacityException(String msg, Class<?> scope, Long id, boolean affinityGroupsApplied) {
super(msg, scope, id);
this.affinityGroupsApplied = affinityGroupsApplied;
}
public boolean isAffinityApplied() {
return affinityGroupsApplied;
}
}

View File

@ -81,7 +81,9 @@ public interface IpAddress extends ControlledEntity, Identity, InternalIdentity
Long getVpcId();
String getVmIp();
boolean isPortable();
Long getNetworkId();
}

View File

@ -0,0 +1,70 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network;
import com.cloud.deploy.DeployDestination;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
/**
* NetworkGuru and NetworkElements that implement this interface
* will be called during Virtual Machine migration.
*/
public interface NetworkMigrationResponder {
/**
* Prepare for migration.
*
* This method will be called per nic before the vm migration.
* @param nic
* @param network
* @param vm
* @param dest
* @param context
* @return true when operation was successful.
*/
public boolean prepareMigration(NicProfile nic, Network network, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context);
/**
* Cancel for migration preparation.
*
* This method will be called per nic when the entire vm migration
* process failed and need to release the resouces that was
* allocated at the migration preparation.
* @param nic destination nic
* @param network destination network
* @param vm destination vm profile
* @param src The context nic migrates from.
* @param dst The context nic migrates to.
*/
public void rollbackMigration(NicProfile nic, Network network, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext src, ReservationContext dst);
/**
* Commit the migration resource.
*
* This method will be called per nic when the entire vm migration
* process was successful. This is useful to release the resource of
* source deployment where vm has left.
* @param nic source nic
* @param network source network
* @param vm source vm profile
* @param src the context nic migrates from.
* @param dst the context nic migrates to.
*/
public void commitMigration(NicProfile nic, Network network, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext src, ReservationContext dst);
}

View File

@ -52,6 +52,11 @@ public interface NetworkService {
boolean releaseIpAddress(long ipAddressId) throws InsufficientAddressCapacityException;
IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) throws ResourceAllocationException,
InsufficientAddressCapacityException, ConcurrentOperationException;
boolean releasePortableIpAddress(long ipAddressId) throws InsufficientAddressCapacityException;
Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceAllocationException;

View File

@ -114,6 +114,7 @@ public class ApiConstants {
public static final String IS_CLEANUP_REQUIRED = "iscleanuprequired";
public static final String IS_EXTRACTABLE = "isextractable";
public static final String IS_FEATURED = "isfeatured";
public static final String IS_PORTABLE = "isportable";
public static final String IS_PUBLIC = "ispublic";
public static final String IS_PERSISTENT = "ispersistent";
public static final String IS_READY = "isready";
@ -158,6 +159,7 @@ public class ApiConstants {
public static final String POLICY_ID = "policyid";
public static final String PORT = "port";
public static final String PORTAL = "portal";
public static final String PORTABLE_IP_ADDRESS = "portableipaddress";
public static final String PORT_FORWARDING_SERVICE_ID = "portforwardingserviceid";
public static final String PRIVATE_INTERFACE = "privateinterface";
public static final String PRIVATE_IP = "privateip";

View File

@ -119,6 +119,8 @@ import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.api.response.*;
import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule;
import org.apache.cloudstack.region.Region;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpRange;
import org.apache.cloudstack.usage.Usage;
import com.cloud.async.AsyncJob;
@ -441,7 +443,12 @@ public interface ResponseGenerator {
Long getAffinityGroupId(String name, long entityOwnerId);
PortableIpRangeResponse createPortableIPRangeResponse(PortableIpRange range);
PortableIpResponse createPortableIPResponse(PortableIp portableIp);
InternalLoadBalancerElementResponse createInternalLbElementResponse(VirtualRouterProvider result);
IsolationMethodResponse createIsolationMethodResponse(IsolationType method);
}

View File

@ -17,13 +17,11 @@
package org.apache.cloudstack.api.command.admin.cluster;
import java.util.ArrayList;
import java.util.List;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.InvalidParameterValueException;
import org.apache.cloudstack.api.*;
import org.apache.log4j.Logger;
import com.cloud.exception.ResourceInUseException;
import com.cloud.org.Cluster;
import com.cloud.user.Account;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
@ -36,10 +34,8 @@ import org.apache.cloudstack.api.response.PodResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.log4j.Logger;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.org.Cluster;
import com.cloud.user.Account;
import java.util.ArrayList;
import java.util.List;
@APICommand(name = "addCluster", description="Adds a new cluster", responseObject=ClusterResponse.class)
public class AddClusterCmd extends BaseCmd {
@ -86,10 +82,10 @@ public class AddClusterCmd extends BaseCmd {
private String vsmipaddress;
@Parameter (name=ApiConstants.CPU_OVERCOMMIT_RATIO, type = CommandType.STRING, required = false , description = "value of the cpu overcommit ratio, defaults to 1")
private String cpuovercommitRatio;
private String cpuOvercommitRatio;
@Parameter(name = ApiConstants.MEMORY_OVERCOMMIT_RATIO, type = CommandType.STRING, required = false ,description = "value of the default ram overcommit ratio, defaults to 1")
private String memoryovercommitratio;
@Parameter(name = ApiConstants.MEMORY_OVERCOMMIT_RATIO, type = CommandType.STRING, required = false, description = "value of the default memory overcommit ratio, defaults to 1")
private String memoryOvercommitRatio;
@Parameter(name = ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC, type = CommandType.STRING, required = false, description = "Type of virtual switch used for guest traffic in the cluster. Allowed values are, vmwaresvs (for VMware standard vSwitch) and vmwaredvs (for VMware distributed vSwitch)")
private String vSwitchTypeGuestTraffic;
@ -186,15 +182,15 @@ public class AddClusterCmd extends BaseCmd {
}
public Float getCpuOvercommitRatio (){
if(cpuovercommitRatio != null){
return Float.parseFloat(cpuovercommitRatio);
if(cpuOvercommitRatio != null){
return Float.parseFloat(cpuOvercommitRatio);
}
return 1.0f;
}
public Float getMemoryOvercommitRaito (){
if (memoryovercommitratio != null){
return Float.parseFloat(memoryovercommitratio);
public Float getMemoryOvercommitRatio(){
if (memoryOvercommitRatio != null){
return Float.parseFloat(memoryOvercommitRatio);
}
return 1.0f;
}
@ -202,8 +198,8 @@ public class AddClusterCmd extends BaseCmd {
@Override
public void execute(){
try {
if ((getMemoryOvercommitRaito().compareTo(1f) < 0) | (getCpuOvercommitRatio().compareTo(1f) < 0)) {
throw new InvalidParameterValueException("Cpu and ram overcommit ratios should not be less than 1");
if (getMemoryOvercommitRatio().compareTo(1f) < 0 || getCpuOvercommitRatio().compareTo(1f) < 0) {
throw new InvalidParameterValueException("cpu and memory overcommit ratios should be greater than or equal to one");
}
List<? extends Cluster> result = _resourceService.discoverCluster(this);
ListResponse<ClusterResponse> response = new ListResponse<ClusterResponse>();

View File

@ -57,7 +57,7 @@ public class UpdateClusterCmd extends BaseCmd {
@Parameter(name=ApiConstants.CPU_OVERCOMMIT_RATIO, type = CommandType.STRING, description = "Value of cpu overcommit ratio")
private String cpuovercommitratio;
@Parameter(name=ApiConstants.MEMORY_OVERCOMMIT_RATIO, type = CommandType.STRING, description = "Value of ram overcommit ratio")
@Parameter(name=ApiConstants.MEMORY_OVERCOMMIT_RATIO, type = CommandType.STRING, description = "Value of memory overcommit ratio")
private String memoryovercommitratio;
@ -129,13 +129,13 @@ public class UpdateClusterCmd extends BaseCmd {
}
if (getMemoryOvercommitRaito() !=null){
if ((getMemoryOvercommitRaito().compareTo(1f) < 0)) {
throw new InvalidParameterValueException("Memory overcommit ratio should be greater than or equal to one");
throw new InvalidParameterValueException("Memory overcommit ratio should be greater than or equal to one");
}
}
if (getCpuOvercommitRatio() !=null){
if (getCpuOvercommitRatio().compareTo(1f) < 0) {
throw new InvalidParameterValueException("Cpu overcommit ratio should be greater than or equal to one");
throw new InvalidParameterValueException("Cpu overcommit ratio should be greater than or equal to one");
}
}

View File

@ -0,0 +1,156 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.admin.region;
import javax.inject.Inject;
import com.cloud.async.AsyncJob;
import com.cloud.dc.Vlan;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceAllocationException;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCreateCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.PortableIpRangeResponse;
import org.apache.cloudstack.api.response.RegionResponse;
import org.apache.cloudstack.api.response.VlanIpRangeResponse;
import org.apache.cloudstack.region.PortableIpRange;
import org.apache.cloudstack.region.Region;
import org.apache.cloudstack.region.RegionService;
import org.apache.log4j.Logger;
import com.cloud.user.Account;
@APICommand(name = "createPortableIpRange", responseObject=PortableIpRangeResponse.class, description="adds a range of portable public IP's to a region", since="4.2.0")
public class CreatePortableIpRangeCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = Logger.getLogger(CreatePortableIpRangeCmd.class.getName());
private static final String s_name = "createportableiprangeresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, entityType = RegionResponse.class, required=true, description="Id of the Region")
private Integer regionId;
@Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address in the portable IP range")
private String startIp;
@Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, required=true, description="the ending IP address in the portable IP range")
private String endIp;
@Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for the portable IP range")
private String gateway;
@Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the portable IP range")
private String netmask;
@Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="VLAN id, if not specified defaulted to untagged")
private String vlan;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Integer getRegionId() {
return regionId;
}
public String getStartIp() {
return startIp;
}
public String getEndIp() {
return endIp;
}
public String getVlan() {
return vlan;
}
public String getGateway() {
return gateway;
}
public String getNetmask() {
return netmask;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
@Override
public void execute(){
PortableIpRange portableIpRange = _entityMgr.findById(PortableIpRange.class, getEntityId());
PortableIpRangeResponse response = null;
if (portableIpRange != null) {
response = _responseGenerator.createPortableIPRangeResponse(portableIpRange);
}
response.setResponseName(getCommandName());
this.setResponseObject(response);
}
@Override
public void create() throws ResourceAllocationException {
try {
PortableIpRange portableIpRange = _configService.createPortableIpRange(this);
if (portableIpRange != null) {
this.setEntityId(portableIpRange.getId());
this.setEntityUuid(portableIpRange.getUuid());
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create portable public IP range");
}
} catch (ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
}
}
@Override
public String getEventType() {
return EventTypes.EVENT_PORTABLE_IP_RANGE_CREATE;
}
@Override
public String getEventDescription() {
return "creating a portable public ip range in region: " + getRegionId();
}
@Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.PortableIpAddress;
}
}

View File

@ -0,0 +1,93 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.admin.region;
import javax.inject.Inject;
import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import org.apache.cloudstack.api.*;
import org.apache.cloudstack.api.response.PortableIpRangeResponse;
import org.apache.cloudstack.api.response.RegionResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.region.Region;
import org.apache.cloudstack.region.RegionService;
import org.apache.log4j.Logger;
import com.cloud.user.Account;
@APICommand(name = "deletePortableIpRange", description="deletes a range of portable public IP's associated with a region", responseObject=SuccessResponse.class)
public class DeletePortableIpRangeCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(DeletePortableIpRangeCmd.class.getName());
private static final String s_name = "deleteportablepublicipresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.UUID, required=true, entityType = PortableIpRangeResponse.class, description="Id of the portable ip range")
private Long id;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
@Override
public void execute(){
boolean result = _configService.deletePortableIpRange(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete portable ip range");
}
}
@Override
public String getEventType() {
return EventTypes.EVENT_PORTABLE_IP_RANGE_DELETE;
}
@Override
public String getEventDescription() {
return "deleting a portable public ip range";
}
@Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.PortableIpAddress;
}
}

View File

@ -0,0 +1,109 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.admin.region;
import javax.inject.Inject;
import org.apache.cloudstack.api.*;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.PortableIpRangeResponse;
import org.apache.cloudstack.api.response.PortableIpResponse;
import org.apache.cloudstack.api.response.RegionResponse;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpRange;
import org.apache.cloudstack.region.Region;
import org.apache.cloudstack.region.RegionService;
import org.apache.log4j.Logger;
import com.cloud.user.Account;
import java.util.ArrayList;
import java.util.List;
@APICommand(name = "listPortableIpRanges", description="list portable IP ranges", responseObject=PortableIpRangeResponse.class)
public class ListPortableIpRangesCmd extends BaseListCmd {
public static final Logger s_logger = Logger.getLogger(ListPortableIpRangesCmd.class.getName());
private static final String s_name = "listportableipresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, required=false, description="Id of a Region")
private Integer regionId;
@Parameter(name=ApiConstants.ID, type=CommandType.UUID, required=false, entityType = PortableIpRangeResponse.class, description="Id of the portable ip range")
private Long id;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Integer getRegionIdId() {
return regionId;
}
public Long getPortableIpRangeId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
@Override
public void execute(){
ListResponse<PortableIpRangeResponse> response = new ListResponse<PortableIpRangeResponse>();
List<PortableIpRangeResponse> responses = new ArrayList<PortableIpRangeResponse>();
List<? extends PortableIpRange> portableIpRanges = new ArrayList<PortableIpRange>();
portableIpRanges = _configService.listPortableIpRanges(this);
if (portableIpRanges != null && !portableIpRanges.isEmpty()) {
for (PortableIpRange range : portableIpRanges) {
PortableIpRangeResponse rangeResponse = _responseGenerator.createPortableIPRangeResponse(range);
List<? extends PortableIp> portableIps = _configService.listPortableIps(range.getId());
if (portableIps != null && !portableIps.isEmpty()) {
List<PortableIpResponse> portableIpResponses = new ArrayList<PortableIpResponse>();
for (PortableIp portableIP: portableIps) {
PortableIpResponse portableIpresponse = _responseGenerator.createPortableIPResponse(portableIP);
portableIpResponses.add(portableIpresponse);
}
rangeResponse.setPortableIpResponses(portableIpResponses);
}
rangeResponse.setObjectName("portableiprange");
responses.add(rangeResponse);
}
}
response.setResponses(responses, portableIpRanges.size());
response.setResponseName(getCommandName());
this.setResponseObject(response);
}
}

View File

@ -66,6 +66,14 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
"be associated with")
private Long vpcId;
@Parameter(name=ApiConstants.IS_PORTABLE, type = BaseCmd.CommandType.BOOLEAN, description = "should be set to true " +
"if public IP is required to be transferable across zones, if not specified defaults to false")
private Boolean isPortable;
@Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, entityType = RegionResponse.class,
required=false, description="region ID from where portable ip is to be associated.")
private Integer regionId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@ -107,6 +115,18 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
return vpcId;
}
public boolean isPortable() {
if (isPortable == null) {
return false;
} else {
return isPortable;
}
}
public Integer getRegionId() {
return regionId;
}
public Long getNetworkId() {
if (vpcId != null) {
return null;
@ -196,7 +216,13 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
@Override
public void create() throws ResourceAllocationException{
try {
IpAddress ip = _networkService.allocateIP(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getNetworkId());
IpAddress ip = null;
if (!isPortable()) {
ip = _networkService.allocateIP(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getNetworkId());
} else {
ip = _networkService.allocatePortableIP(_accountService.getAccount(getEntityOwnerId()), 1, getZoneId(), getNetworkId(), getVpcId());
}
if (ip != null) {
this.setEntityId(ip.getId());

View File

@ -74,7 +74,12 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd {
@Override
public void execute() throws InsufficientAddressCapacityException{
UserContext.current().setEventDetails("Ip Id: " + getIpAddressId());
boolean result = _networkService.releaseIpAddress(getIpAddressId());
boolean result = false;
if (!isPortable(id)) {
_networkService.releaseIpAddress(getIpAddressId());
} else {
_networkService.releaseIpAddress(getIpAddressId());
}
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
@ -139,4 +144,9 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd {
public Long getInstanceId() {
return getIpAddressId();
}
private boolean isPortable(long id) {
IpAddress ip = getIpAddress(id);
return ip.isPortable();
}
}

View File

@ -91,6 +91,12 @@ public class EnableStaticNatCmd extends BaseCmd{
} else {
ntwkId = networkId;
}
// in case of portable public IP, network ID passed takes precedence
if (ip.isPortable() && networkId != null ) {
ntwkId = networkId;
}
if (ntwkId == null) {
throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId +
" as ip is not associated with any network and no networkId is passed in");

View File

@ -51,6 +51,7 @@ import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
@ -424,9 +425,15 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
} catch (InsufficientCapacityException ex) {
StringBuilder message = new StringBuilder(ex.getMessage());
if (ex instanceof InsufficientServerCapacityException) {
if(((InsufficientServerCapacityException)ex).isAffinityApplied()){
message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them");
}
}
s_logger.info(ex);
s_logger.info(ex.getMessage(), ex);
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
s_logger.info(message.toString(), ex);
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString());
}
} else {
result = _userVmService.getUserVm(getEntityId());

View File

@ -30,10 +30,10 @@ import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import com.cloud.uservm.UserVm;
@ -112,7 +112,7 @@ public class StartVMCmd extends BaseAsyncCmd {
}
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {
public void execute() throws ResourceUnavailableException, ResourceAllocationException {
try {
UserContext.current().setEventDetails("Vm Id: " + getId());
@ -135,6 +135,16 @@ public class StartVMCmd extends BaseAsyncCmd {
} catch (ExecutionException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
} catch (InsufficientCapacityException ex) {
StringBuilder message = new StringBuilder(ex.getMessage());
if (ex instanceof InsufficientServerCapacityException) {
if (((InsufficientServerCapacityException) ex).isAffinityApplied()) {
message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them");
}
}
s_logger.info(ex);
s_logger.info(message.toString(), ex);
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString());
}
}

View File

@ -16,16 +16,15 @@
// under the License.
package org.apache.cloudstack.api.response;
import java.util.ArrayList;
import java.util.List;
import com.cloud.org.Cluster;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import com.cloud.org.Cluster;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
@EntityReference(value = Cluster.class)
public class ClusterResponse extends BaseResponse {
@ -68,7 +67,7 @@ public class ClusterResponse extends BaseResponse {
@SerializedName("cpuovercommitratio") @Param(description = "The cpu overcommit ratio of the cluster")
private String cpuovercommitratio;
@SerializedName("memoryovercommitratio") @Param (description = "The ram overcommit ratio of the cluster")
@SerializedName("memoryovercommitratio") @Param (description = "The memory overcommit ratio of the cluster")
private String memoryovercommitratio;
public String getId() {
@ -162,18 +161,20 @@ public class ClusterResponse extends BaseResponse {
public void setCapacitites(ArrayList<CapacityResponse> arrayList) {
this.capacitites = arrayList;
}
public void setCpuovercommitratio(String cpuovercommitratio){
public void setCpuOvercommitRatio(String cpuovercommitratio){
this.cpuovercommitratio= cpuovercommitratio;
}
public void setRamovercommitratio (String memoryOvercommitRatio){
this.memoryovercommitratio= memoryOvercommitRatio;
}
public String getCpuovercommitratio (){
public String getCpuOvercommitRatio(){
return cpuovercommitratio;
}
public String getRamovercommitratio (){
public void setMemoryOvercommitRatio(String memoryovercommitratio){
this.memoryovercommitratio= memoryovercommitratio;
}
public String getMemoryOvercommitRatio(){
return memoryovercommitratio;
}
}

View File

@ -115,6 +115,9 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR
@SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with ip address", responseObject = ResourceTagResponse.class)
private List<ResourceTagResponse> tags;
@SerializedName(ApiConstants.IS_PORTABLE) @Param(description = "is public IP portable across the zones")
private Boolean isPortable;
/*
@SerializedName(ApiConstants.JOB_ID) @Param(description="shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the volume")
private IdentityProxy jobId = new IdentityProxy("async_job");
@ -247,4 +250,8 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR
public void setAssociatedNetworkName(String associatedNetworkName) {
this.associatedNetworkName = associatedNetworkName;
}
public void setPortable(Boolean portable) {
this.isPortable = portable;
}
}

View File

@ -0,0 +1,93 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.response;
import java.util.Date;
import java.util.List;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import com.cloud.network.IpAddress;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.region.PortableIpRange;
@EntityReference(value=PortableIpRange.class)
public class PortableIpRangeResponse extends BaseResponse {
@SerializedName(ApiConstants.ID)
@Param(description = "portable IP range ID")
private String id;
@SerializedName(ApiConstants.REGION_ID)
@Param(description = "Region Id in which portable ip range is provisioned")
private Integer regionId;
@SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway of the VLAN IP range")
private String gateway;
@SerializedName(ApiConstants.NETMASK) @Param(description="the netmask of the VLAN IP range")
private String netmask;
@SerializedName(ApiConstants.VLAN) @Param(description="the ID or VID of the VLAN.")
private String vlan;
@SerializedName(ApiConstants.START_IP) @Param(description="the start ip of the portable IP range")
private String startIp;
@SerializedName(ApiConstants.END_IP) @Param(description="the end ip of the portable IP range")
private String endIp;
@SerializedName(ApiConstants.PORTABLE_IP_ADDRESS)
@Param(description="List of portable IP and association with zone/network/vpc details that are part of GSLB rule", responseObject = PortableIpResponse.class)
private List<PortableIpResponse> portableIpResponses;
public void setId(String id) {
this.id = id;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
public void setStartIp(String startIp) {
this.startIp = startIp;
}
public void setEndIp(String endIp) {
this.endIp = endIp;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public void setVlan(String vlan) {
this.vlan = vlan;
}
public void setPortableIpResponses(List<PortableIpResponse> portableIpResponses) {
this.portableIpResponses = portableIpResponses;
}
}

View File

@ -0,0 +1,106 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.response;
import java.util.Date;
import java.util.List;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import com.cloud.network.IpAddress;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpRange;
@EntityReference(value=PortableIp.class)
public class PortableIpResponse extends BaseResponse {
@SerializedName(ApiConstants.REGION_ID)
@Param(description = "Region Id in which global load balancer is created")
private Integer regionId;
@SerializedName(ApiConstants.IP_ADDRESS) @Param(description="public IP address")
private String ipAddress;
@SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the zone the public IP address belongs to")
private String zoneId;
@SerializedName(ApiConstants.NETWORK_ID) @Param(description="the ID of the Network where ip belongs to")
private String networkId;
@SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the ip belongs to")
private String vpcId;
@SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to")
private String physicalNetworkId;
@SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the account ID the portable IP address is associated with")
private String accountId;
@SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID the portable IP address is associated with")
private String domainId;
@SerializedName("allocated") @Param(description="date the portal IP address was acquired")
private Date allocated;
@SerializedName(ApiConstants.STATE) @Param(description="State of the ip address. Can be: Allocatin, Allocated and Releasing")
private String state;
public void setRegionId(Integer regionId) {
this.regionId = regionId;
}
public void setAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public void setAssociatedDataCenterId(String zoneId) {
this.zoneId = zoneId;
}
public void setAssociatedWithNetworkId(String networkId) {
this.networkId = networkId;
}
public void setAssociatedWithVpcId(String vpcId) {
this.vpcId = vpcId;
}
public void setPhysicalNetworkId(String physicalNetworkId) {
this.physicalNetworkId = physicalNetworkId;
}
public void setAllocatedToAccountId(String accountId) {
this.accountId = accountId;
}
public void setAllocatedInDomainId(String domainId) {
this.domainId = domainId;
}
public void setAllocatedTime(Date allocatedTimetime) {
this.allocated = allocatedTimetime;
}
public void setState(String state) {
this.state = state;
}
}

View File

@ -0,0 +1,58 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.util.Date;
import com.cloud.utils.net.Ip;
import org.apache.cloudstack.api.InternalIdentity;
public interface PortableIp extends InternalIdentity {
enum State {
Allocating, // The IP Address is being propagated to other network elements and is not ready for use yet.
Allocated, // The IP address is in used.
Releasing, // The IP address is being released for other network elements and is not ready for allocation.
Free // The IP address is ready to be allocated.
}
Long getAllocatedToAccountId();
Long getAllocatedInDomainId();
Date getAllocatedTime();
State getState();
int getRegionId();
Long getAssociatedDataCenterId();
Long getAssociatedWithNetworkId();
Long getAssociatedWithVpcId();
Long getPhysicalNetworkId();
String getAddress();
String getVlan();
String getNetmask();
String getGateway();
}

View File

@ -0,0 +1,38 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import org.apache.cloudstack.acl.InfrastructureEntity;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
public interface PortableIpRange extends InfrastructureEntity, InternalIdentity, Identity {
public final static String UNTAGGED = "untagged";
public String getVlanTag();
public String getGateway();
public String getNetmask();
public int getRegionId();
public String getIpRange();
}

View File

@ -35,8 +35,11 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import javax.inject.Inject;
@ -68,10 +71,12 @@ import com.amazon.ec2.CreateImageResponse;
import com.amazon.ec2.CreateKeyPairResponse;
import com.amazon.ec2.CreateSecurityGroupResponse;
import com.amazon.ec2.CreateSnapshotResponse;
import com.amazon.ec2.CreateTagsResponse;
import com.amazon.ec2.CreateVolumeResponse;
import com.amazon.ec2.DeleteKeyPairResponse;
import com.amazon.ec2.DeleteSecurityGroupResponse;
import com.amazon.ec2.DeleteSnapshotResponse;
import com.amazon.ec2.DeleteTagsResponse;
import com.amazon.ec2.DeleteVolumeResponse;
import com.amazon.ec2.DeregisterImageResponse;
import com.amazon.ec2.DescribeAvailabilityZonesResponse;
@ -82,6 +87,7 @@ import com.amazon.ec2.DescribeInstancesResponse;
import com.amazon.ec2.DescribeKeyPairsResponse;
import com.amazon.ec2.DescribeSecurityGroupsResponse;
import com.amazon.ec2.DescribeSnapshotsResponse;
import com.amazon.ec2.DescribeTagsResponse;
import com.amazon.ec2.DescribeVolumesResponse;
import com.amazon.ec2.DetachVolumeResponse;
import com.amazon.ec2.DisassociateAddressResponse;
@ -122,12 +128,14 @@ import com.cloud.bridge.service.core.ec2.EC2DescribeInstances;
import com.cloud.bridge.service.core.ec2.EC2DescribeKeyPairs;
import com.cloud.bridge.service.core.ec2.EC2DescribeSecurityGroups;
import com.cloud.bridge.service.core.ec2.EC2DescribeSnapshots;
import com.cloud.bridge.service.core.ec2.EC2DescribeTags;
import com.cloud.bridge.service.core.ec2.EC2DescribeVolumes;
import com.cloud.bridge.service.core.ec2.EC2DisassociateAddress;
import com.cloud.bridge.service.core.ec2.EC2Engine;
import com.cloud.bridge.service.core.ec2.EC2Filter;
import com.cloud.bridge.service.core.ec2.EC2GroupFilterSet;
import com.cloud.bridge.service.core.ec2.EC2Image;
import com.cloud.bridge.service.core.ec2.EC2ImageFilterSet;
import com.cloud.bridge.service.core.ec2.EC2ImageAttributes.ImageAttribute;
import com.cloud.bridge.service.core.ec2.EC2ImageLaunchPermission;
import com.cloud.bridge.service.core.ec2.EC2ImportKeyPair;
@ -143,6 +151,10 @@ import com.cloud.bridge.service.core.ec2.EC2SecurityGroup;
import com.cloud.bridge.service.core.ec2.EC2SnapshotFilterSet;
import com.cloud.bridge.service.core.ec2.EC2StartInstances;
import com.cloud.bridge.service.core.ec2.EC2StopInstances;
import com.cloud.bridge.service.core.ec2.EC2TagKeyValue;
import com.cloud.bridge.service.core.ec2.EC2TagTypeId;
import com.cloud.bridge.service.core.ec2.EC2Tags;
import com.cloud.bridge.service.core.ec2.EC2TagsFilterSet;
import com.cloud.bridge.service.core.ec2.EC2Volume;
import com.cloud.bridge.service.core.ec2.EC2VolumeFilterSet;
import com.cloud.bridge.service.exception.EC2ServiceException;
@ -294,6 +306,9 @@ public class EC2RestServlet extends HttpServlet {
else if (action.equalsIgnoreCase( "ImportKeyPair" )) importKeyPair(request, response);
else if (action.equalsIgnoreCase( "DeleteKeyPair" )) deleteKeyPair(request, response);
else if (action.equalsIgnoreCase( "DescribeKeyPairs" )) describeKeyPairs(request, response);
else if (action.equalsIgnoreCase( "CreateTags" )) createTags(request, response);
else if (action.equalsIgnoreCase( "DeleteTags" )) deleteTags(request, response);
else if (action.equalsIgnoreCase( "DescribeTags" )) describeTags(request, response);
else if (action.equalsIgnoreCase( "GetPasswordData" )) getPasswordData(request, response);
else {
logger.error("Unsupported action " + action);
@ -1366,6 +1381,15 @@ public class EC2RestServlet extends HttpServlet {
if (null != value && 0 < value.length) EC2request.addImageSet( value[0] );
}
}
// add filters
EC2Filter[] filterSet = extractFilters( request );
if ( filterSet != null ) {
EC2ImageFilterSet ifs = new EC2ImageFilterSet();
for( int i=0; i < filterSet.length; i++ ) {
ifs.addFilter(filterSet[i]);
}
EC2request.setFilterSet( ifs );
}
// -> execute the request
EC2Engine engine = ServiceProvider.getInstance().getEC2Engine();
DescribeImagesResponse EC2response = EC2SoapServiceImpl.toDescribeImagesResponse( engine.describeImages( EC2request ));
@ -1824,6 +1848,83 @@ public class EC2RestServlet extends HttpServlet {
serializeResponse(response, EC2Response);
}
private void createTags(HttpServletRequest request, HttpServletResponse response)
throws ADBException, XMLStreamException, IOException {
EC2Tags ec2Request = createTagsRequest(request, response);
if (ec2Request == null) return;
CreateTagsResponse EC2Response = EC2SoapServiceImpl.toCreateTagsResponse(
ServiceProvider.getInstance().getEC2Engine().modifyTags( ec2Request, "create"));
serializeResponse(response, EC2Response);
}
private void deleteTags(HttpServletRequest request, HttpServletResponse response)
throws ADBException, XMLStreamException, IOException {
EC2Tags ec2Request = createTagsRequest(request, response);
if (ec2Request == null) return;
DeleteTagsResponse EC2Response = EC2SoapServiceImpl.toDeleteTagsResponse(
ServiceProvider.getInstance().getEC2Engine().modifyTags( ec2Request, "delete"));
serializeResponse(response, EC2Response);
}
private EC2Tags createTagsRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException {
EC2Tags ec2Request = new EC2Tags();
ArrayList<String> resourceIdList = new ArrayList<String>();
Map<String, String> resourceTagList = new HashMap<String, String>();
int nCount = 1;
do {
String[] resourceIds = request.getParameterValues( "ResourceId." + nCount );
if (resourceIds != null && resourceIds.length > 0)
resourceIdList.add(resourceIds[0]);
else break;
nCount++;
} while (true);
if ( resourceIdList.isEmpty() ) {
response.sendError(530, "At least one Resource is required" );
return null;
}
ec2Request = EC2SoapServiceImpl.toResourceTypeAndIds(ec2Request, resourceIdList);
nCount = 1;
do {
String[] tagKey = request.getParameterValues( "Tag." + nCount + ".Key" );
if ( tagKey != null && tagKey.length > 0 ) {
String[] tagValue = request.getParameterValues( "Tag." + nCount + ".Value" );
if ( tagValue != null && tagValue.length > 0 ) {
resourceTagList.put(tagKey[0], tagValue[0]);
} else
resourceTagList.put(tagKey[0], null);
} else break;
nCount++;
} while (true);
if ( resourceTagList.isEmpty() ) {
response.sendError(530, "At least one Tag is required" );
return null;
}
ec2Request = EC2SoapServiceImpl.toResourceTag(ec2Request, resourceTagList);
return ec2Request;
}
private void describeTags(HttpServletRequest request, HttpServletResponse response)
throws ADBException, XMLStreamException, IOException {
EC2DescribeTags ec2Request = new EC2DescribeTags();
EC2Filter[] filterSet = extractFilters( request );
if (null != filterSet) {
EC2TagsFilterSet tfs = new EC2TagsFilterSet();
for( int i=0; i < filterSet.length; i++ )
tfs.addFilter( filterSet[i] );
ec2Request.setFilterSet( tfs );
}
DescribeTagsResponse EC2Response = EC2SoapServiceImpl.toDescribeTagsResponse(
ServiceProvider.getInstance().getEC2Engine().describeTags( ec2Request));
serializeResponse(response, EC2Response);
}
/**
* This function implements the EC2 REST authentication algorithm. It uses the given
* "AWSAccessKeyId" parameter to look up the Cloud.com account holder's secret key which is
@ -2043,8 +2144,9 @@ public class EC2RestServlet extends HttpServlet {
throws ADBException, XMLStreamException, IOException {
OutputStream os = response.getOutputStream();
response.setStatus(200);
response.setContentType("text/xml; charset=UTF-8");
response.setContentType("text/xml");
XMLStreamWriter xmlWriter = xmlOutFactory.createXMLStreamWriter( os );
xmlWriter.writeStartDocument("UTF-8","1.0");
MTOMAwareXMLSerializer MTOMWriter = new MTOMAwareXMLSerializer( xmlWriter );
MTOMWriter.setDefaultNamespace("http://ec2.amazonaws.com/doc/" + wsdlVersion + "/");
EC2Response.serialize( null, factory, MTOMWriter );

View File

@ -18,7 +18,10 @@ package com.cloud.bridge.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.codec.binary.Base64;
@ -48,6 +51,7 @@ import com.cloud.bridge.service.core.ec2.EC2DescribeInstances;
import com.cloud.bridge.service.core.ec2.EC2DescribeInstancesResponse;
import com.cloud.bridge.service.core.ec2.EC2DescribeKeyPairs;
import com.cloud.bridge.service.core.ec2.EC2DescribeKeyPairsResponse;
import com.cloud.bridge.service.core.ec2.EC2ImageFilterSet;
import com.cloud.bridge.service.core.ec2.EC2ImageLaunchPermission;
import com.cloud.bridge.service.core.ec2.EC2ResourceTag;
import com.cloud.bridge.service.core.ec2.EC2DescribeSecurityGroups;
@ -210,87 +214,103 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
public CreateTagsResponse createTags(CreateTags createTags) {
EC2Tags request = new EC2Tags();
ArrayList<String> resourceIdList = new ArrayList<String>();
Map<String, String> resourceTagList = new HashMap<String, String>();
CreateTagsType ctt = createTags.getCreateTags();
ResourceIdSetType resourceIds = ctt.getResourcesSet();
ResourceTagSetType resourceTags = ctt.getTagSet();
request = toResourceTypeAndIds(resourceIds);
//add resource tag's to the request
if (resourceTags != null) {
ResourceTagSetItemType[] items = resourceTags.getItem();
if (items != null) {
for( int i=0; i < items.length; i++ ) {
EC2TagKeyValue param1 = new EC2TagKeyValue();
param1.setKey(items[i].getKey());
param1.setValue(items[i].getValue());
request.addResourceTag(param1);
}
}
ResourceIdSetItemType[] resourceIdItems = resourceIds.getItem();
if (resourceIdItems != null) {
for( int i=0; i < resourceIdItems.length; i++ )
resourceIdList.add(resourceIdItems[i].getResourceId());
}
request = toResourceTypeAndIds(request, resourceIdList);
//add resource tag's to the request
ResourceTagSetItemType[] resourceTagItems = resourceTags.getItem();
if (resourceTagItems != null) {
for( int i=0; i < resourceTagItems.length; i++ )
resourceTagList.put(resourceTagItems[i].getKey(), resourceTagItems[i].getValue());
}
request = toResourceTag(request, resourceTagList);
return toCreateTagsResponse( engine.modifyTags( request, "create"));
}
public DeleteTagsResponse deleteTags(DeleteTags deleteTags) {
EC2Tags request = new EC2Tags();
ArrayList<String> resourceIdList = new ArrayList<String>();
Map<String, String> resourceTagList = new HashMap<String, String>();
DeleteTagsType dtt = deleteTags.getDeleteTags();
ResourceIdSetType resourceIds = dtt.getResourcesSet();
DeleteTagsSetType resourceTags = dtt.getTagSet();
request = toResourceTypeAndIds(resourceIds);
//add resource tag's to the request
if (resourceTags != null) {
DeleteTagsSetItemType[] items = resourceTags.getItem();
if (items != null) {
for( int i=0; i < items.length; i++ ) {
EC2TagKeyValue param1 = new EC2TagKeyValue();
param1.setKey(items[i].getKey());
if (items[i].getValue() != null)
param1.setValue(items[i].getValue());
request.addResourceTag(param1);
}
}
ResourceIdSetItemType[] resourceIdItems = resourceIds.getItem();
if (resourceIdItems != null) {
for( int i=0; i < resourceIdItems.length; i++ )
resourceIdList.add(resourceIdItems[i].getResourceId());
}
request = toResourceTypeAndIds(request, resourceIdList);
//add resource tag's to the request
DeleteTagsSetItemType[] resourceTagItems = resourceTags.getItem();
if (resourceTagItems != null) {
for( int i=0; i < resourceTagItems.length; i++ )
resourceTagList.put(resourceTagItems[i].getKey(), resourceTagItems[i].getValue());
}
request = toResourceTag(request, resourceTagList);
return toDeleteTagsResponse( engine.modifyTags( request, "delete"));
}
private EC2Tags toResourceTypeAndIds(ResourceIdSetType resourceIds) {
EC2Tags request = new EC2Tags();
//add resource-type and resource-id's to the request
if (resourceIds != null) {
ResourceIdSetItemType[] items = resourceIds.getItem();
List<String> resourceTypeList = new ArrayList<String>();
if (items != null) {
for( int i=0; i < items.length; i++ ) {
if (!items[i].getResourceId().contains(":") || items[i].getResourceId().split(":").length != 2) {
throw new EC2ServiceException( ClientError.InvalidResourceId_Format,
"Invalid Format. ResourceId format is resource-type:resource-uuid");
}
String resourceType = items[i].getResourceId().split(":")[0];
if (resourceTypeList.isEmpty())
resourceTypeList.add(resourceType);
else {
Boolean existsInList = false;
for (String addedResourceType : resourceTypeList) {
if (addedResourceType.equalsIgnoreCase(resourceType)) {
existsInList = true;
break;
}
}
if (!existsInList)
resourceTypeList.add(resourceType);
}
}
for (String resourceType : resourceTypeList){
EC2TagTypeId param1 = new EC2TagTypeId();
param1.setResourceType(resourceType);
for( int i=0; i < items.length; i++ ) {
String[] resourceTag = items[i].getResourceId().split(":");
if (resourceType.equals(resourceTag[0]))
param1.addResourceId(resourceTag[1]);
}
request.addResourceType(param1);
}
public static EC2Tags toResourceTypeAndIds( EC2Tags request, ArrayList<String> resourceIdList ) {
List<String> resourceTypeList = new ArrayList<String>();
for (String resourceId : resourceIdList) {
if (!resourceId.contains(":") || resourceId.split(":").length != 2) {
throw new EC2ServiceException( ClientError.InvalidResourceId_Format,
"Invalid Format. ResourceId format is resource-type:resource-uuid");
}
String resourceType = resourceId.split(":")[0];
if (resourceTypeList.isEmpty())
resourceTypeList.add(resourceType);
else {
Boolean existsInList = false;
for (String addedResourceType : resourceTypeList) {
if (addedResourceType.equalsIgnoreCase(resourceType)) {
existsInList = true;
break;
}
}
if (!existsInList)
resourceTypeList.add(resourceType);
}
}
for (String resourceType : resourceTypeList) {
EC2TagTypeId param1 = new EC2TagTypeId();
param1.setResourceType(resourceType);
for (String resourceId : resourceIdList) {
String[] resourceTag = resourceId.split(":");
if (resourceType.equals(resourceTag[0]))
param1.addResourceId(resourceTag[1]);
}
request.addResourceType(param1);
}
return request;
}
public static EC2Tags toResourceTag( EC2Tags request, Map<String, String> resourceTagList ) {
Set<String> resourceTagKeySet = resourceTagList.keySet();
for (String resourceTagKey : resourceTagKeySet) {
EC2TagKeyValue param1 = new EC2TagKeyValue();
param1.setKey(resourceTagKey);
param1.setValue(resourceTagList.get(resourceTagKey));
request.addResourceTag(param1);
}
return request;
}
@ -388,7 +408,10 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
for( int i=0; i < items3.length; i++ ) request.addOwnersSet( items3[i].getOwner());
}
}
FilterSetType fst = dit.getFilterSet();
if ( fst != null) {
request.setFilterSet(toImageFilterSet(fst));
}
return toDescribeImagesResponse( engine.describeImages( request ));
}
@ -929,7 +952,7 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
DescribeImagesResponseItemType param3 = new DescribeImagesResponseItemType();
param3.setImageId( images[i].getId());
param3.setImageLocation( "" );
param3.setImageState( (images[i].getIsReady() ? "available" : "unavailable" ));
param3.setImageState( images[i].getState());
param3.setImageOwnerId(ownerId);
param3.setIsPublic( images[i].getIsPublic());
@ -941,16 +964,14 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
String description = images[i].getDescription();
param3.setDescription( (null == description ? "" : description));
if (null == description) param3.setArchitecture( "" );
else if (-1 != description.indexOf( "x86_64" )) param3.setArchitecture( "x86_64" );
else if (-1 != description.indexOf( "i386" )) param3.setArchitecture( "i386" );
else param3.setArchitecture( "" );
param3.setImageType( "machine" );
param3.setArchitecture( images[i].getArchitecture());
param3.setImageType( images[i].getImageType());
param3.setKernelId( "" );
param3.setRamdiskId( "" );
param3.setPlatform( "" );
param3.setHypervisor( images[i].getHypervisor());
StateReasonType param6 = new StateReasonType();
param6.setCode( "" );
@ -1268,6 +1289,27 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
return tfs;
}
private EC2ImageFilterSet toImageFilterSet( FilterSetType fst ) {
EC2ImageFilterSet ifs = new EC2ImageFilterSet();
FilterType[] items = fst.getItem();
if (items != null) {
for (FilterType item : items) {
EC2Filter oneFilter = new EC2Filter();
String filterName = item.getName();
oneFilter.setName( filterName );
ValueSetType vft = item.getValueSet();
ValueType[] valueItems = vft.getItem();
for (ValueType valueItem : valueItems) {
oneFilter.addValueEncoded( valueItem.getValue());
}
ifs.addFilter( oneFilter );
}
}
return ifs;
}
// toMethods
public static DescribeVolumesResponse toDescribeVolumesResponse( EC2DescribeVolumesResponse engineResponse )
{

View File

@ -24,6 +24,7 @@ public class EC2DescribeImages {
private List<String> executableBySet = new ArrayList<String>();; // a list of strings identifying users
private List<String> imageSet = new ArrayList<String>(); // a list of AMI id's
private List<String> ownersSet = new ArrayList<String>(); // a list of AMI owner id's
private EC2ImageFilterSet ifs = null;
public EC2DescribeImages() {
}
@ -51,4 +52,13 @@ public class EC2DescribeImages {
public String[] getOwnersSet() {
return ownersSet.toArray(new String[0]);
}
public EC2ImageFilterSet getFilterSet() {
return ifs;
}
public void setFilterSet( EC2ImageFilterSet param ) {
ifs = param;
}
}

View File

@ -902,15 +902,19 @@ public class EC2Engine extends ManagerBase {
try {
String[] templateIds = request.getImageSet();
EC2ImageFilterSet ifs = request.getFilterSet();
if ( 0 == templateIds.length ) {
return listTemplates(null, images);
if ( templateIds.length == 0 ) {
images = listTemplates(null, images);
} else {
for (String s : templateIds) {
images = listTemplates(s, images);
}
}
for (String s : templateIds) {
images = listTemplates(s, images);
}
return images;
if (ifs == null)
return images;
else
return ifs.evaluate(images);
} catch( Exception e ) {
logger.error( "EC2 DescribeImages - ", e);
throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
@ -1454,7 +1458,7 @@ public class EC2Engine extends ManagerBase {
vm.setIpAddress(resp.getIpAddress());
vm.setAccountName(resp.getAccountName());
vm.setDomainId(resp.getDomainId());
vm.setHypervisor(resp.getHypervisor());
vm.setHypervisor( mapToAmazonHypervisorType(resp.getHypervisor()) );
vm.setServiceOffering( svcOffering.getName());
vm.setKeyPairName(resp.getKeyPairName());
instances.addInstance(vm);
@ -1856,7 +1860,7 @@ public class EC2Engine extends ManagerBase {
ec2Vm.setIpAddress(cloudVm.getIpAddress());
ec2Vm.setAccountName(cloudVm.getAccountName());
ec2Vm.setDomainId(cloudVm.getDomainId());
ec2Vm.setHypervisor(cloudVm.getHypervisor());
ec2Vm.setHypervisor( mapToAmazonHypervisorType(cloudVm.getHypervisor()) );
ec2Vm.setRootDeviceType(cloudVm.getRootDeviceType());
ec2Vm.setRootDeviceId(cloudVm.getRootDeviceId());
ec2Vm.setServiceOffering(serviceOfferingIdToInstanceType(cloudVm.getServiceOfferingId().toString()));
@ -1951,8 +1955,22 @@ public class EC2Engine extends ManagerBase {
ec2Image.setDescription(temp.getDisplayText());
ec2Image.setOsTypeId(temp.getOsTypeId().toString());
ec2Image.setIsPublic(temp.getIsPublic());
ec2Image.setIsReady(temp.getIsReady());
ec2Image.setState( temp.getIsReady() ? "available" : "pending");
ec2Image.setDomainId(temp.getDomainId());
if ( temp.getHyperVisor().equalsIgnoreCase("xenserver"))
ec2Image.setHypervisor("xen");
else if ( temp.getHyperVisor().equalsIgnoreCase("ovm"))
ec2Image.setHypervisor( "ovm"); // valid values for hypervisor is 'ovm' and 'xen'
else
ec2Image.setHypervisor("");
if (temp.getDisplayText() == null)
ec2Image.setArchitecture("");
else if (temp.getDisplayText().indexOf( "x86_64" ) != -1)
ec2Image.setArchitecture("x86_64");
else if (temp.getDisplayText().indexOf( "i386" ) != -1)
ec2Image.setArchitecture("i386");
else
ec2Image.setArchitecture("");
List<CloudStackKeyValue> resourceTags = temp.getTags();
for(CloudStackKeyValue resourceTag : resourceTags) {
EC2TagKeyValue param = new EC2TagKeyValue();
@ -2480,6 +2498,21 @@ public class EC2Engine extends ManagerBase {
return (resourceType.toLowerCase());
}
/**
* Map CloudStack hypervisor to CloudStack hypervisor
*
* @param CloudStack hypervisor
* @return Amazon hypervisor
*/
private String mapToAmazonHypervisorType( String hypervisor) {
if (hypervisor.equalsIgnoreCase("Xenserver"))
return("xen");
else if(hypervisor.equalsIgnoreCase("Ovm"))
return("ovm");
else
return ("");
}
/**
* Stop an instance
* Wait until one specific VM has stopped

View File

@ -28,10 +28,13 @@ public class EC2Image {
private String name;
private String description;
private String osTypeId;
private boolean isPublic;
private boolean isReady;
private Boolean isPublic;
private String state;
private String accountName;
private String domainId;
private String domainId;
private String hypervisor;
private String architecture;
private String imageType;
private List<EC2TagKeyValue> tagsSet;
public EC2Image() {
@ -40,9 +43,12 @@ public class EC2Image {
description = null;
osTypeId = null;
isPublic = false;
isReady = false;
state = null;
accountName = null;
domainId = null;
domainId = null;
hypervisor = null;
architecture = null;
imageType = "machine";
tagsSet = new ArrayList<EC2TagKeyValue>();
}
@ -78,21 +84,21 @@ public class EC2Image {
return this.osTypeId;
}
public void setIsPublic( boolean isPublic ) {
this.isPublic = isPublic;
}
public boolean getIsPublic() {
return this.isPublic;
}
public void setIsPublic( Boolean isPublic ) {
this.isPublic = isPublic;
}
public void setIsReady( boolean isReady ) {
this.isReady = isReady;
}
public boolean getIsReady() {
return this.isReady;
}
public Boolean getIsPublic() {
return this.isPublic;
}
public void setState( String state ) {
this.state = state;
}
public String getState() {
return this.state;
}
public String getAccountName() {
return accountName;
@ -110,6 +116,25 @@ public class EC2Image {
this.domainId = domainId;
}
public String getHypervisor() {
return hypervisor;
}
public void setHypervisor(String hypervisor) {
this.hypervisor = hypervisor;
}
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public String getImageType() {
return imageType;
}
public void addResourceTag( EC2TagKeyValue param ) {
tagsSet.add( param );

View File

@ -0,0 +1,168 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.bridge.service.core.ec2;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.bridge.service.exception.EC2ServiceException;
public class EC2ImageFilterSet {
protected final static Logger logger = Logger.getLogger(EC2ImageFilterSet.class);
protected List<EC2Filter> filterSet = new ArrayList<EC2Filter>();
private Map<String,String> filterTypes = new HashMap<String,String>();
public EC2ImageFilterSet() {
// -> supported filters
filterTypes.put( "architecture", "string" );
filterTypes.put( "description", "string" );
filterTypes.put( "hypervisor", "string" );
filterTypes.put( "image-id", "string" );
filterTypes.put( "image-type", "string" );
filterTypes.put( "is-public", "Boolean" );
filterTypes.put( "name", "string" );
filterTypes.put( "owner-id", "string" );
filterTypes.put( "state", "string" );
filterTypes.put( "tag-key", "string" );
filterTypes.put( "tag-value", "string" );
}
public void addFilter( EC2Filter param ) {
String filterName = param.getName();
if ( !filterName.startsWith("tag:") ) {
String value = (String) filterTypes.get( filterName );
if (null == value)
throw new EC2ServiceException( "Unsupported filter [" + filterName + "] - 1", 501 );
if (null != value && value.equalsIgnoreCase( "null" ))
throw new EC2ServiceException( "Unsupported filter [" + filterName + "] - 2", 501 );
}
filterSet.add( param );
}
public EC2Filter[] getFilterSet() {
return filterSet.toArray(new EC2Filter[0]);
}
public EC2DescribeImagesResponse evaluate( EC2DescribeImagesResponse sampleList) throws ParseException {
EC2DescribeImagesResponse resultList = new EC2DescribeImagesResponse();
boolean matched;
EC2Image[] imageSet = sampleList.getImageSet();
EC2Filter[] filterSet = getFilterSet();
for (EC2Image image : imageSet) {
matched = true;
for (EC2Filter filter : filterSet) {
if (!filterMatched(image, filter)) {
matched = false;
break;
}
}
if (matched == true)
resultList.addImage(image);
}
return resultList;
}
private boolean filterMatched( EC2Image image, EC2Filter filter ) throws ParseException {
String filterName = filter.getName();
String[] valueSet = filter.getValueSet();
if ( filterName.equalsIgnoreCase( "architecture" ))
return containsString( image.getArchitecture(), valueSet );
if ( filterName.equalsIgnoreCase( "description" ))
return containsString( image.getDescription(), valueSet );
if ( filterName.equalsIgnoreCase( "hypervisor" ))
return containsString( image.getHypervisor(), valueSet );
if ( filterName.equalsIgnoreCase( "image-id" ))
return containsString( image.getId(), valueSet );
if ( filterName.equalsIgnoreCase( "image-type" ))
return containsString( image.getImageType(), valueSet );
if ( filterName.equalsIgnoreCase( "is-public" ))
return image.getIsPublic().toString().equalsIgnoreCase(valueSet[0]);
if ( filterName.equalsIgnoreCase( "name" ))
return containsString( image.getName(), valueSet );
if ( filterName.equalsIgnoreCase( "owner-id" )) {
String owner = new String( image.getDomainId() + ":" + image.getAccountName());
return containsString( owner, valueSet );
}
if ( filterName.equalsIgnoreCase( "state" ))
return containsString( image.getState(), valueSet );
else if (filterName.equalsIgnoreCase("tag-key"))
{
EC2TagKeyValue[] tagSet = image.getResourceTags();
for (EC2TagKeyValue tag : tagSet)
if (containsString(tag.getKey(), valueSet)) return true;
return false;
}
else if (filterName.equalsIgnoreCase("tag-value"))
{
EC2TagKeyValue[] tagSet = image.getResourceTags();
for (EC2TagKeyValue tag : tagSet){
if (tag.getValue() == null) {
if (containsEmptyValue(valueSet)) return true;
}
else {
if (containsString(tag.getValue(), valueSet)) return true;
}
}
return false;
}
else if (filterName.startsWith("tag:"))
{
String key = filterName.split(":")[1];
EC2TagKeyValue[] tagSet = image.getResourceTags();
for (EC2TagKeyValue tag : tagSet){
if (tag.getKey().equalsIgnoreCase(key)) {
if (tag.getValue() == null) {
if (containsEmptyValue(valueSet)) return true;
}
else {
if (containsString(tag.getValue(), valueSet)) return true;
}
}
}
return false;
}
else return false;
}
private boolean containsString( String lookingFor, String[] set ) {
if (lookingFor == null)
return false;
for (String filter: set) {
if (lookingFor.matches( filter )) return true;
}
return false;
}
private boolean containsEmptyValue( String[] set ) {
for( int i=0; i < set.length; i++ ) {
if (set[i].isEmpty()) return true;
}
return false;
}
}

View File

@ -271,6 +271,8 @@
<bean id="physicalNetworkTrafficTypeDaoImpl" class="com.cloud.network.dao.PhysicalNetworkTrafficTypeDaoImpl" />
<bean id="podVlanDaoImpl" class="com.cloud.dc.dao.PodVlanDaoImpl" />
<bean id="podVlanMapDaoImpl" class="com.cloud.dc.dao.PodVlanMapDaoImpl" />
<bean id="PortableIpDaoImpl" class="org.apache.cloudstack.region.PortableIpDaoImpl" />
<bean id="PortableIpRangeDaoImpl" class="org.apache.cloudstack.region.PortableIpRangeDaoImpl" />
<bean id="portForwardingRulesDaoImpl" class="com.cloud.network.rules.dao.PortForwardingRulesDaoImpl" />
<bean id="portProfileDaoImpl" class="com.cloud.network.dao.PortProfileDaoImpl" />
<bean id="primaryDataStoreDaoImpl" class="org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl" />

View File

@ -628,6 +628,11 @@ addCiscoAsa1000vResource=1
deleteCiscoAsa1000vResource=1
listCiscoAsa1000vResources=1
#### portable public IP commands
createPortableIpRange=1
deletePortableIpRange=1
listPortableIpRanges=1
#### Internal LB VM commands
stopInternalLoadBalancerVM=1
startInternalLoadBalancerVM=1
@ -635,3 +640,4 @@ listInternalLoadBalancerVMs=1
### Network Isolation methods listing
listNetworkIsolationMethods=1

View File

@ -28,7 +28,6 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand {
public CreateEntityDownloadURLCommand(String installPath, String uuid) {
super();
this.parent = parent;
this.installPath = installPath;
this.extractLinkUUID = uuid;
}

View File

@ -110,7 +110,7 @@ import java.util.List;
dnsServers = dnsServers+dnsMasqconfigcmd.getDns2()+",";
}
dnsServers = dnsServers +"*";
dnsServers = dnsServers.replace(";*", "");
dnsServers = dnsServers.replace(",*", "");
dnsMasqconf.set(24,"dhcp-option=6,"+dnsServers);
return dnsMasqconf.toArray( new String[dnsMasqconf.size()]);
}

2
debian/rules vendored
View File

@ -80,6 +80,7 @@ install:
mkdir -p $(DESTDIR)/$(SYSCONFDIR)/sudoers.d/
mkdir -p $(DESTDIR)/usr/share/$(PACKAGE)-management
mkdir -p $(DESTDIR)/usr/share/$(PACKAGE)-management/webapps/client
mkdir -p $(DESTDIR)/usr/share/$(PACKAGE)-management/webapps7080
mkdir $(DESTDIR)/usr/share/$(PACKAGE)-management/setup
mkdir $(DESTDIR)/var/log/$(PACKAGE)/management
mkdir $(DESTDIR)/var/cache/$(PACKAGE)/management
@ -153,6 +154,7 @@ install:
mkdir $(DESTDIR)/usr/share/$(PACKAGE)-bridge
mkdir -p $(DESTDIR)/usr/share/$(PACKAGE)-bridge/webapps/awsapi
mkdir $(DESTDIR)/usr/share/$(PACKAGE)-bridge/setup
ln -s /usr/share/$(PACKAGE)-bridge/webapps/awsapi $(DESTDIR)/usr/share/$(PACKAGE)-management/webapps7080/awsapi
cp -r awsapi/target/cloud-awsapi-$(VERSION)-SNAPSHOT/* $(DESTDIR)/usr/share/$(PACKAGE)-bridge/webapps/awsapi
install -D awsapi-setup/setup/cloud-setup-bridge $(DESTDIR)/usr/bin/cloudstack-setup-bridge
install -D awsapi-setup/setup/cloudstack-aws-api-register $(DESTDIR)/usr/bin/cloudstack-aws-api-register

View File

@ -21,10 +21,6 @@ package org.apache.cloudstack.engine.subsystem.api.storage;
public abstract class AbstractScope implements Scope {
@Override
public boolean isSameScope(Scope scope) {
if (this.getScopeType() == scope.getScopeType() && this.getScopeId() == scope.getScopeId()) {
return true;
} else {
return false;
}
return this.getScopeType() == scope.getScopeType() && this.getScopeId().equals(scope.getScopeId());
}
}

View File

@ -24,6 +24,7 @@ import java.util.UUID;
import javax.inject.Inject;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO;
import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO;
import org.apache.cloudstack.engine.cloud.entity.api.db.dao.VMEntityDao;
@ -60,6 +61,7 @@ import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.VirtualMachineProfileImpl;
@ -111,6 +113,9 @@ public class VMEntityManagerImpl implements VMEntityManager {
@Inject
DeploymentPlanningManager _dpMgr;
@Inject
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Override
public VMEntityVO loadVirtualMachine(String vmId) {
// TODO Auto-generated method stub
@ -123,6 +128,16 @@ public class VMEntityManagerImpl implements VMEntityManager {
}
protected boolean areAffinityGroupsAssociated(VirtualMachineProfile<? extends VirtualMachine> vmProfile) {
VirtualMachine vm = vmProfile.getVirtualMachine();
long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
if (vmGroupCount > 0) {
return true;
}
return false;
}
@Override
public String reserveVirtualMachine(VMEntityVO vmEntityVO, String plannerToUse, DeploymentPlan planToDeploy, ExcludeList exclude)
throws InsufficientCapacityException, ResourceUnavailableException {
@ -194,7 +209,8 @@ public class VMEntityManagerImpl implements VMEntityManager {
// call retry it.
return UUID.randomUUID().toString();
}else{
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId());
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile,
DataCenter.class, plan.getDataCenterId(), areAffinityGroupsAssociated(vmProfile));
}
}

View File

@ -43,6 +43,7 @@ public class AlertDaoImpl extends GenericDaoBase<AlertVO, Long> implements Alert
AlertSearchByIdsAndType.and("type", AlertSearchByIdsAndType.entity().getType(), Op.EQ);
AlertSearchByIdsAndType.and("createdDateL", AlertSearchByIdsAndType.entity().getCreatedDate(), Op.LT);
AlertSearchByIdsAndType.and("data_center_id", AlertSearchByIdsAndType.entity().getDataCenterId(), Op.EQ);
AlertSearchByIdsAndType.and("archived", AlertSearchByIdsAndType.entity().getArchived(), Op.EQ);
AlertSearchByIdsAndType.done();
}
@ -53,6 +54,7 @@ public class AlertDaoImpl extends GenericDaoBase<AlertVO, Long> implements Alert
sc.addAnd("type", SearchCriteria.Op.EQ, Short.valueOf(type));
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, Long.valueOf(dataCenterId));
sc.addAnd("archived", SearchCriteria.Op.EQ, false);
if (podId != null) {
sc.addAnd("podId", SearchCriteria.Op.EQ, podId);
}
@ -74,6 +76,7 @@ public class AlertDaoImpl extends GenericDaoBase<AlertVO, Long> implements Alert
sc.addAnd("type", SearchCriteria.Op.EQ, Short.valueOf(type));
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, Long.valueOf(dataCenterId));
sc.addAnd("archived", SearchCriteria.Op.EQ, false);
if (podId != null) {
sc.addAnd("podId", SearchCriteria.Op.EQ, podId);
}
@ -101,6 +104,8 @@ public class AlertDaoImpl extends GenericDaoBase<AlertVO, Long> implements Alert
if(olderThan != null) {
sc.setParameters("createdDateL", olderThan);
}
sc.setParameters("archived", false);
boolean result = true;;
List<AlertVO> alerts = listBy(sc);
if (Ids != null && alerts.size() < Ids.size()) {
@ -135,6 +140,8 @@ public class AlertDaoImpl extends GenericDaoBase<AlertVO, Long> implements Alert
if(olderThan != null) {
sc.setParameters("createdDateL", olderThan);
}
sc.setParameters("archived", false);
boolean result = true;
List<AlertVO> alerts = listBy(sc);
if (ids != null && alerts.size() < ids.size()) {
@ -150,6 +157,7 @@ public class AlertDaoImpl extends GenericDaoBase<AlertVO, Long> implements Alert
if (oldTime == null) return null;
SearchCriteria<AlertVO> sc = createSearchCriteria();
sc.addAnd("createDate", SearchCriteria.Op.LT, oldTime);
sc.addAnd("archived", SearchCriteria.Op.EQ, false);
return listIncludingRemovedBy(sc, null);
}

View File

@ -55,4 +55,6 @@ public interface ResourceCountDao extends GenericDao<ResourceCountVO, Long> {
Set<Long> listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type);
Set<Long> listRowsToUpdateForDomain(long domainId, ResourceType type);
long removeEntriesByOwner(long ownerId, ResourceOwnerType ownerType);
}

View File

@ -219,4 +219,20 @@ public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long>
return super.persist(resourceCountVO);
}
@Override
public long removeEntriesByOwner(long ownerId, ResourceOwnerType ownerType) {
SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId);
return remove(sc);
} else if (ownerType == ResourceOwnerType.Domain) {
sc.setParameters("domainId", ownerId);
return remove(sc);
}
return 0;
}
}

View File

@ -32,4 +32,6 @@ public interface ResourceLimitDao extends GenericDao<ResourceLimitVO, Long> {
ResourceCount.ResourceType getLimitType(String type);
ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type);
long removeEntriesByOwner(Long ownerId, ResourceOwnerType ownerType);
}

View File

@ -97,4 +97,18 @@ public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long>
return null;
}
}
@Override
public long removeEntriesByOwner(Long ownerId, ResourceOwnerType ownerType) {
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId);
return remove(sc);
} else if (ownerType == ResourceOwnerType.Domain) {
sc.setParameters("domainId", ownerId);
return remove(sc);
}
return 0;
}
}

View File

@ -44,6 +44,7 @@ public class EventDaoImpl extends GenericDaoBase<EventVO, Long> implements Event
CompletedEventSearch = createSearchBuilder();
CompletedEventSearch.and("state",CompletedEventSearch.entity().getState(),SearchCriteria.Op.EQ);
CompletedEventSearch.and("startId", CompletedEventSearch.entity().getStartId(), SearchCriteria.Op.EQ);
CompletedEventSearch.and("archived", CompletedEventSearch.entity().getArchived(), Op.EQ);
CompletedEventSearch.done();
ToArchiveOrDeleteEventSearch = createSearchBuilder();
@ -51,6 +52,7 @@ public class EventDaoImpl extends GenericDaoBase<EventVO, Long> implements Event
ToArchiveOrDeleteEventSearch.and("type", ToArchiveOrDeleteEventSearch.entity().getType(), Op.EQ);
ToArchiveOrDeleteEventSearch.and("accountIds", ToArchiveOrDeleteEventSearch.entity().getAccountId(), Op.IN);
ToArchiveOrDeleteEventSearch.and("createDateL", ToArchiveOrDeleteEventSearch.entity().getCreateDate(), Op.LT);
ToArchiveOrDeleteEventSearch.and("archived", ToArchiveOrDeleteEventSearch.entity().getArchived(), Op.EQ);
ToArchiveOrDeleteEventSearch.done();
}
@ -64,6 +66,7 @@ public class EventDaoImpl extends GenericDaoBase<EventVO, Long> implements Event
if (oldTime == null) return null;
SearchCriteria<EventVO> sc = createSearchCriteria();
sc.addAnd("createDate", SearchCriteria.Op.LT, oldTime);
sc.addAnd("archived", SearchCriteria.Op.EQ, false);
return listIncludingRemovedBy(sc, null);
}
@ -72,6 +75,7 @@ public class EventDaoImpl extends GenericDaoBase<EventVO, Long> implements Event
SearchCriteria<EventVO> sc = CompletedEventSearch.create();
sc.setParameters("state", State.Completed);
sc.setParameters("startId", startId);
sc.setParameters("archived", false);
return findOneIncludingRemovedBy(sc);
}
@ -90,6 +94,7 @@ public class EventDaoImpl extends GenericDaoBase<EventVO, Long> implements Event
if (accountIds != null && !accountIds.isEmpty()) {
sc.setParameters("accountIds", accountIds.toArray(new Object[accountIds.size()]));
}
sc.setParameters("archived", false);
return search(sc, null);
}

View File

@ -198,7 +198,7 @@ public class ExternalLoadBalancerDeviceVO implements InternalIdentity, Identity
}
public void setGslbProvider(boolean gslbProvider) {
gslbProvider = gslbProvider;
this.gslbProvider = gslbProvider;
}
public void setGslbSitePublicIP(String gslbSitePublicIP) {

View File

@ -111,6 +111,8 @@ public class IPAddressVO implements IpAddress {
@Column(name="dnat_vmip")
private String vmIp;
@Column(name="is_portable")
private boolean portable = false;
protected IPAddressVO() {
this.uuid = UUID.randomUUID().toString();
@ -134,6 +136,19 @@ public class IPAddressVO implements IpAddress {
this.uuid = UUID.randomUUID().toString();
}
public IPAddressVO(Ip address, long dataCenterId, Long networkId, Long vpcId, long physicalNetworkId, long sourceNetworkId,
long vlanDbId, boolean portable) {
this.address = address;
this.dataCenterId = dataCenterId;
this.associatedWithNetworkId = networkId;
this.vpcId = vpcId;
this.physicalNetworkId = physicalNetworkId;
this.sourceNetworkId = sourceNetworkId;
this.vlanId = vlanDbId;
this.portable = portable;
this.uuid = UUID.randomUUID().toString();
}
public long getMacAddress() {
return macAddress;
}
@ -283,6 +298,15 @@ public class IPAddressVO implements IpAddress {
this.system = isSystem;
}
@Override
public boolean isPortable() {
return portable;
}
public void setPortable(boolean portable) {
this.portable = portable;
}
@Override
public Long getVpcId() {
return vpcId;

View File

@ -19,6 +19,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-framework-jobs</artifactId>
<name>Apache CloudStack Framework - Jobs</name>
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack-framework</artifactId>

View File

@ -17,17 +17,24 @@
package org.apache.cloudstack.affinity;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.framework.messagebus.MessageSubscriber;
import org.apache.log4j.Logger;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.exception.AffinityConflictException;
import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
@ -46,7 +53,10 @@ public class HostAntiAffinityProcessor extends AffinityProcessorBase implements
protected AffinityGroupDao _affinityGroupDao;
@Inject
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
private int _vmCapacityReleaseInterval;
@Inject
protected ConfigurationDao _configDao;
@Override
public void process(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan,
ExcludeList avoid)
@ -76,12 +86,14 @@ public class HostAntiAffinityProcessor extends AffinityProcessorBase implements
}
} else if (VirtualMachine.State.Stopped.equals(groupVM.getState())
&& groupVM.getLastHostId() != null) {
avoid.addHost(groupVM.getLastHostId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Added host " + groupVM.getLastHostId() + " to avoid set, since VM "
+ groupVM.getId() + " is present on the host, in Stopped state");
long secondsSinceLastUpdate = (DateUtil.currentGMTTime().getTime() - groupVM.getUpdateTime().getTime()) / 1000;
if (secondsSinceLastUpdate < _vmCapacityReleaseInterval) {
avoid.addHost(groupVM.getLastHostId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Added host " + groupVM.getLastHostId() + " to avoid set, since VM "
+ groupVM.getId() + " is present on the host, in Stopped state but has reserved capacity");
}
}
}
}
}
@ -89,5 +101,12 @@ public class HostAntiAffinityProcessor extends AffinityProcessorBase implements
}
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
_vmCapacityReleaseInterval = NumbersUtil.parseInt(_configDao.getValue(Config.CapacitySkipcountingHours.key()),3600);
return true;
}
}

View File

@ -35,6 +35,7 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.diskProtocol;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef.nicModel;
@ -64,31 +65,45 @@ public class LibvirtDomainXMLParser {
NodeList disks = devices.getElementsByTagName("disk");
for (int i = 0; i < disks.getLength(); i++) {
Element disk = (Element) disks.item(i);
String diskFmtType = getAttrValue("driver", "type", disk);
String diskFile = getAttrValue("source", "file", disk);
String diskDev = getAttrValue("source", "dev", disk);
String diskLabel = getAttrValue("target", "dev", disk);
String bus = getAttrValue("target", "bus", disk);
String type = disk.getAttribute("type");
String device = disk.getAttribute("device");
DiskDef def = new DiskDef();
if (type.equalsIgnoreCase("file")) {
if (device.equalsIgnoreCase("disk")) {
DiskDef.diskFmtType fmt = null;
if (diskFmtType != null) {
fmt = DiskDef.diskFmtType.valueOf(diskFmtType
.toUpperCase());
if (type.equalsIgnoreCase("network")) {
String diskFmtType = getAttrValue("driver", "type", disk);
String diskPath = getAttrValue("source", "name", disk);
String protocol = getAttrValue("source", "protocol", disk);
String authUserName = getAttrValue("auth", "username", disk);
String poolUuid = getAttrValue("secret", "uuid", disk);
String host = getAttrValue("host", "name", disk);
int port = Integer.parseInt(getAttrValue("host", "port", disk));
String diskLabel = getAttrValue("target", "dev", disk);
String bus = getAttrValue("target", "bus", disk);
def.defNetworkBasedDisk(diskPath, host, port, authUserName, poolUuid, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()), DiskDef.diskProtocol.valueOf(protocol.toUpperCase()));
} else {
String diskFmtType = getAttrValue("driver", "type", disk);
String diskFile = getAttrValue("source", "file", disk);
String diskDev = getAttrValue("source", "dev", disk);
String diskLabel = getAttrValue("target", "dev", disk);
String bus = getAttrValue("target", "bus", disk);
String device = disk.getAttribute("device");
if (type.equalsIgnoreCase("file")) {
if (device.equalsIgnoreCase("disk")) {
DiskDef.diskFmtType fmt = null;
if (diskFmtType != null) {
fmt = DiskDef.diskFmtType.valueOf(diskFmtType
.toUpperCase());
}
def.defFileBasedDisk(diskFile, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()), fmt);
} else if (device.equalsIgnoreCase("cdrom")) {
def.defISODisk(diskFile);
}
def.defFileBasedDisk(diskFile, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()), fmt);
} else if (device.equalsIgnoreCase("cdrom")) {
def.defISODisk(diskFile);
} else if (type.equalsIgnoreCase("block")) {
def.defBlockBasedDisk(diskDev, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()));
}
} else if (type.equalsIgnoreCase("block")) {
def.defBlockBasedDisk(diskDev, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()));
}
diskDefs.add(def);
}

View File

@ -16,24 +16,6 @@
// under the License.
package com.cloud.hypervisor.xen.discoverer;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.persistence.EntityExistsException;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
@ -65,6 +47,7 @@ import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.xen.resource.CitrixResourceBase;
import com.cloud.hypervisor.xen.resource.XcpOssResource;
import com.cloud.hypervisor.xen.resource.XcpServer16Resource;
import com.cloud.hypervisor.xen.resource.XcpServerResource;
import com.cloud.hypervisor.xen.resource.XenServer56FP1Resource;
import com.cloud.hypervisor.xen.resource.XenServer56Resource;
@ -79,9 +62,9 @@ import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.user.Account;
@ -97,6 +80,22 @@ import com.xensource.xenapi.Pool;
import com.xensource.xenapi.Session;
import com.xensource.xenapi.Types.SessionAuthenticationFailed;
import com.xensource.xenapi.Types.XenAPIException;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.persistence.EntityExistsException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
@Local(value=Discoverer.class)
public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter {
@ -316,6 +315,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L
details.put("wait", Integer.toString(_wait));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
params.put(Config.XenMaxNics.toString().toLowerCase(), _configDao.getValue(Config.XenMaxNics.toString()));
params.put(Config.XenHeartBeatInterval.toString().toLowerCase(), _configDao.getValue(Config.XenHeartBeatInterval.toString()));
params.put(Config.InstanceName.toString().toLowerCase(), _instance);
details.put(Config.InstanceName.toString().toLowerCase(), _instance);
try {
@ -420,6 +420,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L
} else {
prodBrand = prodBrand.trim();
}
String prodVersion = record.softwareVersion.get("product_version");
if (prodVersion == null) {
prodVersion = record.softwareVersion.get("platform_version").trim();
@ -427,36 +428,35 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L
prodVersion = prodVersion.trim();
}
if(prodBrand.equals("XCP") && (prodVersion.equals("1.0.0") || prodVersion.equals("1.1.0") || prodVersion.equals("5.6.100") || prodVersion.startsWith("1.4"))) {
return new XcpServerResource("1.1");
// Xen Cloud Platform group of hypervisors
if (prodBrand.equals("XCP") && (
prodVersion.equals("1.0.0")
|| prodVersion.equals("1.1.0")
|| prodVersion.equals("5.6.100")
|| prodVersion.startsWith("1.4")
)) {
return new XcpServerResource();
} else if (prodBrand.equals("XCP") && prodVersion.startsWith("1.6")) {
return new XcpServerResource("1.6");
}
if(prodBrand.equals("XenServer") && prodVersion.equals("5.6.0"))
return new XenServer56Resource();
if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.0"))
return new XenServer600Resource();
if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.2"))
return new XenServer602Resource();
if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0"))
return new XcpServer16Resource();
} // Citrix Xenserver group of hypervisors
else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.0"))
return new XenServer56Resource();
else if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.0"))
return new XenServer600Resource();
else if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.2"))
return new XenServer602Resource();
else if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0"))
return new XenServer610Resource();
if(prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) {
String prodVersionTextShort = record.softwareVersion.get("product_version_text_short").trim();
if("5.6 SP2".equals(prodVersionTextShort)) {
return new XenServer56SP2Resource();
} else if("5.6 FP1".equals(prodVersionTextShort)) {
return new XenServer56FP1Resource();
}
}
if (prodBrand.equals("XCP_Kronos")) {
return new XcpOssResource();
}
else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) {
String prodVersionTextShort = record.softwareVersion.get("product_version_text_short").trim();
if ("5.6 SP2".equals(prodVersionTextShort)) {
return new XenServer56SP2Resource();
} else if ("5.6 FP1".equals(prodVersionTextShort)) {
return new XenServer56FP1Resource();
}
} else if (prodBrand.equals("XCP_Kronos")) {
return new XcpOssResource();
}
String msg = "Only support XCP 1.0.0, 1.1.0, 1.4.x, 1.5 beta, 1.6.x; XenServer 5.6, XenServer 5.6 FP1, XenServer 5.6 SP2, Xenserver 6.0, 6.0.2, 6.1.0 but this one is " + prodBrand + " " + prodVersion;
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, msg, msg);
@ -585,10 +585,12 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L
Map<String, String> details = startup.getHostDetails();
String prodBrand = details.get("product_brand").trim();
String prodVersion = details.get("product_version").trim();
if(prodBrand.equals("XCP") && (prodVersion.equals("1.0.0") || prodVersion.equals("1.1.0") || prodVersion.equals("5.6.100") || prodVersion.startsWith("1.4") || prodVersion.startsWith("1.6"))) {
if (prodBrand.equals("XCP") && (prodVersion.equals("1.0.0") || prodVersion.equals("1.1.0") || prodVersion.equals("5.6.100") || prodVersion.startsWith("1.4"))) {
resource = XcpServerResource.class.getName();
} else if(prodBrand.equals("XenServer") && prodVersion.equals("5.6.0")) {
} else if (prodBrand.equals("XCP") && prodVersion.startsWith("1.6")) {
resource = XcpServer16Resource.class.getName();
} else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.0")) {
resource = XenServer56Resource.class.getName();
} else if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.0")) {
resource = XenServer600Resource.class.getName();
@ -596,15 +598,15 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L
resource = XenServer602Resource.class.getName();
} else if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0")) {
resource = XenServer610Resource.class.getName();
} else if(prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) {
} else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) {
String prodVersionTextShort = details.get("product_version_text_short").trim();
if("5.6 SP2".equals(prodVersionTextShort)) {
if ("5.6 SP2".equals(prodVersionTextShort)) {
resource = XenServer56SP2Resource.class.getName();
} else if("5.6 FP1".equals(prodVersionTextShort)) {
} else if ("5.6 FP1".equals(prodVersionTextShort)) {
resource = XenServer56FP1Resource.class.getName();
}
} else if (prodBrand.equals("XCP_Kronos")) {
resource = XcpOssResource.class.getName();
resource = XcpOssResource.class.getName();
}
if( resource == null ){

View File

@ -16,11 +16,11 @@
// under the License.
package com.cloud.hypervisor.xen.resource;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
/**
* Reduce bloat inside CitrixResourceBase
*

View File

@ -335,6 +335,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
long _xs_memory_used = 128 * 1024 * 1024L; // xen hypervisor used 128 M
double _xs_virtualization_factor = 63.0/64.0; // 1 - virtualization overhead
//static min values for guests on xen
private static final long mem_128m = 134217728L;
protected boolean _canBridgeFirewall = false;
protected boolean _isOvs = false;
protected List<VIF> _tmpDom0Vif = new ArrayList<VIF>();
@ -657,6 +660,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
Connection conn = getConnection();
Set<VM> vms = VM.getByNameLabel(conn, vmName);
Host host = Host.getByUuid(conn, _host.uuid);
// If DMC is not enable then dont execute this command.
if (isDmcEnabled(conn, host)) {
String msg = "Unable to scale the vm: " + vmName + " as DMC - Dynamic memory control is not enabled for the XenServer:" + _host.uuid + " ,check your license and hypervisor version.";
s_logger.info(msg);
return new ScaleVmAnswer(cmd, false, msg);
}
// stop vm which is running on this host or is in halted state
Iterator<VM> iter = vms.iterator();
while ( iter.hasNext() ) {
@ -1208,8 +1218,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
}
Set<VM> templates = VM.getByNameLabel(conn, guestOsTypeName);
assert templates.size() == 1 : "Should only have 1 template but found " + templates.size();
if (!templates.iterator().hasNext()) {
throw new CloudRuntimeException("No matching OS type found for starting a [" + vmSpec.getOs()
+ "] VM on host " + host.getHostname(conn));
}
VM template = templates.iterator().next();
VM vm = template.createClone(conn, vmSpec.getName());
VM.Record vmr = vm.getRecord(conn);
if (s_logger.isDebugEnabled()) {
@ -3503,8 +3516,29 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
}
}
/**
* WARN: static-min <= dynamic-min <= dynamic-max <= static-max
* @see XcpServerResource#setMemory(com.xensource.xenapi.Connection, com.xensource.xenapi.VM, long, long)
* @param conn
* @param vm
* @param minMemsize
* @param maxMemsize
* @throws XmlRpcException
* @throws XenAPIException
*/
protected void setMemory(Connection conn, VM vm, long minMemsize, long maxMemsize) throws XmlRpcException, XenAPIException {
vm.setMemoryLimits(conn, maxMemsize, maxMemsize, minMemsize, maxMemsize);
vm.setMemoryLimits(conn, mem_128m, maxMemsize, minMemsize, maxMemsize);
}
/**
* When Dynamic Memory Control (DMC) is enabled -
* xen allows scaling the guest memory while the guest is running
*
* By default this is disallowed, override the specific xen resource
* if this is enabled
*/
protected boolean isDmcEnabled(Connection conn, Host host) throws XenAPIException, XmlRpcException {
return false;
}
protected void waitForTask(Connection c, Task task, long pollInterval, long timeout) throws XenAPIException, XmlRpcException {
@ -4299,7 +4333,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
* @throws XenAPIException
* @throws XmlRpcException
*
* @see enableVlanNetwork
* @see CitrixResourceBase#enableVlanNetwork
*/
protected XsLocalNetwork getNetworkByName(Connection conn, String name) throws XenAPIException, XmlRpcException {
Set<Network> networks = Network.getByNameLabel(conn, name);

View File

@ -0,0 +1,32 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.cloud.hypervisor.xen.resource;
public class XcpServer16Resource extends XcpServerResource {
public XcpServer16Resource() {
super();
}
@Override
protected String getGuestOsType(String stdType, boolean bootFromCD) {
return CitrixHelper.getXcp160GuestOsType(stdType);
}
}

View File

@ -16,15 +16,6 @@
// under the License.
package com.cloud.hypervisor.xen.resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.NetworkUsageAnswer;
@ -33,18 +24,27 @@ import com.cloud.resource.ServerResource;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.VM;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import javax.ejb.Local;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Local(value=ServerResource.class)
public class XcpServerResource extends CitrixResourceBase {
private final static Logger s_logger = Logger.getLogger(XcpServerResource.class);
private String version;
public XcpServerResource(String version) {
private final static Logger s_logger = Logger.getLogger(XcpServerResource.class);
private static final long mem_32m = 33554432L;
private String version;
public XcpServerResource() {
super();
this.version = version;
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof NetworkUsageCommand) {
@ -53,15 +53,6 @@ public class XcpServerResource extends CitrixResourceBase {
return super.executeRequest(cmd);
}
}
@Override
protected String getGuestOsType(String stdType, boolean bootFromCD) {
if (version.equalsIgnoreCase("1.6")) {
return CitrixHelper.getXcp160GuestOsType(stdType);
} else {
return CitrixHelper.getXcpGuestOsType(stdType);
}
}
@Override
protected List<File> getPatchFiles() {
@ -77,19 +68,9 @@ public class XcpServerResource extends CitrixResourceBase {
}
@Override
protected void setMemory(Connection conn, VM vm, long minMemsize, long maxMemsize) throws XmlRpcException, XenAPIException {
vm.setMemoryStaticMin(conn, 33554432L);
//vm.setMemoryDynamicMin(conn, 33554432L);
//vm.setMemoryDynamicMax(conn, 33554432L);
vm.setMemoryStaticMax(conn, 33554432L);
//vm.setMemoryStaticMax(conn, maxMemsize );
vm.setMemoryDynamicMax(conn, maxMemsize );
vm.setMemoryDynamicMin(conn, minMemsize );
//vm.setMemoryStaticMin(conn, maxMemsize );
protected String getGuestOsType(String stdType, boolean bootFromCD) {
return CitrixHelper.getXcpGuestOsType(stdType);
}
protected NetworkUsageAnswer execute(NetworkUsageCommand cmd) {
try {
@ -108,5 +89,70 @@ public class XcpServerResource extends CitrixResourceBase {
}
}
/**
XCP provides four memory configuration fields through which
administrators can control this behaviour:
* static-min
* dynamic-min
* dynamic-max
* static-max
The fields static-{min,max} act as *hard* lower and upper
bounds for a guest's memory. For a running guest:
* it's not possible to assign the guest more memory than
static-max without first shutting down the guest.
* it's not possible to assign the guest less memory than
static-min without first shutting down the guest.
The fields dynamic-{min,max} act as *soft* lower and upper
bounds for a guest's memory. It's possible to change these
fields even when a guest is running.
The dynamic range must lie wholly within the static range. To
put it another way, XCP at all times ensures that:
static-min <= dynamic-min <= dynamic-max <= static-max
At all times, XCP will attempt to keep a guest's memory usage
between dynamic-min and dynamic-max.
If dynamic-min = dynamic-max, then XCP will attempt to keep
a guest's memory allocation at a constant size.
If dynamic-min < dynamic-max, then XCP will attempt to give
the guest as much memory as possible, while keeping the guest
within dynamic-min and dynamic-max.
If there is enough memory on a given host to give all resident
guests dynamic-max, then XCP will attempt do so.
If there is not enough memory to give all guests dynamic-max,
then XCP will ask each of the guests (on that host) to use
an amount of memory that is the same *proportional* distance
between dynamic-min and dynamic-max.
XCP will refuse to start guests if starting those guests would
cause the sum of all the dynamic-min values to exceed the total
host memory (taking into account various memory overheads).
cf: http://wiki.xen.org/wiki/XCP_FAQ_Dynamic_Memory_Control
*/
@Override
protected void setMemory(Connection conn, VM vm, long minMemsize, long maxMemsize) throws XmlRpcException, XenAPIException {
//setMemoryLimits(staticMin, staticMax, dynamicMin, dynamicMax)
if (s_logger.isDebugEnabled()) {
s_logger.debug("Memory Limits for VM [" + vm.getNameLabel(conn) +
"[staticMin:" + mem_32m + ", staticMax:" + maxMemsize
+ ", dynamicMin: " + minMemsize + ", dynamicMax:" + maxMemsize+"]]");
}
vm.setMemoryLimits(conn, mem_32m, maxMemsize, minMemsize, maxMemsize);
}
@Override
protected boolean isDmcEnabled(Connection conn, Host host) {
//Dynamic Memory Control (DMC) is a technology provided by Xen Cloud Platform (XCP), starting from the 0.5 release
//For the supported XCPs dmc is default enabled, XCP 1.0.0, 1.1.0, 1.4.x, 1.5 beta, 1.6.x;
return true;
}
}

View File

@ -17,18 +17,6 @@
package com.cloud.hypervisor.xen.resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.to.VirtualMachineTO;
@ -39,16 +27,27 @@ import com.cloud.template.VirtualMachineTemplate.BootloaderType;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Console;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
import com.xensource.xenapi.Types.XenAPIException;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import javax.ejb.Local;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Local(value=ServerResource.class)
public class XenServer56FP1Resource extends XenServer56Resource {
private static final long mem_128m = 134217728L;
private static final Logger s_logger = Logger.getLogger(XenServer56FP1Resource.class);
public XenServer56FP1Resource() {
@ -128,41 +127,46 @@ public class XenServer56FP1Resource extends XenServer56Resource {
assert templates.size() == 1 : "Should only have 1 template but found " + templates.size();
VM template = templates.iterator().next();
VM.Record record = template.getRecord(conn);
record.affinity = host;
record.otherConfig.remove("disks");
record.otherConfig.remove("default_template");
record.otherConfig.remove("mac_seed");
record.isATemplate = false;
record.nameLabel = vmSpec.getName();
record.actionsAfterCrash = Types.OnCrashBehaviour.DESTROY;
record.actionsAfterShutdown = Types.OnNormalExit.DESTROY;
record.memoryDynamicMax = vmSpec.getMaxRam();
record.memoryDynamicMin = vmSpec.getMinRam();
Map<String, String> hostParams = new HashMap<String, String>();
hostParams = host.getLicenseParams(conn);
if (hostParams.get("restrict_dmc").equalsIgnoreCase("false")) {
record.memoryStaticMax = 8589934592L; //8GB
record.memoryStaticMin = 134217728L; //128MB
VM.Record vmr = template.getRecord(conn);
vmr.affinity = host;
vmr.otherConfig.remove("disks");
vmr.otherConfig.remove("default_template");
vmr.otherConfig.remove("mac_seed");
vmr.isATemplate = false;
vmr.nameLabel = vmSpec.getName();
vmr.actionsAfterCrash = Types.OnCrashBehaviour.DESTROY;
vmr.actionsAfterShutdown = Types.OnNormalExit.DESTROY;
if (isDmcEnabled(conn, host)) {
//scaling is allowed
vmr.memoryStaticMin = mem_128m; //128MB
//TODO: Remove hardcoded 8GB and assign proportionate to ServiceOffering and mem overcommit ratio
vmr.memoryStaticMax = 8589934592L; //8GB
vmr.memoryDynamicMin = vmSpec.getMinRam();
vmr.memoryDynamicMax = vmSpec.getMaxRam();
} else {
s_logger.warn("Host "+ _host.uuid + " does not support Dynamic Memory Control, so we cannot scale up the vm");
record.memoryStaticMax = vmSpec.getMaxRam();
record.memoryStaticMin = vmSpec.getMinRam();
//scaling disallowed, set static memory target
if (s_logger.isDebugEnabled()) {
s_logger.warn("Host "+ host.getHostname(conn) +" does not support dynamic scaling");
}
vmr.memoryStaticMin = vmSpec.getMinRam();
vmr.memoryStaticMax = vmSpec.getMaxRam();
vmr.memoryDynamicMin = vmSpec.getMinRam();
vmr.memoryDynamicMax = vmSpec.getMaxRam();
}
if (guestOsTypeName.toLowerCase().contains("windows")) {
record.VCPUsMax = (long) vmSpec.getCpus();
vmr.VCPUsMax = (long) vmSpec.getCpus();
} else {
record.VCPUsMax = 32L;
vmr.VCPUsMax = 32L;
}
record.VCPUsAtStartup = (long) vmSpec.getCpus();
record.consoles.clear();
vmr.VCPUsAtStartup = (long) vmSpec.getCpus();
vmr.consoles.clear();
VM vm = VM.create(conn, record);
VM.Record vmr = vm.getRecord(conn);
VM vm = VM.create(conn, vmr);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Created VM " + vmr.uuid + " for " + vmSpec.getName());
s_logger.debug("Created VM " + vm.getUuid(conn) + " for " + vmSpec.getName());
}
Map<String, String> vcpuParams = new HashMap<String, String>();
@ -229,4 +233,17 @@ public class XenServer56FP1Resource extends XenServer56Resource {
return vm;
}
/**
* When Dynamic Memory Control (DMC) is enabled -
* xen allows scaling the guest memory while the guest is running
*
* This is determined by the 'restrict_dmc' option on the host.
* When false, scaling is allowed hence DMC is enabled
*/
@Override
protected boolean isDmcEnabled(Connection conn, Host host) throws XenAPIException, XmlRpcException {
Map<String, String> hostParams = new HashMap<String, String>();
hostParams = host.getLicenseParams(conn);
return hostParams.get("restrict_dmc").equalsIgnoreCase("false");
}
}

View File

@ -58,7 +58,10 @@ public class CitrixResourceBaseTest {
super.scaleVM(conn, vm, vmSpec, host);
}
@Override
protected boolean isDmcEnabled(Connection conn, Host host) throws Types.XenAPIException, XmlRpcException {
return true;
}
};
@Mock XsHost _host;
@Mock Host host;

View File

@ -17,7 +17,8 @@
* under the License.
*/
import com.cloud.network.element.MidoNetElement;
package com.cloud.network.element;
import com.cloud.user.AccountVO;
import com.cloud.user.dao.AccountDao;
import junit.framework.TestCase;

View File

@ -65,3 +65,5 @@ getRouterStatus.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin
bumpUpPriority.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin
getDomRVersion.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin
router_proxy.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin
createipAlias.sh=..,0755,/usr/lib/xcp/bin
deleteipAlias.sh=..,0755,/usr/lib/xcp/bin

View File

@ -40,8 +40,8 @@ make_migratable.sh=..,0755,/opt/xensource/bin
setup_iscsi.sh=..,0755,/opt/xensource/bin
pingtest.sh=../../..,0755,/opt/xensource/bin
dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin
createipAlias.sh=../../..,0755,/opt/xensource/bin
deleteipAlias.sh=../../..,0755,/opt/xensource/bin
createipAlias.sh=..,0755,/opt/xensource/bin
deleteipAlias.sh=..,0755,/opt/xensource/bin
router_proxy.sh=../../../../network/domr/,0755,/opt/xensource/bin
vm_data.sh=../../../../network/domr/,0755,/opt/xensource/bin
save_password_to_domr.sh=../../../../network/domr/,0755,/opt/xensource/bin

View File

@ -38,8 +38,8 @@ make_migratable.sh=..,0755,/opt/xensource/bin
setup_iscsi.sh=..,0755,/opt/xensource/bin
cloud-setup-bonding.sh=..,0755,/opt/xensource/bin
pingtest.sh=../../..,0755,/opt/xensource/bin
createipAlias.sh=../../..,0755,/opt/xensource/bin
deleteipAlias.sh=../../..,0755,/opt/xensource/bin
createipAlias.sh=..,0755,/opt/xensource/bin
deleteipAlias.sh=..,0755,/opt/xensource/bin
dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin
vm_data.sh=../../../../network/domr/,0755,/opt/xensource/bin
save_password_to_domr.sh=../../../../network/domr/,0755,/opt/xensource/bin

View File

@ -37,8 +37,8 @@ setupxenserver.sh=..,0755,/opt/xensource/bin
make_migratable.sh=..,0755,/opt/xensource/bin
setup_iscsi.sh=..,0755,/opt/xensource/bin
pingtest.sh=../../..,0755,/opt/xensource/bin
createipAlias.sh=../../..,0755,/opt/xensource/bin
deleteipAlias.sh=../../..,0755,/opt/xensource/bin
createipAlias.sh=..,0755,/opt/xensource/bin
deleteipAlias.sh=..,0755,/opt/xensource/bin
dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin
vm_data.sh=../../../../network/domr/,0755,/opt/xensource/bin
save_password_to_domr.sh=../../../../network/domr/,0755,/opt/xensource/bin

View File

@ -40,8 +40,8 @@ id_rsa.cloud=../../../systemvm,0600,/root/.ssh
network_info.sh=..,0755,/opt/xensource/bin
setupxenserver.sh=..,0755,/opt/xensource/bin
make_migratable.sh=..,0755,/opt/xensource/bin
createipAlias.sh=../../..,0755,/opt/xensource/bin
deleteipAlias.sh=../../..,0755,/opt/xensource/bin
createipAlias.sh=..,0755,/opt/xensource/bin
deleteipAlias.sh=..,0755,/opt/xensource/bin
setup_iscsi.sh=..,0755,/opt/xensource/bin
pingtest.sh=../../..,0755,/opt/xensource/bin
dhcp_entry.sh=../../../../network/domr/,0755,/opt/xensource/bin

View File

@ -40,12 +40,6 @@ import com.cloud.network.vpc.PrivateGateway;
import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcOffering;
import com.cloud.vm.*;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.network.vpc.PrivateGateway;
import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcOffering;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.affinity.AffinityGroup;
@ -55,6 +49,8 @@ import org.apache.cloudstack.api.ApiConstants.VMDetails;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.ResponseGenerator;
import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpRange;
import org.apache.cloudstack.api.response.AccountResponse;
import org.apache.cloudstack.api.response.ApplicationLoadBalancerInstanceResponse;
import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse;
@ -104,6 +100,8 @@ import org.apache.cloudstack.api.response.NicResponse;
import org.apache.cloudstack.api.response.NicSecondaryIpResponse;
import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
import org.apache.cloudstack.api.response.PodResponse;
import org.apache.cloudstack.api.response.PortableIpRangeResponse;
import org.apache.cloudstack.api.response.PortableIpResponse;
import org.apache.cloudstack.api.response.PrivateGatewayResponse;
import org.apache.cloudstack.api.response.ProjectAccountResponse;
import org.apache.cloudstack.api.response.ProjectInvitationResponse;
@ -728,6 +726,8 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
ipResponse.setPortable(ipAddr.isPortable());
//set tag information
List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.PublicIpAddress, ipAddr.getId());
List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
@ -975,8 +975,8 @@ public class ApiResponseHelper implements ResponseGenerator {
clusterResponse.setManagedState(cluster.getManagedState().toString());
String cpuOvercommitRatio=ApiDBUtils.findClusterDetails(cluster.getId(),"cpuOvercommitRatio").getValue();
String memoryOvercommitRatio=ApiDBUtils.findClusterDetails(cluster.getId(),"memoryOvercommitRatio").getValue();
clusterResponse.setCpuovercommitratio(cpuOvercommitRatio);
clusterResponse.setRamovercommitratio(memoryOvercommitRatio);
clusterResponse.setCpuOvercommitRatio(cpuOvercommitRatio);
clusterResponse.setMemoryOvercommitRatio(memoryOvercommitRatio);
if (showCapacities != null && showCapacities) {
@ -3830,6 +3830,69 @@ public class ApiResponseHelper implements ResponseGenerator {
}
}
@Override
public PortableIpRangeResponse createPortableIPRangeResponse(PortableIpRange ipRange) {
PortableIpRangeResponse response = new PortableIpRangeResponse();
response.setId(ipRange.getUuid());
String ipRangeStr = ipRange.getIpRange();
if (ipRangeStr != null) {
String[] range = ipRangeStr.split("-");
response.setStartIp(range[0]);
response.setEndIp(range[1]);
}
response.setVlan(ipRange.getVlanTag());
response.setGateway(ipRange.getGateway());
response.setNetmask(ipRange.getNetmask());
response.setRegionId(ipRange.getRegionId());
return response;
}
@Override
public PortableIpResponse createPortableIPResponse(PortableIp portableIp) {
PortableIpResponse response = new PortableIpResponse();
response.setAddress(portableIp.getAddress());
Long accountId = portableIp.getAllocatedInDomainId();
if (accountId != null) {
Account account = ApiDBUtils.findAccountById(accountId);
response.setAllocatedToAccountId(account.getAccountName());
Domain domain = ApiDBUtils.findDomainById(account.getDomainId());
response.setAllocatedInDomainId(domain.getUuid());
}
response.setAllocatedTime(portableIp.getAllocatedTime());
if (portableIp.getAssociatedDataCenterId() != null) {
DataCenter zone = ApiDBUtils.findZoneById(portableIp.getAssociatedDataCenterId());
if (zone != null) {
response.setAssociatedDataCenterId(zone.getUuid());
}
}
if (portableIp.getPhysicalNetworkId() != null) {
PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(portableIp.getPhysicalNetworkId());
if (pnw != null) {
response.setPhysicalNetworkId(pnw.getUuid());
}
}
if (portableIp.getAssociatedWithNetworkId() != null) {
Network ntwk = ApiDBUtils.findNetworkById(portableIp.getAssociatedWithNetworkId());
if (ntwk != null) {
response.setAssociatedWithNetworkId(ntwk.getUuid());
}
}
if (portableIp.getAssociatedWithVpcId() != null) {
Vpc vpc = ApiDBUtils.findVpcById(portableIp.getAssociatedWithVpcId());
if (vpc != null) {
response.setAssociatedWithVpcId(vpc.getUuid());
}
}
response.setState(portableIp.getState().name());
return response;
}
@Override
public InternalLoadBalancerElementResponse createInternalLbElementResponse(VirtualRouterProvider result) {
@ -3848,7 +3911,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response;
}
@Override
public IsolationMethodResponse createIsolationMethodResponse(IsolationType method) {
IsolationMethodResponse response = new IsolationMethodResponse();

View File

@ -177,10 +177,10 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
ServiceOfferingVO svo = _offeringsDao.findById(vm.getServiceOfferingId());
CapacityVO capacityCpu = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_CPU);
CapacityVO capacityMemory = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_MEMORY);
Long clusterId=null;
Long clusterId = null;
if (hostId != null) {
HostVO host = _hostDao.findById(hostId);
clusterId= host.getClusterId();
HostVO host = _hostDao.findById(hostId);
clusterId = host.getClusterId();
}
if (capacityCpu == null || capacityMemory == null || svo == null) {
return false;
@ -263,8 +263,8 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
long hostId = vm.getHostId();
HostVO host = _hostDao.findById(hostId);
long clusterId = host.getClusterId();
float cpuOvercommitRatio =Float.parseFloat(_clusterDetailsDao.findDetail(clusterId,"cpuOvercommitRatio").getValue());
float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId,"memoryOvercommitRatio").getValue());
float cpuOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "cpuOvercommitRatio").getValue());
float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "memoryOvercommitRatio").getValue());
ServiceOfferingVO svo = _offeringsDao.findById(vm.getServiceOfferingId());
@ -348,7 +348,7 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
}
@Override
public boolean checkIfHostHasCapacity(long hostId, Integer cpu, long ram, boolean checkFromReservedCapacity, float cpuOvercommitRatio,float memoryOvercommitRatio, boolean considerReservedCapacity) {
public boolean checkIfHostHasCapacity(long hostId, Integer cpu, long ram, boolean checkFromReservedCapacity, float cpuOvercommitRatio, float memoryOvercommitRatio, boolean considerReservedCapacity) {
boolean hasCapacity = false;
if (s_logger.isDebugEnabled()) {
@ -381,7 +381,7 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
long actualTotalCpu = capacityCpu.getTotalCapacity();
long actualTotalMem = capacityMem.getTotalCapacity();
long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio );
long totalMem = (long) (actualTotalMem *memoryOvercommitRatio );
long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
}
@ -744,8 +744,8 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
capacityCPU.addAnd("podId", SearchCriteria.Op.EQ, server.getPodId());
capacityCPU.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_CPU);
List<CapacityVO> capacityVOCpus = _capacityDao.search(capacitySC, null);
Float cpuovercommitratio = Float.parseFloat(_clusterDetailsDao.findDetail(server.getClusterId(),"cpuOvercommitRatio").getValue());
Float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(server.getClusterId(),"memoryOvercommitRatio").getValue());
Float cpuovercommitratio = Float.parseFloat(_clusterDetailsDao.findDetail(server.getClusterId(), "cpuOvercommitRatio").getValue());
Float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(server.getClusterId(), "memoryOvercommitRatio").getValue());
if (capacityVOCpus != null && !capacityVOCpus.isEmpty()) {
CapacityVO CapacityVOCpu = capacityVOCpus.get(0);
@ -778,7 +778,7 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
if (capacityVOMems != null && !capacityVOMems.isEmpty()) {
CapacityVO CapacityVOMem = capacityVOMems.get(0);
long newTotalMem = (long)((server.getTotalMemory())* memoryOvercommitRatio);
long newTotalMem = (long) ((server.getTotalMemory()) * memoryOvercommitRatio);
if (CapacityVOMem.getTotalCapacity() <= newTotalMem
|| (CapacityVOMem.getUsedCapacity() + CapacityVOMem.getReservedCapacity() <= newTotalMem)) {
CapacityVOMem.setTotalCapacity(newTotalMem);

View File

@ -43,6 +43,7 @@ import com.cloud.dc.*;
import com.cloud.dc.dao.*;
import com.cloud.user.*;
import com.cloud.event.UsageEventUtils;
import com.cloud.utils.db.*;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.api.ApiConstants.LDAPParams;
import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd;
@ -59,6 +60,9 @@ import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd;
import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd;
import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd;
import org.apache.cloudstack.api.command.admin.region.CreatePortableIpRangeCmd;
import org.apache.cloudstack.api.command.admin.region.DeletePortableIpRangeCmd;
import org.apache.cloudstack.api.command.admin.region.ListPortableIpRangesCmd;
import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DedicatePublicIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd;
@ -67,6 +71,8 @@ import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd;
import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd;
import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd;
import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd;
import org.apache.cloudstack.region.*;
import org.apache.cloudstack.region.dao.RegionDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
@ -186,10 +192,6 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.NicIpAlias;
@ -332,6 +334,12 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
@Inject
VpcManager _vpcMgr;
@Inject
PortableIpRangeDao _portableIpRangeDao;
@Inject
RegionDao _regionDao;
@Inject
PortableIpDao _portableIpDao;
@Inject
ConfigurationServer _configServer;
@Inject
DcDetailsDao _dcDetailsDao;
@ -4718,4 +4726,153 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
return null;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RANGE_CREATE, eventDescription = "creating portable ip range", async = false)
public PortableIpRange createPortableIpRange(CreatePortableIpRangeCmd cmd) throws ConcurrentOperationException {
Integer regionId = cmd.getRegionId();
String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
String gateway = cmd.getGateway();
String netmask = cmd.getNetmask();
Long userId = UserContext.current().getCallerUserId();
String vlanId = cmd.getVlan();
Region region = _regionDao.findById(regionId);
if (region == null) {
throw new InvalidParameterValueException("Invalid region ID: " + regionId);
}
if (!NetUtils.isValidIp(startIP) || !NetUtils.isValidIp(endIP) || !NetUtils.validIpRange(startIP, endIP)) {
throw new InvalidParameterValueException("Invalid portable ip range: " + startIP + "-" + endIP);
}
if (!NetUtils.sameSubnet(startIP, gateway, netmask)) {
throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as " +
"your portable IP range's gateway and as per the IP range's netmask.");
}
if (!NetUtils.sameSubnet(endIP, gateway, netmask)) {
throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as " +
"your portable IP range's gateway and as per the IP range's netmask.");
}
if (checkOverlapPortableIpRange(regionId, startIP, endIP)) {
throw new InvalidParameterValueException("Ip range: " + startIP + "-" + endIP + " overlaps with a portable" +
" IP range already configured in the region " + regionId);
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!NetUtils.isValidVlan(vlanId)) {
throw new InvalidParameterValueException("Invalid vlan id " + vlanId);
}
}
GlobalLock portableIpLock = GlobalLock.getInternLock("PortablePublicIpRange");
portableIpLock.lock(5);
Transaction txn = Transaction.currentTxn();
txn.start();
PortableIpRangeVO portableIpRange = new PortableIpRangeVO(regionId, vlanId, gateway, netmask, startIP, endIP);
portableIpRange = _portableIpRangeDao.persist(portableIpRange);
long startIpLong = NetUtils.ip2Long(startIP);
long endIpLong = NetUtils.ip2Long(endIP);
while(startIpLong <= endIpLong) {
PortableIpVO portableIP = new PortableIpVO(regionId, portableIpRange.getId(), vlanId,
gateway, netmask,NetUtils.long2Ip(startIpLong));
_portableIpDao.persist(portableIP);
startIpLong++;
}
txn.commit();
portableIpLock.unlock();
return portableIpRange;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RANGE_DELETE, eventDescription = "deleting portable ip range", async = false)
public boolean deletePortableIpRange(DeletePortableIpRangeCmd cmd) {
long rangeId = cmd.getId();
PortableIpRangeVO portableIpRange = _portableIpRangeDao.findById(rangeId);
if (portableIpRange == null) {
throw new InvalidParameterValueException("Please specify a valid portable IP range id.");
}
List<PortableIpVO> fullIpRange = _portableIpDao.listByRangeId(portableIpRange.getId());
List<PortableIpVO> freeIpRange = _portableIpDao.listByRangeIdAndState(portableIpRange.getId(), PortableIp.State.Free);
if (fullIpRange != null && freeIpRange != null) {
if (fullIpRange.size() == freeIpRange.size()) {
_portableIpRangeDao.expunge(portableIpRange.getId());
return true;
} else {
throw new InvalidParameterValueException("Can't delete portable IP range as there are IP's assigned.");
}
}
return false;
}
@Override
public List<? extends PortableIpRange> listPortableIpRanges(ListPortableIpRangesCmd cmd) {
Integer regionId = cmd.getRegionIdId();
Long rangeId = cmd.getPortableIpRangeId();
List <PortableIpRangeVO> ranges = new ArrayList<PortableIpRangeVO>();
if (regionId != null) {
Region region = _regionDao.findById(regionId);
if (region == null) {
throw new InvalidParameterValueException("Invalid region ID: " + regionId);
}
return _portableIpRangeDao.listByRegionId(regionId);
}
if (rangeId != null) {
PortableIpRangeVO range = _portableIpRangeDao.findById(rangeId);
if (range == null) {
throw new InvalidParameterValueException("Invalid portable IP range ID: " + regionId);
}
ranges.add(range);
return ranges;
}
return _portableIpRangeDao.listAll();
}
@Override
public List<? extends PortableIp> listPortableIps(long id) {
PortableIpRangeVO portableIpRange = _portableIpRangeDao.findById(id);
if (portableIpRange == null) {
throw new InvalidParameterValueException("Please specify a valid portable IP range id.");
}
return _portableIpDao.listByRangeId(portableIpRange.getId());
}
private boolean checkOverlapPortableIpRange(int regionId, String newStartIpStr, String newEndIpStr) {
long newStartIp = NetUtils.ip2Long(newStartIpStr);
long newEndIp = NetUtils.ip2Long(newEndIpStr);
List<PortableIpRangeVO> existingPortableIPRanges = _portableIpRangeDao.listByRegionId(regionId);
for (PortableIpRangeVO portableIpRange : existingPortableIPRanges) {
String ipRangeStr = portableIpRange.getIpRange();
String[] range = ipRangeStr.split("-");
long startip = NetUtils.ip2Long(range[0]);
long endIp = NetUtils.ip2Long(range[1]);
if ((newStartIp >= startip && newStartIp <= endIp) || (newEndIp >= startip && newEndIp <= endIp)) {
return true;
}
if ((startip >= newStartIp && startip <= newEndIp) || (endIp >= newStartIp && endIp <= newEndIp)) {
return true;
}
}
return false;
}
}

View File

@ -86,9 +86,9 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis
ServiceOffering offering = vmProfile.getServiceOffering();
VirtualMachine vm = vmProfile.getVirtualMachine();
Long minMemory = (long) (offering.getRamSize()/vmProfile.getCpuOvercommitRatio());
int minspeed= (int)(offering.getSpeed()/vmProfile.getMemoryOvercommitRatio());
int maxspeed = (offering.getSpeed());
Long minMemory = (long) (offering.getRamSize() / vmProfile.getMemoryOvercommitRatio());
int minspeed = (int) (offering.getSpeed() / vmProfile.getCpuOvercommitRatio());
int maxspeed = (offering.getSpeed());
VirtualMachineTO to = new VirtualMachineTO(vm.getId(), vm.getInstanceName(), vm.getType(), offering.getCpu(), minspeed, maxspeed,
minMemory * 1024l * 1024l, offering.getRamSize() * 1024l * 1024l, null, null, vm.isHaEnabled(), vm.limitCpuUse(), vm.getVncPassword());
to.setBootArgs(vmProfile.getBootArgs());

View File

@ -59,6 +59,7 @@ import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Type;
import com.cloud.vm.VirtualMachineProfile;
import org.apache.cloudstack.region.PortableIp;
/**
* NetworkManager manages the network for the different end users.
@ -122,7 +123,34 @@ public interface NetworkManager {
Pair<NetworkGuru, NetworkVO> implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException;
<T extends VMInstanceVO> void prepareNicForMigration(VirtualMachineProfile<T> vm, DeployDestination dest);
/**
* prepares vm nic change for migration
*
* This method will be called in migration transaction before the vm migration.
* @param vm
* @param dest
*/
void prepareNicForMigration(VirtualMachineProfile<? extends VMInstanceVO> vm, DeployDestination dest);
/**
* commit vm nic change for migration
*
* This method will be called in migration transaction after the successful
* vm migration.
* @param src
* @param dst
*/
void commitNicForMigration(VirtualMachineProfile<? extends VMInstanceVO> src, VirtualMachineProfile<? extends VMInstanceVO> dst);
/**
* rollback vm nic change for migration
*
* This method will be called in migaration transaction after vm migration
* failure.
* @param src
* @param dst
*/
void rollbackNicForMigration(VirtualMachineProfile<? extends VMInstanceVO> src, VirtualMachineProfile<? extends VMInstanceVO> dst);
boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements);
@ -240,6 +268,16 @@ public interface NetworkManager {
IPAddressVO associateIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException;
IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException;
IPAddressVO disassociatePortableIPToGuestNetwork(long ipAddrId, long networkId) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException;
boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId);
void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException;;
/**
* @param network
@ -325,6 +363,9 @@ public interface NetworkManager {
DataCenter zone) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException;
IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID)
throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException;
Map<String, String> finalizeServicesAndProvidersForNetwork(NetworkOffering offering,
Long physicalNetworkId);

View File

@ -105,6 +105,10 @@ import com.cloud.vm.VirtualMachine.Type;
import com.cloud.vm.dao.*;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpDao;
import org.apache.cloudstack.region.PortableIpVO;
import org.apache.cloudstack.region.Region;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
@ -251,6 +255,8 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
UserIpv6AddressDao _ipv6Dao;
@Inject
Ipv6AddressManager _ipv6Mgr;
@Inject
PortableIpDao _portableIpDao;
protected StateMachine2<Network.State, Network.Event, Network> _stateMachine;
private final HashMap<String, NetworkOfferingVO> _systemNetworks = new HashMap<String, NetworkOfferingVO>(5);
@ -702,6 +708,62 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
return ip;
}
@Override
@DB
public IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID)
throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException {
Transaction txn = Transaction.currentTxn();
GlobalLock portableIpLock = GlobalLock.getInternLock("PortablePublicIpRange");
PortableIpVO allocatedPortableIp;
IPAddressVO ipaddr;
try {
portableIpLock.lock(5);
txn.start();
//TODO: get the region ID corresponding to running management server
List<PortableIpVO> portableIpVOs = _portableIpDao.listByRegionIdAndState(1, PortableIp.State.Free);
if (portableIpVOs == null || portableIpVOs.isEmpty()) {
InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException
("Unable to find available portable IP addresses", Region.class, new Long(1));
throw ex;
}
// allocate first portable IP to the user
allocatedPortableIp = portableIpVOs.get(0);
allocatedPortableIp.setAllocatedTime(new Date());
allocatedPortableIp.setAllocatedToAccountId(ipOwner.getAccountId());
allocatedPortableIp.setAllocatedInDomainId(ipOwner.getDomainId());
allocatedPortableIp.setState(PortableIp.State.Allocated);
_portableIpDao.update(allocatedPortableIp.getId(), allocatedPortableIp);
// provision portable IP range VLAN
long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dcId, TrafficType.Public).getId();
Network network = _networkModel.getNetwork(physicalNetworkId);
String range = allocatedPortableIp.getAddress() + "-" + allocatedPortableIp.getAddress();
VlanVO vlan = new VlanVO(VlanType.VirtualNetwork, allocatedPortableIp.getVlan(), allocatedPortableIp.getGateway(),
allocatedPortableIp.getNetmask(), dcId, range, network.getId(), network.getId(), null, null, null);
vlan = _vlanDao.persist(vlan);
// provision the portable IP in to user_ip_address table
ipaddr = new IPAddressVO(new Ip(allocatedPortableIp.getAddress()), dcId, networkId, vpcID, network.getId(),
network.getId(), vlan.getId(), true);
ipaddr.setState(State.Allocated);
ipaddr.setAllocatedTime(new Date());
ipaddr.setAllocatedInDomainId(ipOwner.getDomainId());
ipaddr.setAllocatedToAccountId(ipOwner.getId());
ipaddr= _ipAddressDao.persist(ipaddr);
txn.commit();
} finally {
portableIpLock.unlock();
}
return ipaddr;
}
protected IPAddressVO getExistingSourceNatInNetwork(long ownerId, Long networkId) {
List<? extends IpAddress> addrs = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true);
@ -741,12 +803,14 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
}
DataCenter zone = _configMgr.getZone(network.getDataCenterId());
if (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
_accountMgr.checkAccess(UserContext.current().getCaller(), AccessType.UseNetwork, false, network);
} else {
throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if " +
"network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network");
if (zone.getNetworkType() == NetworkType.Advanced) {
if (network.getGuestType() == Network.GuestType.Shared) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
_accountMgr.checkAccess(UserContext.current().getCaller(), AccessType.UseNetwork, false, network);
} else {
throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if " +
"network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network");
}
}
} else {
_accountMgr.checkAccess(caller, null, true, ipToAssoc);
@ -844,6 +908,162 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
}
}
@Override
public IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
return associateIPToGuestNetwork(ipAddrId, networkId, releaseOnFailure);
}
@DB
@Override
public IPAddressVO disassociatePortableIPToGuestNetwork(long ipId, long networkId)
throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = UserContext.current().getCaller();
Account owner = null;
Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
IPAddressVO ipToAssoc = _ipAddressDao.findById(ipId);
if (ipToAssoc != null) {
if (ipToAssoc.getAssociatedWithNetworkId() == null) {
throw new InvalidParameterValueException("IP " + ipToAssoc + " is not associated with any network");
}
if (ipToAssoc.getAssociatedWithNetworkId() != network.getId()) {
throw new InvalidParameterValueException("IP " + ipToAssoc + " is not associated with network id" + networkId);
}
DataCenter zone = _configMgr.getZone(network.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Advanced) {
if (network.getGuestType() == Network.GuestType.Shared) {
assert (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()));
_accountMgr.checkAccess(UserContext.current().getCaller(), AccessType.UseNetwork, false, network);
}
} else {
_accountMgr.checkAccess(caller, null, true, ipToAssoc);
}
owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId());
} else {
s_logger.debug("Unable to find ip address by id: " + ipId);
return null;
}
DataCenter zone = _configMgr.getZone(network.getDataCenterId());
// Check that network belongs to IP owner - skip this check
// - if zone is basic zone as there is just one guest network,
// - if shared network in Advanced zone
// - and it belongs to the system
if (network.getAccountId() != owner.getId()) {
if (zone.getNetworkType() != NetworkType.Basic && !(zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Shared)) {
throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP");
}
}
// Check if IP has any services (rules) associated in the network
List<PublicIpAddress> ipList = new ArrayList<PublicIpAddress>();
PublicIp publicIp = PublicIp.createFromAddrAndVlan(ipToAssoc, _vlanDao.findById(ipToAssoc.getVlanId()));
ipList.add(publicIp);
Map<PublicIpAddress, Set<Service>> ipToServices = _networkModel.getIpToServices(ipList, false, true);
if (ipToServices != null & !ipToServices.isEmpty()) {
Set<Service> services = ipToServices.get(publicIp);
if (services != null && !services.isEmpty()) {
throw new InvalidParameterValueException("IP " + ipToAssoc + " has services and rules associated in the network " + networkId);
}
}
IPAddressVO ip = _ipAddressDao.findById(ipId);
ip.setAssociatedWithNetworkId(null);
_ipAddressDao.update(ipId, ip);
try {
boolean success = applyIpAssociations(network, false);
if (success) {
s_logger.debug("Successfully associated ip address " + ip.getAddress().addr() + " to network " + network);
} else {
s_logger.warn("Failed to associate ip address " + ip.getAddress().addr() + " to network " + network);
}
return ip;
} finally {
}
}
@Override
public boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId) {
Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
IPAddressVO ip = _ipAddressDao.findById(ipAddrId);
if (ip == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
// Check if IP has any services (rules) associated in the network
List<PublicIpAddress> ipList = new ArrayList<PublicIpAddress>();
PublicIp publicIp = PublicIp.createFromAddrAndVlan(ip, _vlanDao.findById(ip.getVlanId()));
ipList.add(publicIp);
Map<PublicIpAddress, Set<Service>> ipToServices = _networkModel.getIpToServices(ipList, false, true);
if (ipToServices != null & !ipToServices.isEmpty()) {
Set<Service> ipServices = ipToServices.get(publicIp);
if (ipServices != null && !ipServices.isEmpty()) {
return false;
}
}
return true;
}
@DB
@Override
public void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
Network srcNetwork = _networksDao.findById(currentNetworkId);
if (srcNetwork == null) {
throw new InvalidParameterValueException("Invalid source network id " + currentNetworkId +" is given");
}
Network dstNetwork = _networksDao.findById(newNetworkId);
if (dstNetwork == null) {
throw new InvalidParameterValueException("Invalid source network id " + newNetworkId +" is given");
}
IPAddressVO ip = _ipAddressDao.findById(ipAddrId);
if (ip == null) {
throw new InvalidParameterValueException("Invalid portable ip address id is given");
}
Transaction txn = Transaction.currentTxn();
txn.start();
assert(isPortableIpTransferableFromNetwork(ipAddrId, currentNetworkId));
if (srcNetwork.getVpcId() != null) {
_vpcMgr.unassignIPFromVpcNetwork(ipAddrId, currentNetworkId);
} else {
disassociatePortableIPToGuestNetwork(ipAddrId, currentNetworkId);
}
associatePortableIPToGuestNetwork(ipAddrId, newNetworkId, false);
if (dstNetwork.getVpcId() != null) {
ip.setVpcId(dstNetwork.getVpcId());
} else {
ip.setVpcId(null);
}
_ipAddressDao.update(ipAddrId, ip);
txn.commit();
}
@Override
@DB
@ -884,12 +1104,42 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
}
if (success) {
if (ip.isPortable()) {
releasePortableIpAddress(addrId);
}
s_logger.debug("Released a public ip id=" + addrId);
}
return success;
}
@DB
private void releasePortableIpAddress(long addrId) {
Transaction txn = Transaction.currentTxn();
GlobalLock portableIpLock = GlobalLock.getInternLock("PortablePublicIpRange");
txn.start();
try {
portableIpLock.lock(5);
IPAddressVO ip = _ipAddressDao.findById(addrId);
// unassign portable IP
PortableIpVO portableIp = _portableIpDao.findByIpAddress(ip.getAddress().addr());
_portableIpDao.unassignIpAddress(portableIp.getId());
// removed the provisioned vlan
VlanVO vlan = _vlanDao.findById(ip.getVlanId());
_vlanDao.expunge(vlan.getId());
// remove the provisioned public ip address
_ipAddressDao.expunge(ip.getId());
txn.commit();
} finally {
portableIpLock.releaseRef();
}
}
@Override
@DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
@ -1750,8 +2000,9 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
}
@Override
public <T extends VMInstanceVO> void prepareNicForMigration(VirtualMachineProfile<T> vm, DeployDestination dest) {
public void prepareNicForMigration(VirtualMachineProfile<? extends VMInstanceVO> vm, DeployDestination dest) {
List<NicVO> nics = _nicDao.listByVmId(vm.getId());
ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), null, null);
for (NicVO nic : nics) {
NetworkVO network = _networksDao.findById(nic.getNetworkId());
Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
@ -1759,11 +2010,80 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate,
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network));
if(guru instanceof NetworkMigrationResponder){
if(!((NetworkMigrationResponder) guru).prepareMigration(profile, network, vm, dest, context)){
s_logger.error("NetworkGuru "+guru+" prepareForMigration failed."); // XXX: Transaction error
}
}
for (NetworkElement element : _networkElements) {
if(element instanceof NetworkMigrationResponder){
if(!((NetworkMigrationResponder) element).prepareMigration(profile, network, vm, dest, context)){
s_logger.error("NetworkElement "+element+" prepareForMigration failed."); // XXX: Transaction error
}
}
}
guru.updateNicProfile(profile, network);
vm.addNic(profile);
}
}
private NicProfile findNicProfileById(VirtualMachineProfile<? extends VMInstanceVO> vm, long id){
for(NicProfile nic: vm.getNics()){
if(nic.getId() == id){
return nic;
}
}
return null;
}
@Override
public void commitNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> src,
VirtualMachineProfile<? extends VMInstanceVO> dst) {
for(NicProfile nicSrc: src.getNics()){
NetworkVO network = _networksDao.findById(nicSrc.getNetworkId());
NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
NicProfile nicDst = findNicProfileById(dst, nicSrc.getId());
ReservationContext src_context = new ReservationContextImpl(nicSrc.getReservationId(), null, null);
ReservationContext dst_context = new ReservationContextImpl(nicDst.getReservationId(), null, null);
if(guru instanceof NetworkMigrationResponder){
((NetworkMigrationResponder) guru).commitMigration(nicSrc, network, src, src_context, dst_context);
}
for (NetworkElement element : _networkElements) {
if(element instanceof NetworkMigrationResponder){
((NetworkMigrationResponder) element).commitMigration(nicSrc, network, src, src_context, dst_context);
}
}
// update the reservation id
NicVO nicVo = _nicDao.findById(nicDst.getId());
nicVo.setReservationId(nicDst.getReservationId());
_nicDao.persist(nicVo);
}
}
@Override
public void rollbackNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> src,
VirtualMachineProfile<? extends VMInstanceVO> dst) {
for(NicProfile nicDst: dst.getNics()){
NetworkVO network = _networksDao.findById(nicDst.getNetworkId());
NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName());
NicProfile nicSrc = findNicProfileById(src, nicDst.getId());
ReservationContext src_context = new ReservationContextImpl(nicSrc.getReservationId(), null, null);
ReservationContext dst_context = new ReservationContextImpl(nicDst.getReservationId(), null, null);
if(guru instanceof NetworkMigrationResponder){
((NetworkMigrationResponder) guru).rollbackMigration(nicDst, network, dst, src_context, dst_context);
}
for (NetworkElement element : _networkElements) {
if(element instanceof NetworkMigrationResponder){
((NetworkMigrationResponder) element).rollbackMigration(nicDst, network, dst, src_context, dst_context);
}
}
}
}
@Override
@DB
public void release(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean forced) throws

View File

@ -39,6 +39,7 @@ import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.network.vpc.dao.VpcDao;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
@ -184,32 +185,6 @@ import com.cloud.vm.dao.NicSecondaryIpDao;
import com.cloud.vm.dao.NicSecondaryIpVO;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.*;
import com.cloud.vm.dao.*;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd;
import org.apache.cloudstack.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd;
import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd;
import org.apache.cloudstack.api.command.user.network.ListNetworksCmd;
import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd;
import org.apache.cloudstack.api.command.user.vm.ListNicsCmd;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
@ -315,6 +290,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
@Inject
AccountGuestVlanMapDao _accountGuestVlanMapDao;
@Inject
VpcDao _vpcDao;
@Inject
NetworkACLDao _networkACLDao;
int _cidrLimit;
@ -527,22 +504,23 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId)
throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = UserContext.current().getCaller();
long callerUserId = UserContext.current().getCallerUserId();
DataCenter zone = _configMgr.getZone(zoneId);
if (networkId != null) {
Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
if (network.getGuestType() == Network.GuestType.Shared) {
DataCenter zone = _configMgr.getZone(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
// if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork'
if (zone.getNetworkType() == NetworkType.Advanced) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
Account caller = UserContext.current().getCaller();
long callerUserId = UserContext.current().getCallerUserId();
_accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
@ -554,20 +532,67 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
}
}
}
} else {
_accountMgr.checkAccess(caller, null, false, ipOwner);
}
return allocateIP(ipOwner, false, zoneId);
return _networkMgr.allocateIp(ipOwner, false, caller, callerUserId, zone);
}
public IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId)
@Override
@ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_ASSIGN, eventDescription = "allocating portable public Ip", create = true)
public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId)
throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = UserContext.current().getCaller();
// check permissions
_accountMgr.checkAccess(caller, null, false, ipOwner);
long callerUserId = UserContext.current().getCallerUserId();
DataCenter zone = _configMgr.getZone(zoneId);
return _networkMgr.allocateIp(ipOwner, isSystem, caller, callerUserId, zone);
if ((networkId == null && vpcId == null) && (networkId != null && vpcId != null)) {
throw new InvalidParameterValueException("One of Network id or VPC is should be passed");
}
if (networkId != null) {
Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
if (network.getGuestType() == Network.GuestType.Shared) {
if (zone == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
// if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork'
if (zone.getNetworkType() == NetworkType.Advanced) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
_accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
}
return _networkMgr.allocatePortableIp(ipOwner, caller, zoneId, networkId, null);
} else {
throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone" +
" with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled");
}
}
}
}
if (vpcId != null) {
Vpc vpc = _vpcDao.findById(vpcId);
if (vpc != null) {
throw new InvalidParameterValueException("Invalid vpc id is given");
}
}
_accountMgr.checkAccess(caller, null, false, ipOwner);
return _networkMgr.allocatePortableIp(ipOwner, caller, zoneId, null, null);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RELEASE, eventDescription = "disassociating portable Ip", async = true)
public boolean releasePortableIpAddress(long ipAddressId) throws InsufficientAddressCapacityException {
return releaseIpAddressInternal(ipAddressId);
}
@Override
@ -810,9 +835,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_RELEASE, eventDescription = "disassociating Ip", async = true)
public boolean releaseIpAddress(long ipAddressId) throws InsufficientAddressCapacityException {
return releaseIpAddressInternal(ipAddressId);
}
@DB
private boolean releaseIpAddressInternal(long ipAddressId) throws InsufficientAddressCapacityException {
Long userId = UserContext.current().getCallerUserId();
Account caller = UserContext.current().getCaller();
@ -851,6 +880,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
boolean success = _networkMgr.disassociatePublicIpAddress(ipAddressId, userId, caller);
if (success) {
if (!ipVO.isPortable()) {
return success;
}
Long networkId = ipVO.getAssociatedWithNetworkId();
if (networkId != null) {
Network guestNetwork = getNetwork(networkId);
@ -867,7 +899,6 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
return success;
}
@Override
@DB
public Network getNetwork(long id) {

View File

@ -220,6 +220,15 @@ public class PublicIp implements PublicIpAddress {
return _addr.getVmIp();
}
@Override
public boolean isPortable() {
return _addr.isPortable();
}
public void setPortable(boolean portable) {
_addr.setPortable(portable);
}
public Long getIpMacAddress() {
return _addr.getMacAddress();
}

View File

@ -47,7 +47,9 @@ import com.cloud.network.Network;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkMigrationResponder;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkServiceProvider;
@ -85,9 +87,13 @@ import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachine.Type;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao;
@ -108,10 +114,12 @@ import java.util.Set;
@Local(value = {NetworkElement.class, FirewallServiceProvider.class,
DhcpServiceProvider.class, UserDataServiceProvider.class,
StaticNatServiceProvider.class, LoadBalancingServiceProvider.class,
PortForwardingServiceProvider.class, IpDeployer.class, RemoteAccessVPNServiceProvider.class} )
PortForwardingServiceProvider.class, IpDeployer.class,
RemoteAccessVPNServiceProvider.class, NetworkMigrationResponder.class} )
public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider,
UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider,
LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer {
LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer,
NetworkMigrationResponder {
private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class);
protected static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@ -130,6 +138,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
ConfigurationManager _configMgr;
@Inject
RulesManager _rulesMgr;
@Inject
UserVmManager _userVmMgr;
@Inject
UserVmDao _userVmDao;
@ -1024,7 +1034,6 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
// TODO Auto-generated method stub
return null;
}
private boolean canHandleLbRules(List<LoadBalancingRule> rules) {
Map<Capability, String> lbCaps = this.getCapabilities().get(Service.Lb);
if (!lbCaps.isEmpty()) {
@ -1039,5 +1048,60 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
}
}
return true;
}
@Override
public boolean prepareMigration(NicProfile nic, Network network,
VirtualMachineProfile<? extends VirtualMachine> vm,
DeployDestination dest, ReservationContext context) {
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) {
return true;
}
if (vm.getType() == Type.DomainRouter) {
assert vm instanceof DomainRouterVO;
DomainRouterVO router = (DomainRouterVO)vm.getVirtualMachine();
_routerMgr.setupDhcpForPvlan(false, router, router.getHostId(), nic);
} else if (vm.getType() == Type.User){
assert vm instanceof UserVmVO;
UserVmVO userVm = (UserVmVO)vm.getVirtualMachine();
_userVmMgr.setupVmForPvlan(false, userVm.getHostId(), nic);
}
return true;
}
@Override
public void rollbackMigration(NicProfile nic, Network network,
VirtualMachineProfile<? extends VirtualMachine> vm,
ReservationContext src, ReservationContext dst) {
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) {
return;
}
if (vm.getType() == Type.DomainRouter) {
assert vm instanceof DomainRouterVO;
DomainRouterVO router = (DomainRouterVO)vm.getVirtualMachine();
_routerMgr.setupDhcpForPvlan(true, router, router.getHostId(), nic);
} else if (vm.getType() == Type.User){
assert vm instanceof UserVmVO;
UserVmVO userVm = (UserVmVO)vm.getVirtualMachine();
_userVmMgr.setupVmForPvlan(true, userVm.getHostId(), nic);
}
}
@Override
public void commitMigration(NicProfile nic, Network network,
VirtualMachineProfile<? extends VirtualMachine> vm,
ReservationContext src, ReservationContext dst) {
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) {
return;
}
if (vm.getType() == Type.DomainRouter) {
assert vm instanceof DomainRouterVO;
DomainRouterVO router = (DomainRouterVO)vm.getVirtualMachine();
_routerMgr.setupDhcpForPvlan(true, router, router.getHostId(), nic);
} else if (vm.getType() == Type.User){
assert vm instanceof UserVmVO;
UserVmVO userVm = (UserVmVO)vm.getVirtualMachine();
_userVmMgr.setupVmForPvlan(true, userVm.getHostId(), nic);
}
}
}

View File

@ -33,7 +33,6 @@ import com.cloud.user.User;
import com.cloud.uservm.UserVm;
import com.cloud.utils.component.Manager;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.Nic;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachineProfile;
@ -113,4 +112,5 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA
boolean removeDhcpSupportForSubnet(Network network, List<DomainRouterVO> routers) throws ResourceUnavailableException;
boolean setupDhcpForPvlan(boolean add, DomainRouterVO router, Long hostId, NicProfile nic);
}

View File

@ -2223,8 +2223,9 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
return dhcpRange;
}
private boolean setupDhcpForPvlan(boolean add, DomainRouterVO router, Nic nic) {
if (!nic.getBroadcastUri().getScheme().equals("pvlan")) {
@Override
public boolean setupDhcpForPvlan(boolean add, DomainRouterVO router, Long hostId, NicProfile nic) {
if (!nic.getBroadCastUri().getScheme().equals("pvlan")) {
return false;
}
String op = "add";
@ -2233,15 +2234,22 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
}
Network network = _networkDao.findById(nic.getNetworkId());
String networkTag = _networkModel.getNetworkTag(router.getHypervisorType(), network);
PvlanSetupCommand cmd = PvlanSetupCommand.createDhcpSetup(op, nic.getBroadcastUri(), networkTag, router.getInstanceName(), nic.getMacAddress(), nic.getIp4Address());
Commands cmds = new Commands(cmd);
PvlanSetupCommand cmd = PvlanSetupCommand.createDhcpSetup(op, nic.getBroadCastUri(), networkTag, router.getInstanceName(), nic.getMacAddress(), nic.getIp4Address());
// In fact we send command to the host of router, we're not programming router but the host
try {
sendCommandsToRouter(router, cmds);
} catch (AgentUnavailableException e) {
Answer answer = null;
try {
answer = _agentMgr.send(hostId, cmd);
} catch (OperationTimedoutException e) {
s_logger.warn("Timed Out", e);
return false;
} catch (AgentUnavailableException e) {
s_logger.warn("Agent Unavailable ", e);
return false;
}
return false;
}
if (answer == null || !answer.getResult()) {
return false;
}
return true;
}
@ -2563,7 +2571,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
if (network.getTrafficType() == TrafficType.Guest) {
guestNetworks.add(network);
if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
result = setupDhcpForPvlan(true, router, nic);
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
result = setupDhcpForPvlan(true, router, router.getHostId(), nicProfile);
}
}
}
@ -2601,7 +2610,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
for (Nic nic : routerNics) {
Network network = _networkModel.getNetwork(nic.getNetworkId());
if (network.getTrafficType() == TrafficType.Guest && nic.getBroadcastUri().getScheme().equals("pvlan")) {
setupDhcpForPvlan(false, domR, nic);
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
setupDhcpForPvlan(false, domR, domR.getHostId(), nicProfile);
}
}

View File

@ -491,6 +491,49 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules
return false;
}
performedIpAssoc = true;
} else if (ipAddress.isPortable()) {
s_logger.info("Portable IP " + ipAddress.getUuid() + " is not associated with the network, so" +
"associate IP with the network " + networkId);
try {
// check if StaticNat service is enabled in the network
_networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
// associate portable IP to vpc, if network is part of VPC
if (network.getVpcId() != null) {
_vpcMgr.associateIPToVpc(ipId, network.getVpcId());
}
// associate portable IP with guest network
_networkMgr.associatePortableIPToGuestNetwork(ipId, networkId, false);
} catch (Exception e) {
s_logger.warn("Failed to associate portable id=" + ipId + " to network id=" + networkId + " as " +
"a part of enable static nat");
return false;
}
performedIpAssoc = true;
}
} else if (ipAddress.getAssociatedWithNetworkId() != networkId) {
if (ipAddress.isPortable()) {
// check if destination network has StaticNat service enabled
_networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
// check if portable IP can be transferred across the networks
if (_networkMgr.isPortableIpTransferableFromNetwork(ipId, ipAddress.getAssociatedWithNetworkId() )) {
try {
_networkMgr.transferPortableIP(ipId, ipAddress.getAssociatedWithNetworkId(), networkId);
} catch (Exception e) {
s_logger.warn("Failed to associate portable id=" + ipId + " to network id=" + networkId + " as " +
"a part of enable static nat");
return false;
}
} else {
throw new InvalidParameterValueException("Portable IP: " + ipId + " has associated services" +
"in network " + ipAddress.getAssociatedWithNetworkId() + " so can not be transferred to " +
" network " + networkId);
}
} else {
throw new InvalidParameterValueException("Invalid network Id=" + networkId + ". IP is associated with"
+ " a different network than passed network id");
}
} else {
_networkModel.checkIpForService(ipAddress, Service.StaticNat, null);

View File

@ -342,9 +342,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
//Check ofr valid action Allow/Deny
if(action != null){
try {
NetworkACLItem.Action.valueOf(action);
} catch (IllegalArgumentException ex) {
if(!("Allow".equalsIgnoreCase(action) || "Deny".equalsIgnoreCase(action))){
throw new InvalidParameterValueException("Invalid action. Allowed actions are Allow and Deny");
}
}

View File

@ -129,6 +129,7 @@ public abstract class DiscovererBase extends AdapterBase implements Discoverer {
params.put("max.template.iso.size", _configDao.getValue(Config.MaxTemplateAndIsoSize.toString()));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
params.put(Config.XenMaxNics.toString().toLowerCase(), _configDao.getValue(Config.XenMaxNics.toString()));
params.put(Config.XenHeartBeatInterval.toString().toLowerCase(), _configDao.getValue(Config.XenHeartBeatInterval.toString()));
return params;
}

View File

@ -505,10 +505,10 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
clusterId = cluster.getId();
result.add(cluster);
ClusterDetailsVO cluster_detail_cpu = new ClusterDetailsVO(clusterId, "cpuOvercommitRatio", Float.toString(cmd.getCpuOvercommitRatio()));
ClusterDetailsVO cluster_detail_ram = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", Float.toString(cmd.getMemoryOvercommitRaito()));
_clusterDetailsDao.persist(cluster_detail_cpu);
_clusterDetailsDao.persist(cluster_detail_ram);
ClusterDetailsVO cluster_detail_cpu = new ClusterDetailsVO(clusterId, "cpuOvercommitRatio", Float.toString(cmd.getCpuOvercommitRatio()));
ClusterDetailsVO cluster_detail_ram = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", Float.toString(cmd.getMemoryOvercommitRatio()));
_clusterDetailsDao.persist(cluster_detail_cpu);
_clusterDetailsDao.persist(cluster_detail_ram);
if (clusterType == Cluster.ClusterType.CloudManaged) {
return result;
@ -530,8 +530,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
}
if(cmd.getMemoryOvercommitRaito().compareTo(1f) > 0) {
cluster_detail_ram = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", Float.toString(cmd.getMemoryOvercommitRaito()));
if(cmd.getMemoryOvercommitRatio().compareTo(1f) > 0) {
cluster_detail_ram = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", Float.toString(cmd.getMemoryOvercommitRatio()));
_clusterDetailsDao.persist(cluster_detail_ram);
}

View File

@ -47,6 +47,14 @@ import com.cloud.exception.*;
import com.cloud.vm.*;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.ApiConstants;
import com.cloud.event.ActionEventUtils;
import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd;
import org.apache.cloudstack.api.command.admin.region.*;
import org.apache.cloudstack.api.response.ExtractResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.apache.cloudstack.affinity.AffinityGroupProcessor;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.api.ApiConstants;
@ -124,9 +132,6 @@ import org.apache.cloudstack.api.command.admin.pod.CreatePodCmd;
import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd;
import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd;
import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd;
import org.apache.cloudstack.api.command.admin.region.AddRegionCmd;
import org.apache.cloudstack.api.command.admin.region.RemoveRegionCmd;
import org.apache.cloudstack.api.command.admin.region.UpdateRegionCmd;
import org.apache.cloudstack.api.command.admin.resource.ArchiveAlertsCmd;
import org.apache.cloudstack.api.command.admin.resource.DeleteAlertsCmd;
import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd;
@ -571,8 +576,78 @@ import com.cloud.vm.dao.VMInstanceDao;
import edu.emory.mathcs.backport.java.util.Arrays;
import edu.emory.mathcs.backport.java.util.Collections;
import org.apache.cloudstack.api.command.admin.config.ListDeploymentPlannersCmd;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd;
import org.apache.cloudstack.api.command.admin.autoscale.DeleteCounterCmd;
import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd;
import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd;
import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd;
import org.apache.cloudstack.api.command.admin.cluster.UpdateClusterCmd;
import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd;
import org.apache.cloudstack.api.command.admin.config.ListHypervisorCapabilitiesCmd;
import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd;
import org.apache.cloudstack.api.command.admin.config.UpdateHypervisorCapabilitiesCmd;
import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd;
import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd;
import org.apache.cloudstack.api.command.admin.pod.CreatePodCmd;
import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd;
import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd;
import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd;
import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd;
import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd;
import org.apache.cloudstack.api.command.admin.template.PrepareTemplateCmd;
import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd;
import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
import org.apache.cloudstack.api.command.admin.vm.MigrateVMCmd;
import org.apache.cloudstack.api.command.admin.vm.MigrateVirtualMachineWithVolumeCmd;
import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd;
import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd;
import org.apache.cloudstack.api.command.admin.zone.MarkDefaultZoneForAccountCmd;
import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd;
import org.apache.cloudstack.api.command.user.account.AddAccountToProjectCmd;
import org.apache.cloudstack.api.command.user.account.DeleteAccountFromProjectCmd;
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.address.AssociateIPAddrCmd;
import org.apache.cloudstack.api.command.user.address.DisassociateIPAddrCmd;
import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd;
import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd;
import org.apache.cloudstack.api.command.user.event.ArchiveEventsCmd;
import org.apache.cloudstack.api.command.user.event.DeleteEventsCmd;
import org.apache.cloudstack.api.command.user.event.ListEventTypesCmd;
import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd;
import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd;
import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd;
import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd;
import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd;
import org.apache.cloudstack.api.command.user.region.ListRegionsCmd;
import org.apache.cloudstack.api.command.user.region.ha.gslb.*;
import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd;
import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd;
import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd;
import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd;
import org.apache.cloudstack.api.command.user.tag.CreateTagsCmd;
import org.apache.cloudstack.api.command.user.tag.DeleteTagsCmd;
import org.apache.cloudstack.api.command.user.tag.ListTagsCmd;
import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd;
import org.apache.cloudstack.api.command.user.vmsnapshot.CreateVMSnapshotCmd;
import org.apache.cloudstack.api.command.user.vmsnapshot.DeleteVMSnapshotCmd;
import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd;
import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.api.command.admin.config.ListDeploymentPlannersCmd;
public class ManagementServerImpl extends ManagerBase implements ManagementServer {
public static final Logger s_logger = Logger.getLogger(ManagementServerImpl.class.getName());
@ -2897,6 +2972,9 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
cmdList.add(ListAffinityGroupsCmd.class);
cmdList.add(UpdateVMAffinityGroupCmd.class);
cmdList.add(ListAffinityGroupTypesCmd.class);
cmdList.add(CreatePortableIpRangeCmd.class);
cmdList.add(DeletePortableIpRangeCmd.class);
cmdList.add(ListPortableIpRangesCmd.class);
cmdList.add(ListDeploymentPlannersCmd.class);
cmdList.add(ReleaseHostReservationCmd.class);
cmdList.add(ScaleSystemVMCmd.class);

View File

@ -708,19 +708,19 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
VolumeVO volume = new VolumeVO(volumeName, zoneId, -1, -1, -1,
new Long(-1), null, null, 0, Volume.Type.DATADISK);
Account owner = (caller.getId() == ownerId) ? caller : _accountMgr
.getActiveAccountById(ownerId);
volume.setPoolId(null);
volume.setDataCenterId(zoneId);
volume.setPodId(null);
volume.setAccountId(ownerId);
volume.setDomainId(((caller == null) ? Domain.ROOT_DOMAIN : caller
.getDomainId()));
long diskOfferingId = _diskOfferingDao.findByUniqueName(
"Cloud.com-Custom").getId();
volume.setDiskOfferingId(diskOfferingId);
// volume.setSize(size);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setDomainId((caller == null) ? Domain.ROOT_DOMAIN : caller
volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner
.getDomainId());
volume = _volsDao.persist(volume);
@ -878,14 +878,6 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
size = diskOffering.getDiskSize();
}
if(displayVolumeEnabled == null){
displayVolumeEnabled = true;
} else{
if(!_accountMgr.isRootAdmin(caller.getType())){
throw new PermissionDeniedException( "Cannot update parameter displayvolume, only admin permitted ");
}
}
if (!validateVolumeSizeRange(size)) {// convert size from mb to gb
// for validation
throw new InvalidParameterValueException(
@ -917,6 +909,14 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
_accountMgr.checkAccess(caller, null, true, snapshotCheck);
}
if(displayVolumeEnabled == null){
displayVolumeEnabled = true;
} else{
if(!_accountMgr.isRootAdmin(caller.getType())){
throw new PermissionDeniedException( "Cannot update parameter displayvolume, only admin permitted ");
}
}
// Check that the resource limit for primary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.primary_storage,
new Long(size));

View File

@ -54,9 +54,12 @@ import com.cloud.api.query.dao.UserAccountJoinDao;
import com.cloud.api.query.vo.ControlledViewEntity;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.ResourceLimit;
import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterVnetDao;
@ -229,6 +232,10 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
private AccountGuestVlanMapDao _accountGuestVlanMapDao;
@Inject
private DataCenterVnetDao _dataCenterVnetDao;
@Inject
private ResourceLimitService _resourceLimitMgr;
@Inject
private ResourceLimitDao _resourceLimitDao;
private List<UserAuthenticator> _userAuthenticators;
List<UserAuthenticator> _userPasswordEncoders;
@ -714,6 +721,16 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
// Update resource count for this account and for parent domains.
List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
for (ResourceCountVO resourceCount : resourceCounts) {
_resourceLimitMgr.decrementResourceCount(accountId, resourceCount.getType(), resourceCount.getCount());
}
// Delete resource count and resource limits entries set for this account (if there are any).
_resourceCountDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
_resourceLimitDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
return true;
} catch (Exception ex) {
s_logger.warn("Failed to cleanup account " + account + " due to ", ex);

View File

@ -16,11 +16,13 @@
// under the License.
package com.cloud.user;
import java.util.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd;
import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd;
@ -29,8 +31,10 @@ import org.apache.cloudstack.region.RegionManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.ResourceLimit;
import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
@ -49,7 +53,6 @@ import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Manager;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
@ -82,6 +85,8 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
private ProjectManager _projectMgr;
@Inject
private RegionManager _regionMgr;
@Inject
private ResourceLimitDao _resourceLimitDao;
@Override
public Domain getDomain(long domainId) {
@ -329,6 +334,10 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId);
if (accountsForCleanup.isEmpty()) {
deleteDomainSuccess = _domainDao.remove(domainId);
// Delete resource count and resource limits entries set for this domain (if there are any).
_resourceCountDao.removeEntriesByOwner(domainId, ResourceOwnerType.Domain);
_resourceLimitDao.removeEntriesByOwner(domainId, ResourceOwnerType.Domain);
} else {
s_logger.debug("Can't delete the domain yet because it has " + accountsForCleanup.size() + "accounts that need a cleanup");
}

View File

@ -94,4 +94,5 @@ public interface UserVmManager extends VirtualMachineGuru<UserVmVO>, UserVmServi
boolean upgradeVirtualMachine(Long id, Long serviceOfferingId) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException;
boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic);
}

View File

@ -2366,6 +2366,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
} else {
// verify permissions
_accountMgr.checkAccess(caller, null, true, owner, ag);
// Root admin has access to both VM and AG by default, but
// make sure the owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType())) {
if (ag.getAccountId() != owner.getAccountId()) {
throw new PermissionDeniedException("Affinity Group " + ag
+ " does not belong to the VM's account");
}
}
}
}
}
@ -2813,8 +2821,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
return true;
}
private boolean setupVmForPvlan(boolean add, Long hostId, NicVO nic) {
if (!nic.getBroadcastUri().getScheme().equals("pvlan")) {
@Override
public boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic) {
if (!nic.getBroadCastUri().getScheme().equals("pvlan")) {
return false;
}
String op = "add";
@ -2825,7 +2834,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
Network network = _networkDao.findById(nic.getNetworkId());
Host host = _hostDao.findById(hostId);
String networkTag = _networkModel.getNetworkTag(host.getHypervisorType(), network);
PvlanSetupCommand cmd = PvlanSetupCommand.createVmSetup(op, nic.getBroadcastUri(), networkTag, nic.getMacAddress());
PvlanSetupCommand cmd = PvlanSetupCommand.createVmSetup(op, nic.getBroadCastUri(), networkTag, nic.getMacAddress());
Answer answer = null;
try {
answer = _agentMgr.send(hostId, cmd);
@ -2908,7 +2917,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
// In vmware, we will be effecting pvlan settings in portgroups in StartCommand.
if (profile.getHypervisorType() != HypervisorType.VMware) {
if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
if (!setupVmForPvlan(true, hostId, nic)) {
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
if (!setupVmForPvlan(true, hostId, nicProfile)) {
return false;
}
}
@ -3050,7 +3060,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
NetworkVO network = _networkDao.findById(nic.getNetworkId());
if (network.getTrafficType() == TrafficType.Guest) {
if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
setupVmForPvlan(false, vm.getHostId(), nic);
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
setupVmForPvlan(false, vm.getHostId(), nicProfile);
}
}
}
@ -3220,7 +3231,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
if (vm == null || vm.getRemoved() != null) {
InvalidParameterValueException ex = new InvalidParameterValueException(
"Unable to find a virtual machine with specified vmId");
ex.addProxyObject(vm, vmId, "vmId");
throw ex;
}

View File

@ -36,6 +36,7 @@ import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
@ -253,6 +254,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
protected ResourceLimitService _resourceLimitMgr;
@Inject
protected RulesManager rulesMgr;
@Inject
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
protected List<DeploymentPlanner> _planners;
public List<DeploymentPlanner> getPlanners() {
@ -666,6 +669,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
protected boolean areAffinityGroupsAssociated(VirtualMachineProfile<? extends VirtualMachine> vmProfile) {
VirtualMachine vm = vmProfile.getVirtualMachine();
long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
if (vmGroupCount > 0) {
return true;
}
return false;
}
@Override
public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
@ -797,7 +810,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
reuseVolume = false;
continue;
}
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId());
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile,
DataCenter.class, plan.getDataCenterId(), areAffinityGroupsAssociated(vmProfile));
}
if (dest != null) {
@ -810,8 +824,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
Long cluster_id = dest.getCluster().getId();
ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id,"cpuOvercommitRatio");
ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id,"memoryOvercommitRatio");
vmProfile.setcpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
vmProfile.setramOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
vmProfile.setCpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
vmProfile.setMemoryOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
try {
if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
@ -1152,7 +1166,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
vmGuru.prepareStop(profile);
StopCommand stop = new StopCommand(vm);
boolean stopped = false;
StopAnswer answer = null;
@ -1400,6 +1414,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile<VMInstanceVO> vmSrc = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
for(NicProfile nic: _networkMgr.getNicProfiles(vm)){
vmSrc.addNic(nic);
}
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
_networkMgr.prepareNicForMigration(profile, dest);
this.volumeMgr.prepareForMigration(profile, dest);
@ -1425,6 +1444,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
@ -1433,10 +1453,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
@ -1488,6 +1510,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_networkMgr.rollbackNicForMigration(vmSrc, profile);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone "
+ dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs.");
@ -1502,6 +1525,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}else{
_networkMgr.commitNicForMigration(vmSrc, profile);
}
work.setStep(Step.Done);
@ -2802,7 +2827,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
VirtualMachineGuru<VMInstanceVO> vmGuru = getVmGuru(vmVO);
s_logger.debug("Plugging nic for vm " + vm + " in network " + network);
boolean result = false;
try{
result = vmGuru.plugNic(network, nicTO, vmTO, context, dest);
@ -2812,17 +2837,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// insert nic's Id into DB as resource_name
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmVO.getAccountId(),
vmVO.getDataCenterId(), vmVO.getId(), Long.toString(nic.getId()), nic.getNetworkId(),
null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid());
null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid());
return nic;
} else {
s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
return null;
}
}
}finally{
if(!result){
_networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
}
}
}
} else if (vm.getState() == State.Stopped) {
//1) allocate nic
return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
@ -2863,10 +2888,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
}
// if specified nic is associated with PF/LB/Static NAT
if(rulesMgr.listAssociatedRulesForGuestNic(nic).size() > 0){
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network
+ ", nic has associated Port forwarding or Load balancer or Static NAT rules.");
}
@ -2884,7 +2909,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network );
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(),
vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null,
vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null,
isDefault, VirtualMachine.class.getName(), vm.getUuid());
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);

View File

@ -16,12 +16,6 @@
// under the License.
package com.cloud.vm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.offering.ServiceOffering;
@ -34,6 +28,11 @@ import com.cloud.template.VirtualMachineTemplate.BootloaderType;
import com.cloud.user.Account;
import com.cloud.user.dao.AccountDao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of VirtualMachineProfile.
*
@ -239,28 +238,27 @@ public class VirtualMachineProfileImpl<T extends VMInstanceVO> implements Virtua
return _params;
}
public void setServiceOffering(ServiceOfferingVO offering) {
_offering = offering;
}
public void setServiceOffering(ServiceOfferingVO offering) {
_offering = offering;
}
public void setcpuOvercommitRatio(Float cpuOvercommitRatio){
this.cpuOvercommitRatio= cpuOvercommitRatio;
public void setCpuOvercommitRatio(Float cpuOvercommitRatio) {
this.cpuOvercommitRatio = cpuOvercommitRatio;
}
public void setramOvercommitRatio(Float memoryOvercommitRatio){
this.memoryOvercommitRatio= memoryOvercommitRatio;
public void setMemoryOvercommitRatio(Float memoryOvercommitRatio) {
this.memoryOvercommitRatio = memoryOvercommitRatio;
}
@Override
public Float getCpuOvercommitRatio(){
return this.cpuOvercommitRatio;
}
@Override
public Float getMemoryOvercommitRatio(){
public Float getCpuOvercommitRatio() {
return this.cpuOvercommitRatio;
}
@Override
public Float getMemoryOvercommitRatio() {
return this.memoryOvercommitRatio;
}
}

View File

@ -36,6 +36,7 @@ import com.cloud.deploy.DeploymentPlanner;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.network.security.SecurityGroup;
import com.cloud.user.Account;
@ -332,6 +333,14 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
} else {
// verify permissions
_accountMgr.checkAccess(caller, null, true, owner, ag);
// Root admin has access to both VM and AG by default, but make sure the
// owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType())) {
if (ag.getAccountId() != owner.getAccountId()) {
throw new PermissionDeniedException("Affinity Group " + ag
+ " does not belong to the VM's account");
}
}
}
}
_affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);

View File

@ -0,0 +1,39 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.util.List;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.utils.db.GenericDao;
public interface PortableIpDao extends GenericDao<PortableIpVO, Long> {
List<PortableIpVO> listByRegionId(int regionId);
List<PortableIpVO> listByRangeId(long rangeId);
List<PortableIpVO> listByRangeIdAndState(long rangeId, PortableIp.State state);
List<PortableIpVO> listByRegionIdAndState(int regionId, PortableIp.State state);
PortableIpVO findByIpAddress(String ipAddress);
void unassignIpAddress(long ipAddressId);
}

View File

@ -0,0 +1,131 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.springframework.stereotype.Component;
import com.cloud.dc.AccountVlanMapVO;
import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.utils.Pair;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
@Local(value={PortableIpDao.class})
public class PortableIpDaoImpl extends GenericDaoBase<PortableIpVO, Long> implements PortableIpDao {
private final SearchBuilder<PortableIpVO> listByRegionIDSearch;
private final SearchBuilder<PortableIpVO> listByRangeIDSearch;
private final SearchBuilder<PortableIpVO> listByRangeIDAndStateSearch;
private final SearchBuilder<PortableIpVO> listByRegionIDAndStateSearch;
private final SearchBuilder<PortableIpVO> findByIpAddressSearch;
public PortableIpDaoImpl() {
listByRegionIDSearch = createSearchBuilder();
listByRegionIDSearch.and("regionId", listByRegionIDSearch.entity().getRegionId(), SearchCriteria.Op.EQ);
listByRegionIDSearch.done();
listByRangeIDSearch = createSearchBuilder();
listByRangeIDSearch.and("rangeId", listByRangeIDSearch.entity().getRangeId(), SearchCriteria.Op.EQ);
listByRangeIDSearch.done();
listByRangeIDAndStateSearch = createSearchBuilder();
listByRangeIDAndStateSearch.and("rangeId", listByRangeIDAndStateSearch.entity().getRangeId(), SearchCriteria.Op.EQ);
listByRangeIDAndStateSearch.and("state", listByRangeIDAndStateSearch.entity().getState(), SearchCriteria.Op.EQ);
listByRangeIDAndStateSearch.done();
listByRegionIDAndStateSearch = createSearchBuilder();
listByRegionIDAndStateSearch.and("regionId", listByRegionIDAndStateSearch.entity().getRangeId(), SearchCriteria.Op.EQ);
listByRegionIDAndStateSearch.and("state", listByRegionIDAndStateSearch.entity().getState(), SearchCriteria.Op.EQ);
listByRegionIDAndStateSearch.done();
findByIpAddressSearch = createSearchBuilder();
findByIpAddressSearch.and("address", findByIpAddressSearch.entity().getAddress(), SearchCriteria.Op.EQ);
findByIpAddressSearch.done();
}
@Override
public List<PortableIpVO> listByRegionId(int regionIdId) {
SearchCriteria<PortableIpVO> sc = listByRegionIDSearch.create();
sc.setParameters("regionId", regionIdId);
return listBy(sc);
}
@Override
public List<PortableIpVO> listByRangeId(long rangeId) {
SearchCriteria<PortableIpVO> sc = listByRangeIDSearch.create();
sc.setParameters("rangeId", rangeId);
return listBy(sc);
}
@Override
public List<PortableIpVO> listByRangeIdAndState(long rangeId, PortableIp.State state) {
SearchCriteria<PortableIpVO> sc = listByRangeIDAndStateSearch.create();
sc.setParameters("rangeId", rangeId);
sc.setParameters("state", state);
return listBy(sc);
}
@Override
public List<PortableIpVO> listByRegionIdAndState(int regionId, PortableIp.State state) {
SearchCriteria<PortableIpVO> sc = listByRegionIDAndStateSearch.create();
sc.setParameters("regionId", regionId);
sc.setParameters("state", state);
return listBy(sc);
}
@Override
public PortableIpVO findByIpAddress(String ipAddress) {
SearchCriteria<PortableIpVO> sc = findByIpAddressSearch.create();
sc.setParameters("address", ipAddress);
return findOneBy(sc);
}
@Override
public void unassignIpAddress(long ipAddressId) {
PortableIpVO address = createForUpdate();
address.setAllocatedToAccountId(null);
address.setAllocatedInDomainId(null);
address.setAllocatedTime(null);
address.setState(PortableIp.State.Free);
address.setAssociatedWithNetworkId(null);
address.setAssociatedDataCenterId(null);
address.setAssociatedWithVpcId(null);
address.setPhysicalNetworkId(null);
update(ipAddressId, address);
}
}

View File

@ -0,0 +1,30 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.util.List;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.utils.db.GenericDao;
public interface PortableIpRangeDao extends GenericDao<PortableIpRangeVO, Long> {
List<PortableIpRangeVO> listByRegionId(int regionId);
}

View File

@ -0,0 +1,65 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.springframework.stereotype.Component;
import com.cloud.dc.AccountVlanMapVO;
import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.utils.Pair;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
@Local(value={PortableIpRangeDao.class})
public class PortableIpRangeDaoImpl extends GenericDaoBase<PortableIpRangeVO, Long> implements PortableIpRangeDao {
private final SearchBuilder<PortableIpRangeVO> listByRegionIDSearch;
public PortableIpRangeDaoImpl() {
listByRegionIDSearch = createSearchBuilder();
listByRegionIDSearch.and("regionId", listByRegionIDSearch.entity().getRegionId(), SearchCriteria.Op.EQ);
listByRegionIDSearch.done();
}
@Override
public List<PortableIpRangeVO> listByRegionId(int regionIdId) {
SearchCriteria<PortableIpRangeVO> sc = listByRegionIDSearch.create();
sc.setParameters("regionId", regionIdId);
return listBy(sc);
}
}

View File

@ -0,0 +1,119 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
@Entity
@Table(name="portable_ip_range")
public class PortableIpRangeVO implements PortableIpRange {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
Long id;
@Column(name="uuid")
String uuid;
@Column(name="region_id")
int regionId;
@Column(name="vlan_id")
String vlan;
@Column(name="gateway")
String gateway;
@Column(name="netmask")
String netmask;
@Column(name="start_ip")
String startIp;
@Column(name="end_ip")
String endIp;
public PortableIpRangeVO() {
this.uuid = UUID.randomUUID().toString();
}
public PortableIpRangeVO(int regionId, String vlan, String gateway, String netmask, String startIp, String endIp) {
this.uuid = UUID.randomUUID().toString();
this.regionId =regionId;
this.vlan = vlan;
this.gateway = gateway;
this.netmask = netmask;
this.startIp = startIp;
this.endIp = endIp;
}
@Override
public long getId() {
return id;
}
@Override
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public String getVlanTag() {
return vlan;
}
public void setVlanTag(String vlan) {
this.vlan = vlan;
}
@Override
public String getGateway() {
return gateway;
}
@Override
public String getNetmask() {
return netmask;
}
@Override
public int getRegionId() {
return regionId;
}
@Override
public String getIpRange() {
return startIp + "-" + endIp;
}
}

View File

@ -0,0 +1,222 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.region;
import java.util.Date;
import java.util.UUID;
import javax.persistence.*;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
@Entity
@Table(name="portable_ip_address")
public class PortableIpVO implements PortableIp {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
Long id;
@Column(name="region_id")
int regionId;
@Column(name="allocated")
@Temporal(value=TemporalType.TIMESTAMP)
private Date allocatedTime;
@Column(name="account_id")
private Long allocatedToAccountId = null;
@Column(name="domain_id")
private Long allocatedInDomainId = null;
@Column(name="state")
private State state;
@Column(name="vlan")
String vlan;
@Column(name="gateway")
String gateway;
@Column(name="netmask")
String netmask;
@Column(name="portable_ip_address")
String address;
@Column(name="portable_ip_range_id")
private long rangeId;
@Column(name="physical_network_id")
private Long physicalNetworkId;
@Column(name="data_center_id")
private Long dataCenterId;
@Column(name="network_id")
private Long networkId;
@Column(name="vpc_id")
private Long vpcId;
public PortableIpVO() {
}
public PortableIpVO(int regionId, Long rangeId, String vlan, String gateway, String netmask, String address) {
this.regionId =regionId;
this.vlan = vlan;
this.gateway = gateway;
this.netmask = netmask;
this.address = address;
state = State.Free;
this.rangeId = rangeId;
}
@Override
public long getId() {
return id;
}
@Override
public Long getAllocatedToAccountId() {
return allocatedToAccountId;
}
public void setAllocatedToAccountId(Long accountId) {
this.allocatedToAccountId = accountId;
}
@Override
public Long getAllocatedInDomainId() {
return allocatedInDomainId;
}
public void setAllocatedInDomainId(Long domainId) {
this.allocatedInDomainId = domainId;
}
@Override
public Date getAllocatedTime() {
return allocatedTime;
}
public void setAllocatedTime(Date date) {
this.allocatedTime = date;
}
@Override
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
@Override
public int getRegionId() {
return regionId;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
@Override
public Long getAssociatedDataCenterId() {
return dataCenterId;
}
public void setAssociatedDataCenterId(Long datacenterId) {
this.dataCenterId = datacenterId;
}
@Override
public Long getAssociatedWithNetworkId() {
return networkId;
}
public void setAssociatedWithNetworkId(Long networkId) {
this.networkId = networkId;
}
@Override
public Long getAssociatedWithVpcId() {
return vpcId;
}
public void setAssociatedWithVpcId(Long vpcId) {
this.vpcId = vpcId;
}
@Override
public Long getPhysicalNetworkId() {
return physicalNetworkId;
}
public void setPhysicalNetworkId(Long physicalNetworkId) {
this.physicalNetworkId = physicalNetworkId;
}
@Override
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String getVlan() {
return vlan;
}
public void setVlan(String vlan) {
this.vlan = vlan;
}
@Override
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
@Override
public String getGateway() {
return gateway;
}
public void setGateay(String gateway) {
this.gateway = gateway;
}
Long getRangeId() {
return rangeId;
}
public void setRangeId(Long rangeId) {
this.rangeId = rangeId;
}
}

View File

@ -75,7 +75,6 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.*;
import com.cloud.vm.VirtualMachine.Type;
import com.cloud.vm.VirtualMachineProfile;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd;
import org.apache.cloudstack.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd;
@ -89,7 +88,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
@Component
@Local(value = { NetworkManager.class, NetworkService.class })
public class MockNetworkManagerImpl extends ManagerBase implements NetworkManager, NetworkService {
@ -106,6 +104,27 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
return null;
}
@Override
public IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException {
return null;// TODO Auto-generated method stub
}
@Override
public IPAddressVO disassociatePortableIPToGuestNetwork(long ipAddrId, long networkId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
return null; // TODO Auto-generated method stub
}
@Override
public boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId) {
return false;
}
@Override
public void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
}
@Override
public boolean releaseIpAddress(long ipAddressId) {
// TODO Auto-generated method stub
@ -258,12 +277,6 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
}
@Override
public <T extends VMInstanceVO> void prepareNicForMigration(VirtualMachineProfile<T> vm, DeployDestination dest) {
// TODO Auto-generated method stub
}
@Override
public boolean destroyNetwork(long networkId, ReservationContext context) {
// TODO Auto-generated method stub
@ -861,6 +874,23 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
return null;
}
@Override
public IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID)
throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException {
return null;// TODO Auto-generated method stub
}
@Override
public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) throws ResourceAllocationException,
InsufficientAddressCapacityException, ConcurrentOperationException {
return null;
}
@Override
public boolean releasePortableIpAddress(long ipAddressId) throws InsufficientAddressCapacityException {
return false;// TODO Auto-generated method stub
}
@Override
public boolean isSecondaryIpSetForNic(long nicId) {
// TODO Auto-generated method stub
@ -930,4 +960,27 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
public PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp, boolean isSystem) throws InsufficientAddressCapacityException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void prepareNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> vm,
DeployDestination dest) {
// TODO Auto-generated method stub
}
@Override
public void commitNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> src,
VirtualMachineProfile<? extends VMInstanceVO> dst) {
// TODO Auto-generated method stub
}
@Override
public void rollbackNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> src,
VirtualMachineProfile<? extends VMInstanceVO> dst) {
// TODO Auto-generated method stub
}
}

View File

@ -455,4 +455,10 @@ public class MockUserVmManagerImpl extends ManagerBase implements UserVmManager,
// TODO Auto-generated method stub
return null;
}
@Override
public boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic) {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -16,6 +16,44 @@
// under the License.
package com.cloud.vpc;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.naming.NamingException;
import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd;
import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd;
import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd;
import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd;
import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd;
import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.CreateDiskOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.DeleteDiskOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd;
import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd;
import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd;
import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd;
import org.apache.cloudstack.api.command.admin.region.CreatePortableIpRangeCmd;
import org.apache.cloudstack.api.command.admin.region.DeletePortableIpRangeCmd;
import org.apache.cloudstack.api.command.admin.region.ListPortableIpRangesCmd;
import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DedicatePublicIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd;
import org.apache.cloudstack.api.command.admin.vlan.ReleasePublicIpRangeCmd;
import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd;
import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd;
import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd;
import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpRange;
import org.springframework.stereotype.Component;
import com.cloud.configuration.Configuration;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ConfigurationService;
@ -381,6 +419,26 @@ public class MockConfigurationManagerImpl extends ManagerBase implements Configu
return false;
}
@Override
public PortableIpRange createPortableIpRange(CreatePortableIpRangeCmd cmd) throws ConcurrentOperationException {
return null;// TODO Auto-generated method stub
}
@Override
public boolean deletePortableIpRange(DeletePortableIpRangeCmd cmd) {
return false;// TODO Auto-generated method stub
}
@Override
public List<? extends PortableIpRange> listPortableIpRanges(ListPortableIpRangesCmd cmd) {
return null;// TODO Auto-generated method stub
}
@Override
public List<? extends PortableIp> listPortableIps(long id) {
return null;// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.cloud.utils.component.Manager#configure(java.lang.String, java.util.Map)
*/

View File

@ -63,7 +63,6 @@ import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PhysicalNetworkTrafficType;
import com.cloud.network.PublicIpAddress;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.AccountGuestVlanMapVO;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
@ -198,13 +197,36 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
return null;
}
@Override
public IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID)
throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException {
return null;// TODO Auto-generated method stub
}
@Override
public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) throws ResourceAllocationException,
InsufficientAddressCapacityException, ConcurrentOperationException {
return null;
}
@Override
public boolean releasePortableIpAddress(long ipAddressId) throws InsufficientAddressCapacityException {
return false;// TODO Auto-generated method stub
}
@Override
public boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId) {
return false;
}
@Override
public void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkService#releaseIpAddress(long)
*/
* @see com.cloud.network.NetworkService#releaseIpAddress(long)
*/
@Override
public boolean releaseIpAddress(long ipAddressId) throws InsufficientAddressCapacityException {
// TODO Auto-generated method stub
@ -823,18 +845,6 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
/* (non-Javadoc)
* @see com.cloud.network.NetworkManager#prepareNicForMigration(com.cloud.vm.VirtualMachineProfile, com.cloud.deploy.DeployDestination)
*/
@Override
public <T extends VMInstanceVO> void prepareNicForMigration(VirtualMachineProfile<T> vm, DeployDestination dest) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkManager#shutdownNetwork(long, com.cloud.vm.ReservationContext, boolean)
@ -1112,13 +1122,20 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
return null;
}
@Override
public IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException {
return null;// TODO Auto-generated method stub
}
@Override
public IPAddressVO disassociatePortableIPToGuestNetwork(long ipAddrId, long networkId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
return null;// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkManager#setupDns(com.cloud.network.Network, com.cloud.network.Network.Provider)
*/
* @see com.cloud.network.NetworkManager#setupDns(com.cloud.network.Network, com.cloud.network.Network.Provider)
*/
@Override
public boolean setupDns(Network network, Provider provider) {
// TODO Auto-generated method stub
@ -1442,4 +1459,40 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkManage
}
@Override
public void prepareNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> vm,
DeployDestination dest) {
// TODO Auto-generated method stub
}
@Override
public void commitNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> src,
VirtualMachineProfile<? extends VMInstanceVO> dst) {
// TODO Auto-generated method stub
}
@Override
public void rollbackNicForMigration(
VirtualMachineProfile<? extends VMInstanceVO> src,
VirtualMachineProfile<? extends VMInstanceVO> dst) {
// TODO Auto-generated method stub
}
}

View File

@ -420,4 +420,10 @@ VpcVirtualNetworkApplianceService {
return null;
}
@Override
public boolean setupDhcpForPvlan(boolean add, DomainRouterVO router, Long hostId,
NicProfile nic) {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -20,6 +20,9 @@ package org.apache.cloudstack.networkoffering;
import java.io.IOException;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.region.PortableIpDaoImpl;
import org.apache.cloudstack.region.dao.RegionDaoImpl;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl;
import org.apache.cloudstack.test.utils.SpringUtils;
import org.mockito.Mockito;
@ -113,6 +116,7 @@ import com.cloud.vm.dao.NicDaoImpl;
import com.cloud.vm.dao.NicSecondaryIpDaoImpl;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDaoImpl;
import org.apache.cloudstack.region.PortableIpRangeDaoImpl;
@Configuration
@ComponentScan(basePackageClasses={
@ -162,6 +166,9 @@ import com.cloud.vm.dao.VMInstanceDaoImpl;
NetworkServiceMapDaoImpl.class,
PrimaryDataStoreDaoImpl.class,
StoragePoolDetailsDaoImpl.class,
PortableIpRangeDaoImpl.class,
RegionDaoImpl.class,
PortableIpDaoImpl.class,
AccountGuestVlanMapDaoImpl.class
},
includeFilters={@Filter(value=ChildTestConfiguration.Library.class, type=FilterType.CUSTOM)},

View File

@ -1267,6 +1267,43 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'Netwo
alter table `cloud_usage`.`usage_network_offering` add column nic_id bigint(20) unsigned NOT NULL;
CREATE TABLE `cloud`.`portable_ip_range` (
`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT,
`uuid` varchar(40),
`region_id` int unsigned NOT NULL,
`vlan_id` varchar(255),
`gateway` varchar(255),
`netmask` varchar(255),
`start_ip` varchar(255),
`end_ip` varchar(255),
PRIMARY KEY (`id`),
CONSTRAINT `fk_portableip__region_id` FOREIGN KEY (`region_id`) REFERENCES `region`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`portable_ip_address` (
`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT,
`account_id` bigint unsigned NULL,
`domain_id` bigint unsigned NULL,
`allocated` datetime NULL COMMENT 'Date portable ip was allocated',
`state` char(32) NOT NULL default 'Free' COMMENT 'state of the portable ip address',
`region_id` int unsigned NOT NULL,
`vlan` varchar(255),
`gateway` varchar(255),
`netmask` varchar(255),
`portable_ip_address` varchar(255),
`portable_ip_range_id` bigint unsigned NOT NULL,
`data_center_id` bigint unsigned NULL COMMENT 'zone to which portable IP is associated',
`physical_network_id` bigint unsigned NULL COMMENT 'physical network id in the zone to which portable IP is associated',
`network_id` bigint unsigned NULL COMMENT 'guest network to which portable ip address is associated with',
`vpc_id` bigint unsigned COMMENT 'vpc to which portable ip address is associated with',
PRIMARY KEY (`id`),
CONSTRAINT `fk_portable_ip_address__portable_ip_range_id` FOREIGN KEY (`portable_ip_range_id`) REFERENCES `portable_ip_range`(`id`) ON DELETE CASCADE,
CONSTRAINT `fk_portable_ip_address__region_id` FOREIGN KEY (`region_id`) REFERENCES `region`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `cloud`.`user_ip_address` ADD COLUMN is_portable int(1) unsigned NOT NULL default '0';
DROP VIEW IF EXISTS `cloud`.`disk_offering_view`;
CREATE VIEW `cloud`.`disk_offering_view` AS
select
@ -1667,6 +1704,10 @@ CREATE TABLE `cloud`.`nic_ip_alias` (
alter table `cloud`.`vpc_gateways` add column network_acl_id bigint unsigned default 1 NOT NULL;
update `cloud`.`vpc_gateways` set network_acl_id = 2;
INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'VpcManager', 'blacklisted.routes', NULL, 'Routes that are blacklisted, can not be used for Static Routes creation for the VPC Private Gateway');
-- Re-enable foreign key checking, at the end of the upgrade path
SET foreign_key_checks = 1;

View File

@ -561,7 +561,7 @@ class TestNonRootAdminsPrivileges(cloudstackTestCase):
self.apiclient,
self.services["account"]
)
self.debug("Created account: %s" % account_1.account.name)
self.debug("Created account: %s" % account_1.name)
self.cleanup.append(account_1)
account_2 = Account.create(
self.apiclient,

Some files were not shown because too many files have changed in this diff Show More