merged from master

This commit is contained in:
Alex Huang 2013-01-10 15:55:42 -08:00
commit d6f44a4d6a
89 changed files with 904 additions and 660 deletions

View File

@ -31,7 +31,7 @@ import com.cloud.exception.ResourceAllocationException;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
@APICommand(description="Creates a private network", responseObject=NetworkResponse.class) //@APICommand(description="Creates a private network", responseObject=NetworkResponse.class)
public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = Logger.getLogger(CreatePrivateNetworkCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(CreatePrivateNetworkCmd.class.getName());
@ -153,6 +153,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd {
if (result != null) { if (result != null) {
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a Private network"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a Private network");
} }
@ -190,8 +191,4 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd {
} }
@Override
public String getEntityTable() {
return "networks";
}
} }

View File

@ -25,7 +25,7 @@ import com.cloud.event.EventTypes;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
@APICommand(description="Destroys console proxy", responseObject=SuccessResponse.class) //@APICommand(description="Destroys console proxy", responseObject=SuccessResponse.class)
public class DestroyConsoleProxyCmd extends BaseAsyncCmd { public class DestroyConsoleProxyCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(DestroyConsoleProxyCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(DestroyConsoleProxyCmd.class.getName());

View File

@ -27,7 +27,7 @@ import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.SnapshotScheduleResponse; import org.apache.cloudstack.api.response.SnapshotScheduleResponse;
import com.cloud.storage.snapshot.SnapshotSchedule; import com.cloud.storage.snapshot.SnapshotSchedule;
@APICommand(description="Lists recurring snapshot schedule", responseObject=SnapshotScheduleResponse.class) //@APICommand(description="Lists recurring snapshot schedule", responseObject=SnapshotScheduleResponse.class)
public class ListRecurringSnapshotScheduleCmd extends BaseListCmd { public class ListRecurringSnapshotScheduleCmd extends BaseListCmd {
private static final String s_name = "listrecurringsnapshotscheduleresponse"; private static final String s_name = "listrecurringsnapshotscheduleresponse";

View File

@ -16,10 +16,8 @@
// under the License. // under the License.
package com.cloud.exception; package com.cloud.exception;
import com.cloud.utils.IdentityProxy;
import java.util.ArrayList; import java.util.ArrayList;
import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.utils.exception.CSExceptionErrorCode;
import com.cloud.utils.AnnotationHelper;
/** /**
* by the API response serializer. Any exceptions that are thrown by * by the API response serializer. Any exceptions that are thrown by
@ -56,6 +54,7 @@ public class CloudException extends Exception {
return; return;
} }
public ArrayList<String> getIdProxyList() { public ArrayList<String> getIdProxyList() {
return idList; return idList;
} }

View File

@ -16,11 +16,8 @@
// under the License. // under the License.
package org.apache.cloudstack.acl; package org.apache.cloudstack.acl;
import java.util.Properties; import org.apache.cloudstack.acl.RoleType;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.component.Adapter; import com.cloud.utils.component.Adapter;
/** /**
@ -28,5 +25,5 @@ import com.cloud.utils.component.Adapter;
*/ */
public interface APIAccessChecker extends Adapter { public interface APIAccessChecker extends Adapter {
// Interface for checking access to an API for an user // Interface for checking access to an API for an user
boolean canAccessAPI(User user, String apiCommandName) throws PermissionDeniedException; boolean canAccessAPI(RoleType roleType, String apiCommandName) throws PermissionDeniedException;
} }

View File

@ -25,6 +25,8 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
@Parameter(name = "id", type = CommandType.LONG) @Parameter(name = "id", type = CommandType.LONG)
private Long id; private Long id;
private String uuid;
public abstract void create() throws ResourceAllocationException; public abstract void create() throws ResourceAllocationException;
public Long getEntityId() { public Long getEntityId() {
@ -35,14 +37,19 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
this.id = id; this.id = id;
} }
public abstract String getEntityTable(); public String getEntityUuid() {
return uuid;
}
public String getResponse(long jobId, long objectId, String objectEntityTable) { public void setEntityUuid(String uuid) {
this.uuid = uuid;
}
public String getResponse(long jobId, String objectUuid) {
CreateCmdResponse response = new CreateCmdResponse(); CreateCmdResponse response = new CreateCmdResponse();
AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId); AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId);
response.setJobId(job.getUuid()); response.setJobId(job.getUuid());
response.setId(objectId); response.setId(objectUuid);
response.setIdEntityTable(objectEntityTable);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
return _responseGenerator.toSerializedString(response, getResponseType()); return _responseGenerator.toSerializedString(response, getResponseType());
} }

View File

@ -17,7 +17,6 @@
package org.apache.cloudstack.api; package org.apache.cloudstack.api;
import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants;
import com.cloud.utils.IdentityProxy;
import org.apache.cloudstack.api.ResponseObject; import org.apache.cloudstack.api.ResponseObject;
import com.cloud.serializer.Param; import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ -46,6 +45,7 @@ public abstract class BaseResponse implements ResponseObject {
this.objectName = objectName; this.objectName = objectName;
} }
@Override
public String getObjectId() { public String getObjectId() {
return null; return null;
} }
@ -56,18 +56,22 @@ public abstract class BaseResponse implements ResponseObject {
@SerializedName(ApiConstants.JOB_STATUS) @Param(description="the current status of the latest async job acting on this object") @SerializedName(ApiConstants.JOB_STATUS) @Param(description="the current status of the latest async job acting on this object")
private Integer jobStatus; private Integer jobStatus;
@Override
public String getJobId() { public String getJobId() {
return jobId; return jobId;
} }
@Override
public void setJobId(String jobId) { public void setJobId(String jobId) {
this.jobId = jobId; this.jobId = jobId;
} }
@Override
public Integer getJobStatus() { public Integer getJobStatus() {
return jobStatus; return jobStatus;
} }
@Override
public void setJobStatus(Integer jobStatus) { public void setJobStatus(Integer jobStatus) {
this.jobStatus = jobStatus; this.jobStatus = jobStatus;
} }

View File

@ -81,6 +81,7 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd {
if (ctr != null) { if (ctr != null) {
this.setEntityId(ctr.getId()); this.setEntityId(ctr.getId());
this.setEntityUuid(ctr.getUuid());
CounterResponse response = _responseGenerator.createCounterResponse(ctr); CounterResponse response = _responseGenerator.createCounterResponse(ctr);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
this.setResponseObject(response); this.setResponseObject(response);
@ -113,8 +114,5 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
@Override
public String getEntityTable() {
return "counter";
}
} }

View File

@ -59,10 +59,6 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd {
@Parameter(name=ApiConstants.SERVICE_LIST, type=CommandType.LIST, collectionType = CommandType.STRING, description="the list of services to be enabled for this physical network service provider") @Parameter(name=ApiConstants.SERVICE_LIST, type=CommandType.LIST, collectionType = CommandType.STRING, description="the list of services to be enabled for this physical network service provider")
private List<String> enabledServices; private List<String> enabledServices;
@Override
public String getEntityTable() {
return "physical_network_service_providers";
}
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
@ -116,6 +112,7 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd {
PhysicalNetworkServiceProvider result = _networkService.addProviderToPhysicalNetwork(getPhysicalNetworkId(), getProviderName(), getDestinationPhysicalNetworkId(), getEnabledServices()); PhysicalNetworkServiceProvider result = _networkService.addProviderToPhysicalNetwork(getPhysicalNetworkId(), getProviderName(), getDestinationPhysicalNetworkId(), getEnabledServices());
if (result != null) { if (result != null) {
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider entity to physical network"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider entity to physical network");
} }

View File

@ -79,10 +79,6 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd {
return tags; return tags;
} }
@Override
public String getEntityTable() {
return "physical_network";
}
public Long getZoneId() { public Long getZoneId() {
return zoneId; return zoneId;
@ -164,6 +160,7 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd {
PhysicalNetwork result = _networkService.createPhysicalNetwork(getZoneId(),getVlan(),getNetworkSpeed(), getIsolationMethods(),getBroadcastDomainRange(),getDomainId(), getTags(), getNetworkName()); PhysicalNetwork result = _networkService.createPhysicalNetwork(getZoneId(),getVlan(),getNetworkSpeed(), getIsolationMethods(),getBroadcastDomainRange(),getDomainId(), getTags(), getNetworkName());
if (result != null) { if (result != null) {
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network entity"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network entity");
} }

View File

@ -53,10 +53,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd {
this.nspId = nspId; this.nspId = nspId;
} }
@Override
public String getEntityTable() {
return "virtual_router_providers";
}
public Long getNspId() { public Long getNspId() {
return nspId; return nspId;
@ -94,6 +91,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd {
VirtualRouterProvider result = _service.addElement(getNspId(), VirtualRouterProviderType.VirtualRouter); VirtualRouterProvider result = _service.addElement(getNspId(), VirtualRouterProviderType.VirtualRouter);
if (result != null) { if (result != null) {
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network");
} }

View File

@ -66,10 +66,6 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Override
public String getEntityTable() {
return "physical_network_traffic_types";
}
public Long getPhysicalNetworkId() { public Long getPhysicalNetworkId() {
return physicalNetworkId; return physicalNetworkId;
@ -136,6 +132,7 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd {
PhysicalNetworkTrafficType result = _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getXenLabel(), getKvmLabel(), getVmwareLabel(), getSimulatorLabel(), getVlan()); PhysicalNetworkTrafficType result = _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getXenLabel(), getKvmLabel(), getVmwareLabel(), getSimulatorLabel(), getVlan());
if (result != null) { if (result != null) {
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network");
} }

View File

@ -123,6 +123,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
if (result != null) { if (result != null) {
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway");
} }
@ -156,10 +157,6 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
return "creating private gateway"; return "creating private gateway";
} }
@Override
public String getEntityTable() {
return "vpc_gateways";
}
@Override @Override

View File

@ -70,6 +70,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{
VpcOffering vpcOff = _vpcService.createVpcOffering(getVpcOfferingName(), getDisplayText(), getSupportedServices()); VpcOffering vpcOff = _vpcService.createVpcOffering(getVpcOfferingName(), getDisplayText(), getSupportedServices());
if (vpcOff != null) { if (vpcOff != null) {
this.setEntityId(vpcOff.getId()); this.setEntityId(vpcOff.getId());
this.setEntityUuid(vpcOff.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC offering"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC offering");
} }
@ -87,10 +88,6 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{
} }
} }
@Override
public String getEntityTable() {
return "vpc_offerings";
}
@Override @Override
public String getEventType() { public String getEventType() {

View File

@ -87,9 +87,6 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "user_ip_address";
}
public String getAccountName() { public String getAccountName() {
if (accountName != null) { if (accountName != null) {
@ -220,6 +217,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
if (ip != null) { if (ip != null) {
this.setEntityId(ip.getId()); this.setEntityId(ip.getId());
this.setEntityUuid(ip.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to allocate ip address"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to allocate ip address");
} }

View File

@ -62,10 +62,6 @@ public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd {
private Long conditionDomainId; private Long conditionDomainId;
private Long conditionAccountId; private Long conditionAccountId;
@Override
public String getEntityTable() {
return "autoscale_policies";
}
public int getDuration() { public int getDuration() {
return duration; return duration;
@ -159,6 +155,7 @@ public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd {
AutoScalePolicy result = _autoScaleService.createAutoScalePolicy(this); AutoScalePolicy result = _autoScaleService.createAutoScalePolicy(this);
if (result != null) { if (result != null) {
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create AutoScale Policy"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create AutoScale Policy");
} }

View File

@ -72,10 +72,6 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd {
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@Override
public String getEntityTable() {
return "autoscale_vmgroups";
}
public int getMinMembers() { public int getMinMembers() {
return minMembers; return minMembers;
@ -161,6 +157,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd {
AutoScaleVmGroup result = _autoScaleService.createAutoScaleVmGroup(this); AutoScaleVmGroup result = _autoScaleService.createAutoScaleVmGroup(this);
if (result != null) { if (result != null) {
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group");
} }

View File

@ -86,10 +86,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd {
private Long domainId; private Long domainId;
private Long accountId; private Long accountId;
@Override
public String getEntityTable() {
return "autoscale_vmprofiles";
}
public Long getDomainId() { public Long getDomainId() {
if (domainId == null) { if (domainId == null) {
@ -232,6 +229,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd {
AutoScaleVmProfile result = _autoScaleService.createAutoScaleVmProfile(this); AutoScaleVmProfile result = _autoScaleService.createAutoScaleVmProfile(this);
if (result != null) { if (result != null) {
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Profile"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Profile");
} }

View File

@ -72,6 +72,7 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd {
if (condition != null) { if (condition != null) {
this.setEntityId(condition.getId()); this.setEntityId(condition.getId());
this.setEntityUuid(condition.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create condition."); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create condition.");
} }
@ -146,8 +147,5 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd {
return accountId; return accountId;
} }
@Override
public String getEntityTable() {
return "conditions";
}
} }

View File

@ -80,9 +80,6 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getEntityTable() {
return "firewall_rules";
}
public Long getIpAddressId() { public Long getIpAddressId() {
return ipAddressId; return ipAddressId;
@ -242,6 +239,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal
try { try {
FirewallRule result = _firewallService.createFirewallRule(this); FirewallRule result = _firewallService.createFirewallRule(this);
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException ex) { } catch (NetworkRuleConflictException ex) {
s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.info("Network rule conflict: " + ex.getMessage());
s_logger.trace("Network Rule Conflict: ", ex); s_logger.trace("Network Rule Conflict: ", ex);

View File

@ -94,9 +94,6 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getEntityTable() {
return "firewall_rules";
}
public Long getIpAddressId() { public Long getIpAddressId() {
return ipAddressId; return ipAddressId;
@ -301,6 +298,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P
try { try {
PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, getOpenFirewall()); PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, getOpenFirewall());
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException ex) { } catch (NetworkRuleConflictException ex) {
s_logger.info("Network rule conflict: " , ex); s_logger.info("Network rule conflict: " , ex);
s_logger.trace("Network Rule Conflict: ", ex); s_logger.trace("Network Rule Conflict: ", ex);

View File

@ -91,9 +91,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd {
return paramList; return paramList;
} }
public String getEntityTable() {
return "firewall_rules";
}
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
// ///////////// API Implementation/////////////////// // ///////////// API Implementation///////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@ -141,6 +139,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd {
try { try {
StickinessPolicy result = _lbService.createLBStickinessPolicy(this); StickinessPolicy result = _lbService.createLBStickinessPolicy(this);
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException e) { } catch (NetworkRuleConflictException e) {
s_logger.warn("Exception: ", e); s_logger.warn("Exception: ", e);
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());

View File

@ -120,9 +120,6 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements
return privatePort; return privatePort;
} }
public String getEntityTable() {
return "firewall_rules";
}
public Long getSourceIpAddressId() { public Long getSourceIpAddressId() {
if (publicIpId != null) { if (publicIpId != null) {
@ -283,6 +280,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements
try { try {
LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall()); LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall());
this.setEntityId(result.getId()); this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException e) { } catch (NetworkRuleConflictException e) {
s_logger.warn("Exception: ", e); s_logger.warn("Exception: ", e);
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());

View File

@ -75,9 +75,6 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "firewall_rules";
}
public Long getIpAddressId() { public Long getIpAddressId() {
return ipAddressId; return ipAddressId;
@ -151,6 +148,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta
try { try {
StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall()); StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall());
this.setEntityId(rule.getId()); this.setEntityId(rule.getId());
this.setEntityUuid(rule.getUuid());
} catch (NetworkRuleConflictException e) { } catch (NetworkRuleConflictException e) {
s_logger.info("Unable to create Static Nat Rule due to ", e); s_logger.info("Unable to create Static Nat Rule due to ", e);
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());

View File

@ -86,10 +86,6 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getEntityTable() {
return "firewall_rules";
}
public Long getIpAddressId() { public Long getIpAddressId() {
return null; return null;
} }
@ -262,6 +258,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR
try { try {
FirewallRule result = _networkACLService.createNetworkACL(this); FirewallRule result = _networkACLService.createNetworkACL(this);
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException ex) { } catch (NetworkRuleConflictException ex) {
s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.info("Network rule conflict: " + ex.getMessage());
s_logger.trace("Network Rule Conflict: ", ex); s_logger.trace("Network Rule Conflict: ", ex);

View File

@ -56,9 +56,6 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd {
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getEntityTable() {
return "projects";
}
public String getAccountName() { public String getAccountName() {
if (accountName != null) { if (accountName != null) {
@ -127,6 +124,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd {
Project project = _projectService.createProject(getName(), getDisplayText(), getAccountName(), getDomainId()); Project project = _projectService.createProject(getName(), getDisplayText(), getAccountName(), getDomainId());
if (project != null) { if (project != null) {
this.setEntityId(project.getId()); this.setEntityId(project.getId());
this.setEntityUuid(project.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project");
} }

View File

@ -65,9 +65,6 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd {
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getEntityTable() {
return "snapshots";
}
public String getAccountName() { public String getAccountName() {
return accountName; return accountName;
@ -153,6 +150,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd {
Snapshot snapshot = _snapshotService.allocSnapshot(getVolumeId(), getPolicyId()); Snapshot snapshot = _snapshotService.allocSnapshot(getVolumeId(), getPolicyId());
if (snapshot != null) { if (snapshot != null) {
this.setEntityId(snapshot.getId()); this.setEntityId(snapshot.getId());
this.setEntityUuid(snapshot.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot");
} }

View File

@ -102,9 +102,6 @@ import com.cloud.user.UserContext;
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getEntityTable() {
return "vm_template";
}
public Integer getBits() { public Integer getBits() {
return bits; return bits;
@ -240,13 +237,15 @@ import com.cloud.user.UserContext;
public void create() throws ResourceAllocationException { public void create() throws ResourceAllocationException {
if (isBareMetal()) { if (isBareMetal()) {
_bareMetalVmService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId())); _bareMetalVmService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId()));
/*Baremetal creates template record after taking image proceeded, use vmId as entity id here*/ /*Baremetal creates template record after taking image proceeded, use vmId as entity id and uuid here*/
this.setEntityId(vmId); this.setEntityId(vmId);
this.setEntityUuid(vmId.toString());
} else { } else {
VirtualMachineTemplate template = null; VirtualMachineTemplate template = null;
template = _userVmService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId())); template = _userVmService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId()));
if (template != null) { if (template != null) {
this.setEntityId(template.getId()); this.setEntityId(template.getId());
this.setEntityUuid(template.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, throw new ServerApiException(BaseCmd.INTERNAL_ERROR,
"Failed to create a template"); "Failed to create a template");

View File

@ -171,9 +171,6 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "vm_instance";
}
public String getAccountName() { public String getAccountName() {
if (accountName == null) { if (accountName == null) {
@ -446,6 +443,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
if (vm != null) { if (vm != null) {
setEntityId(vm.getId()); setEntityId(vm.getId());
setEntityUuid(vm.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
} }

View File

@ -76,9 +76,6 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "volumes";
}
public String getAccountName() { public String getAccountName() {
return accountName; return accountName;
@ -154,6 +151,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
Volume volume = _storageService.allocVolume(this); Volume volume = _storageService.allocVolume(this);
if (volume != null) { if (volume != null) {
this.setEntityId(volume.getId()); this.setEntityId(volume.getId());
this.setEntityUuid(volume.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create volume"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create volume");
} }

View File

@ -67,6 +67,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{
try { try {
StaticRoute result = _vpcService.createStaticRoute(getGatewayId(), getCidr()); StaticRoute result = _vpcService.createStaticRoute(getGatewayId(), getCidr());
setEntityId(result.getId()); setEntityId(result.getId());
setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException ex) { } catch (NetworkRuleConflictException ex) {
s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.info("Network rule conflict: " + ex.getMessage());
s_logger.trace("Network rule conflict: ", ex); s_logger.trace("Network rule conflict: ", ex);
@ -74,10 +75,6 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{
} }
} }
@Override
public String getEntityTable() {
return "static_routes";
}
@Override @Override
public String getEventType() { public String getEventType() {

View File

@ -124,6 +124,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{
getCidr(), getNetworkDomain()); getCidr(), getNetworkDomain());
if (vpc != null) { if (vpc != null) {
this.setEntityId(vpc.getId()); this.setEntityId(vpc.getId());
this.setEntityUuid(vpc.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC");
} }
@ -157,11 +158,6 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{
} }
} }
@Override
public String getEntityTable() {
return "vpc";
}
@Override @Override
public String getEventType() { public String getEventType() {

View File

@ -103,9 +103,6 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd {
return accountId; return accountId;
} }
public String getEntityTable() {
return "vpn_users";
}
@Override @Override
public String getEventDescription() { public String getEventDescription() {
@ -150,5 +147,6 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user");
} }
setEntityId(vpnUser.getId()); setEntityId(vpnUser.getId());
setEntityUuid(vpnUser.getUuid());
} }
} }

View File

@ -62,10 +62,6 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "user_ip_address";
}
public Long getPublicIpId() { public Long getPublicIpId() {
return publicIpId; return publicIpId;
} }
@ -146,6 +142,11 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
RemoteAccessVpn vpn = _ravService.createRemoteAccessVpn(publicIpId, ipRange, getOpenFirewall(), getNetworkId()); RemoteAccessVpn vpn = _ravService.createRemoteAccessVpn(publicIpId, ipRange, getOpenFirewall(), getNetworkId());
if (vpn != null) { if (vpn != null) {
this.setEntityId(vpn.getServerAddressId()); this.setEntityId(vpn.getServerAddressId());
// find uuid for server ip address
IpAddress ipAddr = _entityMgr.findById(IpAddress.class, vpn.getServerAddressId());
if (ipAddr != null) {
this.setEntityUuid(ipAddr.getUuid());
}
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn");
} }

View File

@ -51,9 +51,6 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_vpn_connection";
}
public Long getVpnGatewayId() { public Long getVpnGatewayId() {
return vpnGatewayId; return vpnGatewayId;
@ -95,6 +92,7 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd {
Site2SiteVpnConnection conn = _s2sVpnService.createVpnConnection(this); Site2SiteVpnConnection conn = _s2sVpnService.createVpnConnection(this);
if (conn != null) { if (conn != null) {
this.setEntityId(conn.getId()); this.setEntityId(conn.getId());
this.setEntityUuid(conn.getUuid());
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create site to site vpn connection"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create site to site vpn connection");
} }

View File

@ -78,9 +78,6 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_customer_gateway";
}
public String getName() { public String getName() {
return name; return name;

View File

@ -47,10 +47,6 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_vpn_gateway";
}
public Long getVpcId() { public Long getVpcId() {
return vpcId; return vpcId;
} }

View File

@ -44,9 +44,6 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_vpn_connection";
}
public Long getId() { public Long getId() {
return id; return id;

View File

@ -43,9 +43,6 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_customer_gateway";
}
public Long getId() { public Long getId() {
return id; return id;

View File

@ -43,9 +43,6 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_vpn_gateway";
}
public Long getId() { public Long getId() {
return id; return id;

View File

@ -53,9 +53,6 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() {
return "s2s_vpn_connection";
}
public Long getDomainId() { public Long getDomainId() {
return domainId; return domainId;

View File

@ -78,11 +78,7 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd {
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public String getEntityTable() { public Long getId() {
return "s2s_customer_gateway";
}
public Long getId() {
return id; return id;
} }

View File

@ -17,7 +17,6 @@
package org.apache.cloudstack.api.response; package org.apache.cloudstack.api.response;
import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants;
import com.cloud.utils.IdentityProxy;
import com.cloud.serializer.Param; import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.BaseResponse;

View File

@ -16,24 +16,16 @@
// under the License. // under the License.
package org.apache.cloudstack.api.response; package org.apache.cloudstack.api.response;
import org.apache.cloudstack.api.ApiConstants;
import com.cloud.utils.IdentityProxy;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.BaseResponse;
public class CreateCmdResponse extends BaseResponse { public class CreateCmdResponse extends BaseResponse {
@SerializedName(ApiConstants.ID) private String id;
private IdentityProxy id = new IdentityProxy();
public Long getId() { public String getId() {
return id.getValue(); return id;
} }
public void setId(Long id) { public void setId(String id) {
this.id.setValue(id); this.id = id;
}
public void setIdEntityTable(String entityTable) {
this.id.setTableName(entityTable);
} }
} }

View File

@ -17,7 +17,6 @@
package org.apache.cloudstack.api.response; package org.apache.cloudstack.api.response;
import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants;
import com.cloud.utils.IdentityProxy;
import com.cloud.serializer.Param; import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.BaseResponse;

View File

@ -19,7 +19,6 @@
package org.apache.cloudstack.api.response; package org.apache.cloudstack.api.response;
import com.cloud.serializer.Param; import com.cloud.serializer.Param;
import com.cloud.utils.IdentityProxy;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.BaseResponse;
@ -29,7 +28,7 @@ public class S3Response extends BaseResponse {
@SerializedName(ID) @SerializedName(ID)
@Param(description = "The ID of the S3 configuration") @Param(description = "The ID of the S3 configuration")
private IdentityProxy id = new IdentityProxy("s3"); private String id;
@SerializedName(S3_ACCESS_KEY) @SerializedName(S3_ACCESS_KEY)
@Param(description = "The S3 access key") @Param(description = "The S3 access key")
@ -135,11 +134,11 @@ public class S3Response extends BaseResponse {
@Override @Override
public String getObjectId() { public String getObjectId() {
return this.id.getValue().toString(); return this.id;
} }
public void setObjectId(Long id) { public void setObjectId(String id) {
this.id.setValue(id); this.id = id;
} }
public String getAccessKey() { public String getAccessKey() {

View File

@ -135,8 +135,8 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe
@SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with tempate", responseObject = ResourceTagResponse.class) @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with tempate", responseObject = ResourceTagResponse.class)
private List<ResourceTagResponse> tags; private List<ResourceTagResponse> tags;
@SerializedName(ApiConstants.SSHKEY_ENABLED) @Param(description="true if template is sshkey enabled, false otherwise")
private Boolean sshKeyEnabled;
@Override @Override
public String getObjectId() { public String getObjectId() {
@ -290,4 +290,9 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe
public void setTags(List<ResourceTagResponse> tags) { public void setTags(List<ResourceTagResponse> tags) {
this.tags = tags; this.tags = tags;
} }
public void setSshKeyEnabled(boolean sshKeyEnabled) {
this.sshKeyEnabled = sshKeyEnabled;
}
} }

View File

@ -56,9 +56,6 @@ under the License.
<adapters key="org.apache.cloudstack.acl.APIAccessChecker"> <adapters key="org.apache.cloudstack.acl.APIAccessChecker">
<adapter name="StaticRoleBasedAPIAccessChecker" class="org.apache.cloudstack.acl.StaticRoleBasedAPIAccessChecker"/> <adapter name="StaticRoleBasedAPIAccessChecker" class="org.apache.cloudstack.acl.StaticRoleBasedAPIAccessChecker"/>
</adapters> </adapters>
<adapters key="org.apache.cloudstack.discovery.ApiDiscoveryService">
<adapter name="ApiDiscoveryService" class="org.apache.cloudstack.discovery.ApiDiscoveryServiceImpl"/>
</adapters>
<adapters key="com.cloud.agent.manager.allocator.HostAllocator"> <adapters key="com.cloud.agent.manager.allocator.HostAllocator">
<adapter name="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.FirstFitRoutingAllocator"/> <adapter name="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.FirstFitRoutingAllocator"/>
<!--adapter name="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.RecreateHostAllocator"/--> <!--adapter name="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.RecreateHostAllocator"/-->

View File

@ -22,26 +22,19 @@
under the License. under the License.
--> -->
<section id="accessing-vms"> <section id="accessing-vms">
<title>Accessing VMs</title> <title>Accessing VMs</title>
<para>Any user can access their own virtual machines. The administrator can access all VMs running in the cloud.</para> <para>Any user can access their own virtual machines. The administrator can access all VMs running in the cloud.</para>
<para>To access a VM through the &PRODUCT; UI:</para> <para>To access a VM through the &PRODUCT; UI:</para>
<orderedlist> <orderedlist>
<listitem><para>Log in to the &PRODUCT; UI as a user or admin.</para></listitem> <listitem><para>Log in to the &PRODUCT; UI as a user or admin.</para></listitem>
<listitem><para>Click Instances, then click the name of a running VM.</para></listitem> <listitem><para>Click Instances, then click the name of a running VM.</para></listitem>
<listitem><para>Click the View Console <inlinemediaobject> <listitem><para>Click the View Console button <inlinegraphic format="PNG" fileref="images/view-console-button.png"/>.</para></listitem>
<imageobject> </orderedlist>
<imagedata fileref="./images/console-icon.png"/> <para>To access a VM directly over the network:</para>
</imageobject> <orderedlist>
<textobject> <listitem><para>The VM must have some port open to incoming traffic. For example, in a basic zone, a new VM might be assigned to a security group which allows incoming traffic. This depends on what security group you picked when creating the VM. In other cases, you can open a port by setting up a port forwarding policy. See IP Forwarding and Firewalling.</para></listitem>
<phrase>consoleicon.png: button to view the console.</phrase> <listitem><para>If a port is open but you can not access the VM using ssh, its possible that ssh is not already enabled on the VM. This will depend on whether ssh is enabled in the template you picked when creating the VM. Access the VM through the &PRODUCT; UI and enable ssh on the machine using the commands for the VMs operating system.</para></listitem>
</textobject> <listitem><para>If the network has an external firewall device, you will need to create a firewall rule to allow access. See IP Forwarding and Firewalling.</para></listitem>
</inlinemediaobject></para></listitem> </orderedlist>
</orderedlist>
<para>To access a VM directly over the network:</para>
<orderedlist>
<listitem><para>The VM must have some port open to incoming traffic. For example, in a basic zone, a new VM might be assigned to a security group which allows incoming traffic. This depends on what security group you picked when creating the VM. In other cases, you can open a port by setting up a port forwarding policy. See IP Forwarding and Firewalling.</para></listitem>
<listitem><para>If a port is open but you can not access the VM using ssh, its possible that ssh is not already enabled on the VM. This will depend on whether ssh is enabled in the template you picked when creating the VM. Access the VM through the &PRODUCT; UI and enable ssh on the machine using the commands for the VMs operating system.</para></listitem>
<listitem><para>If the network has an external firewall device, you will need to create a firewall rule to allow access. See IP Forwarding and Firewalling.</para></listitem>
</orderedlist>
</section> </section>

View File

@ -0,0 +1,145 @@
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>
<!-- 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.
-->
<section id="aws-api-examples">
<title>Examples</title>
<para>There are many tools available to interface with a AWS compatible API. In this section we provide
a few examples that users of &PRODUCT; can build upon.</para>
<section id="aws-api-boto-examples">
<title>Boto Examples</title>
<para>Boto is one of them. It is a Python package available at https://github.com/boto/boto.
In this section we provide two examples of Python scripts that use Boto and have been tested with the
&PRODUCT; AWS API Interface.</para>
<para>First is an EC2 example. Replace the Access and Secret Keys with your own and
update the endpoint.</para>
<para>
<example>
<title>An EC2 Boto example</title>
<programlisting>#!/usr/bin/env python
import sys
import os
import boto
import boto.ec2
region = boto.ec2.regioninfo.RegionInfo(name="ROOT",endpoint="localhost")
apikey='GwNnpUPrO6KgIdZu01z_ZhhZnKjtSdRwuYd4DvpzvFpyxGMvrzno2q05MB0ViBoFYtdqKd'
secretkey='t4eXLEYWw7chBhDlaKf38adCMSHx_wlds6JfSx3z9fSpSOm0AbP9Moj0oGIzy2LSC8iw'
def main():
'''Establish connection to EC2 cloud'''
conn =boto.connect_ec2(aws_access_key_id=apikey,
aws_secret_access_key=secretkey,
is_secure=False,
region=region,
port=7080,
path="/awsapi",
api_version="2010-11-15")
'''Get list of images that I own'''
images = conn.get_all_images()
print images
myimage = images[0]
'''Pick an instance type'''
vm_type='m1.small'
reservation = myimage.run(instance_type=vm_type,security_groups=['default'])
if __name__ == '__main__':
main()
</programlisting>
</example>
</para>
<para>Second is an S3 example. Replace the Access and Secret keys with your own,
as well as the endpoint of the service. Be sure to also update the file paths to something
that exists on your machine.</para>
<para>
<example>
<title>An S3 Boto Example</title>
<programlisting>#!/usr/bin/env python
import sys
import os
from boto.s3.key import Key
from boto.s3.connection import S3Connection
from boto.s3.connection import OrdinaryCallingFormat
apikey='ChOw-pwdcCFy6fpeyv6kUaR0NnhzmG3tE7HLN2z3OB_s-ogF5HjZtN4rnzKnq2UjtnHeg_yLA5gOw'
secretkey='IMY8R7CJQiSGFk4cHwfXXN3DUFXz07cCiU80eM3MCmfLs7kusgyOfm0g9qzXRXhoAPCH-IRxXc3w'
cf=OrdinaryCallingFormat()
def main():
'''Establish connection to S3 service'''
conn =S3Connection(aws_access_key_id=apikey,aws_secret_access_key=secretkey, \
is_secure=False, \
host='localhost', \
port=7080, \
calling_format=cf, \
path="/awsapi/rest/AmazonS3")
try:
bucket=conn.create_bucket('cloudstack')
k = Key(bucket)
k.key = 'test'
try:
k.set_contents_from_filename('/Users/runseb/Desktop/s3cs.py')
except:
print 'could not write file'
pass
except:
bucket = conn.get_bucket('cloudstack')
k = Key(bucket)
k.key = 'test'
try:
k.get_contents_to_filename('/Users/runseb/Desktop/foobar')
except:
print 'Could not get file'
pass
try:
bucket1=conn.create_bucket('teststring')
k=Key(bucket1)
k.key('foobar')
k.set_contents_from_string('This is my silly test')
except:
bucket1=conn.get_bucket('teststring')
k = Key(bucket1)
k.key='foobar'
k.get_contents_as_string()
if __name__ == '__main__':
main()
</programlisting>
</example>
</para>
</section>
<section id="aws-api-jclouds-examples">
<title>JClouds Examples</title>
<para></para>
</section>
</section>

View File

@ -23,26 +23,88 @@
--> -->
<section id="aws-ec2-configuration"> <section id="aws-ec2-configuration">
<title>Enabling the AWS API Compatible Interface</title> <title>Enabling the EC2 and S3 Compatible Interface</title>
<para>
The software that provides AWS API compatibility is installed along with &PRODUCT;. However, you must enable the feature and perform some setup steps. <para>The software that provides AWS API compatibility is installed along with &PRODUCT;. You must enable the services and perform some setup steps prior to using it.
</para> </para>
<orderedlist> <orderedlist>
<listitem><para>Set the global configuration parameter enable.ec2.api to true. See <xref linkend="global-config" />.</para></listitem> <listitem><para>Set the global configuration parameters for each service to true.
<listitem><para>Create a set of &PRODUCT; service offerings with names that match the Amazon service offerings. See <xref linkend="global-config" />.</para></listitem>
You can do this through the &PRODUCT; UI as described in the Administration Guide.</para> <listitem><para>Create a set of &PRODUCT; service offerings with names that match the Amazon service offerings.
<warning><para>Be sure you have included the Amazon default service offering, m1.small.</para></warning></listitem> You can do this through the &PRODUCT; UI as described in the Administration Guide.</para>
<listitem><para>If you did not already do so when you set the configuration parameter in step 1, restart the Management Server.</para> <warning><para>Be sure you have included the Amazon default service offering, m1.small. As well as any EC2 instance types that you will use.</para></warning>
<programlisting># service cloud-management restart</programlisting></listitem>
<listitem><para>(Optional) The AWS API listens for requests on port 7080. If you prefer AWS API to listen on another port, you can change it as follows:</para>
<orderedlist numeration="loweralpha">
<listitem><para>Edit the files /etc/cloud/management/server.xml, /etc/cloud/management/server-nonssl.xml, and /etc/cloud/management/server-ssl.xml.</para></listitem>
<listitem><para>In each file, find the tag &lt;Service name="Catalina7080"&gt;. Under this tag, locate &lt;Connector executor="tomcatThreadPool-internal" port= ....&lt;.</para></listitem>
<listitem><para>Change the port to whatever port you want to use, then save the files.</para></listitem>
<listitem><para>Restart the Management Server.</para>
<note><para>If you re-install CloudStack, you will have to make these changes again.</para></note>
</listitem> </listitem>
</orderedlist> <listitem><para>If you did not already do so when you set the configuration parameter in step 1,
</listitem> restart the Management Server.</para>
</orderedlist> <programlisting># service cloud-management restart</programlisting>
</listitem>
</orderedlist>
<para>The following sections provides details to perform these steps</para>
<section id="aws-api-settings">
<title>Enabling the Services</title>
<para>To enable the EC2 and S3 compatible services you need to set the configuration variables <emphasis>enable.ec2.api</emphasis>
and <emphasis>enable.s3.api</emphasis> to true. You do not have to enable both at the same time. Enable the ones you need.
This can be done via the &PRODUCT; GUI by going in <emphasis>Global Settings</emphasis> or via the API.</para>
<para>The snapshot below shows you how to use the GUI to enable these services</para>
<para>
<mediaobject>
<imageobject>
<imagedata fileref="./images/ec2-s3-configuration.png"/>
</imageobject>
<textobject>
<phrase>Use the GUI to set the configuration variable to <emphasis>true</emphasis></phrase>
</textobject>
</mediaobject>
</para>
<para>Using the &PRODUCT; API, the easiest is to use the so-called integration port on which you can make
unauthenticated calls. In Global Settings set the port to 8096 and subsequently call the <emphasis>updateConfiguration</emphasis> method.
The following urls shows you how:</para>
<para>
<programlisting>
http://localhost:8096/client/api?command=updateConfiguration&amp;name=enable.ec2.api&amp;value=true
http://localhost:8096/client/api?command=updateConfiguration&amp;name=enable.ec2.api&amp;value=true
</programlisting>
</para>
<para>Once you have enabled the services, restart the server.</para>
</section>
<section id="aws-ec2-service-offerings">
<title>Creating EC2 Compatible Service Offerings</title>
<para>You will also need to define compute service offerings with names compatible with the <ulink url="http://aws.amazon.com/ec2/instance-types/">
Amazon EC2 instance types</ulink> API names (e.g m1.small,m1.large). This can be done via the &PRODUCT; GUI.
Go under <emphasis>Service Offerings</emphasis> select <emphasis>Compute offering</emphasis> and either create
a new compute offering or modify an existing one, ensuring that the name matches an EC2 instance type API name. The snapshot below shows you how:</para>
<para>
<mediaobject>
<imageobject>
<imagedata fileref="./images/compute-service-offerings.png"/>
</imageobject>
<textobject>
<phrase>Use the GUI to set the name of a compute service offering to an EC2 instance
type API name.</phrase>
</textobject>
</mediaobject>
</para>
</section>
<section id="aws-api-port-change">
<title>Modifying the AWS API Port</title>
<note>
<para>(Optional) The AWS API listens for requests on port 7080. If you prefer AWS API to listen on another port, you can change it as follows:</para>
<orderedlist numeration="loweralpha">
<listitem><para>Edit the files /etc/cloud/management/server.xml, /etc/cloud/management/server-nonssl.xml,
and /etc/cloud/management/server-ssl.xml.</para></listitem>
<listitem><para>In each file, find the tag &lt;Service name="Catalina7080"&gt;. Under this tag,
locate &lt;Connector executor="tomcatThreadPool-internal" port= ....&lt;.</para></listitem>
<listitem><para>Change the port to whatever port you want to use, then save the files.</para></listitem>
<listitem><para>Restart the Management Server.</para></listitem>
</orderedlist>
<para>If you re-install &PRODUCT;, you will have to re-enable the services and if need be update the port.</para>
</note>
</section>
</section> </section>

View File

@ -23,16 +23,19 @@
--> -->
<section id="aws-ec2-introduction"> <section id="aws-ec2-introduction">
<title>Amazon Web Services EC2 Compatible Interface</title> <title>Amazon Web Services Compatible Interface</title>
<para>&PRODUCT; can translate Amazon Web Services (AWS) API calls to native &PRODUCT; API calls <para>&PRODUCT; can translate Amazon Web Services (AWS) API calls to native &PRODUCT; API calls
so that users can continue using existing AWS-compatible tools. This translation service runs as so that users can continue using existing AWS-compatible tools. This translation service runs as
a separate web application in the same tomcat server as the management server of &PRODUCT;, a separate web application in the same tomcat server as the management server of &PRODUCT;,
listening on the same port. This Amazon EC2-compatible API is accessible through a SOAP web listening on a different port. The Amazon Web Services (AWS) compatible interface provides the
service.</para> EC2 SOAP and Query APIs as well as the S3 REST API.</para>
<note> <note>
<para>This service was previously enabled by separate software called CloudBridge. It is now <para>This service was previously enabled by separate software called CloudBridge. It is now
fully integrated with the &PRODUCT; management server. </para> fully integrated with the &PRODUCT; management server. </para>
</note> </note>
<warning>
<para>The compatible interface for the EC2 Query API and the S3 API are Work In Progress. The S3 compatible API offers a way to store data on the management server file system, it is not an implementation of the S3 backend.</para>
</warning>
<para>Limitations</para> <para>Limitations</para>
<itemizedlist> <itemizedlist>
<listitem> <listitem>
@ -42,7 +45,9 @@
<para>Available in fresh installations of &PRODUCT;. Not available through upgrade of previous versions.</para> <para>Available in fresh installations of &PRODUCT;. Not available through upgrade of previous versions.</para>
</listitem> </listitem>
<listitem> <listitem>
<para>If you need to support features such as elastic IP, set up a Citrix NetScaler to provide this service. The commands such as ec2-associate-address will not work without EIP setup. Users running VMs in this zone will be using the NetScaler-enabled network offering (DefaultSharedNetscalerEIP and ELBNetworkOffering).</para> <para>Features such as Elastic IP (EIP) and Elastic Load Balacing (ELB) are only available in an infrastructure
with a Citrix NetScaler device. Users accessing a Zone with a NetScaler device will need to use a
NetScaler-enabled network offering (DefaultSharedNetscalerEIP and ELBNetworkOffering).</para>
</listitem> </listitem>
</itemizedlist> </itemizedlist>
</section> </section>

View File

@ -23,13 +23,14 @@
--> -->
<section id="aws-ec2-requirements"> <section id="aws-ec2-requirements">
<title>System Requirements</title> <title>Supported API Version</title>
<itemizedlist> <itemizedlist>
<listitem><para>This interface complies with Amazon's WDSL version dated November 15, 2010, available at <listitem><para>The EC2 interface complies with Amazon's WDSL version dated November 15, 2010, available at
<ulink url="http://ec2.amazonaws.com/doc/2010-11-15/">http://ec2.amazonaws.com/doc/2010-11-15/</ulink>.</para></listitem> <ulink url="http://ec2.amazonaws.com/doc/2010-11-15/">http://ec2.amazonaws.com/doc/2010-11-15/</ulink>.</para></listitem>
<listitem><para>Compatible with the EC2 command-line <listitem><para>The interface is compatible with the EC2 command-line
tools <emphasis>EC2 tools v. 1.3.6230</emphasis>, which can be downloaded at <ulink tools <emphasis>EC2 tools v. 1.3.6230</emphasis>, which can be downloaded at <ulink
url="http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip">http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip</ulink>.</para> url="http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip">http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip</ulink>.</para>
</listitem> </listitem>
</itemizedlist> </itemizedlist>
</section> <note><para>Work is underway to support a more recent version of the EC2 API</para></note>
</section>

View File

@ -24,7 +24,7 @@
<section id="aws-ec2-supported-commands"> <section id="aws-ec2-supported-commands">
<title>Supported AWS API Calls</title> <title>Supported AWS API Calls</title>
<para>The following Amazon EC2 commands are supported by &PRODUCT; when the AWS API compatibility feature is enabled. <para>The following Amazon EC2 commands are supported by &PRODUCT; when the AWS API compatible interface is enabled.
For a few commands, there are differences between the &PRODUCT; and Amazon EC2 versions, and these differences are noted. The underlying SOAP call for each command is also given, for those who have built tools using those calls. For a few commands, there are differences between the &PRODUCT; and Amazon EC2 versions, and these differences are noted. The underlying SOAP call for each command is also given, for those who have built tools using those calls.
</para> </para>
<table frame='all'> <table frame='all'>

View File

@ -24,7 +24,7 @@
<section id="aws-ec2-timeouts"> <section id="aws-ec2-timeouts">
<title>Using Timeouts to Ensure AWS API Command Completion</title> <title>Using Timeouts to Ensure AWS API Command Completion</title>
<para>The Amazon EC2 command-line tools have a default connection timeout. When used with &PRODUCT;, a longer timeout might be needed for some commands. If you find that commands are not completing due to timeouts, you can gain more time for commands to finish by overriding the default timeouts on individual commands. You can add the following optional command-line parameters to any &PRODUCT;-supported EC2 command:</para> <para>The Amazon EC2 command-line tools have a default connection timeout. When used with &PRODUCT;, a longer timeout might be needed for some commands. If you find that commands are not completing due to timeouts, you can specify a custom timeouts. You can add the following optional command-line parameters to any &PRODUCT;-supported EC2 command:</para>
<informaltable frame="all"> <informaltable frame="all">
<tgroup cols="2" align="left" colsep="1" rowsep="1"> <tgroup cols="2" align="left" colsep="1" rowsep="1">
<colspec colname="c1" /> <colspec colname="c1" />
@ -47,4 +47,5 @@
</informaltable> </informaltable>
<para>Example:</para> <para>Example:</para>
<programlisting>ec2-run-instances 2 z us-test1 n 1-3 --connection-timeout 120 --request-timeout 120</programlisting> <programlisting>ec2-run-instances 2 z us-test1 n 1-3 --connection-timeout 120 --request-timeout 120</programlisting>
</section> <note><para>The timeouts optional arguments are not specific to &PRODUCT;.</para></note>
</section>

View File

@ -22,76 +22,84 @@
under the License. under the License.
--> -->
<section id="aws-ec2-user-setup"> <section id="aws-ec2-user-setup">
<title>AWS API User Setup Steps</title> <title>AWS API User Setup</title>
<para>In general, users need not be aware that they are using a translation service provided by &PRODUCT;. <para>In general, users need not be aware that they are using a translation service provided by &PRODUCT;.
They need only send AWS API calls to &PRODUCT;'s endpoint, and it will translate the calls to the native API. They only need to send AWS API calls to &PRODUCT;'s endpoint, and it will translate the calls to the native &PRODUCT; API. Users of the Amazon EC2 compatible interface will be able to keep their existing EC2 tools
Users of the Amazon EC2 compatible interface will be able to keep their existing EC2 tools
and scripts and use them with their &PRODUCT; deployment, by specifying the endpoint of the and scripts and use them with their &PRODUCT; deployment, by specifying the endpoint of the
management server and using the proper user credentials. In order to do this, each user must management server and using the proper user credentials. In order to do this, each user must
perform the following configuration steps: </para> perform the following configuration steps: </para>
<para> <para>
<itemizedlist> <itemizedlist>
<listitem> <listitem>
<para>Generate user credentials and register with the service.</para> <para>Generate user credentials.</para>
</listitem> </listitem>
<listitem> <listitem>
<para>Set up the environment variables for the EC2 command-line tools.</para> <para>Register with the service.</para>
</listitem> </listitem>
<listitem> <listitem>
<para>For SOAP access, use the endpoint http://<replaceable>&PRODUCT;-management-server</replaceable>:7080/awsapi. <para>For convenience, set up environment variables for the EC2 SOAP command-line tools.</para>
The <replaceable>&PRODUCT;-management-server</replaceable> can be specified by a fully-qualified domain name or IP address.</para>
</listitem> </listitem>
</itemizedlist> </itemizedlist>
</para> </para>
<section id="aws-ec2-user-registration"> <section id="aws-ec2-user-registration">
<title>AWS API User Registration</title> <title>AWS API User Registration</title>
<para>Each user must perform a one-time registration. The user follows these steps:</para> <para>Each user must perform a one-time registration. The user follows these steps:</para>
<orderedlist> <orderedlist>
<listitem> <listitem>
<para>Obtain the following by looking in the &PRODUCT; UI, using the API, or asking the cloud administrator:</para> <para>Obtain the following by looking in the &PRODUCT; UI, using the API, or asking the cloud administrator:
<itemizedlist> </para>
<listitem><para>The &PRODUCT; server's publicly available DNS name or IP address</para></listitem> <itemizedlist>
<listitem><para>The user account's API key and Secret key</para></listitem> <listitem><para>The &PRODUCT; server's publicly available DNS name or IP address</para></listitem>
</itemizedlist> <listitem><para>The user account's Access key and Secret key</para></listitem>
</listitem> </itemizedlist>
<listitem> </listitem>
<para> <listitem>
Generate a private key and a self-signed X.509 certificate. The user substitutes their own desired storage location for /path/to/… below. <para>Generate a private key and a self-signed X.509 certificate. The user substitutes their own desired storage location for /path/to/… below.
</para> </para>
<para><programlisting>$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private_key.pem -out /path/to/cert.pem</programlisting> <para>
</para> <programlisting>$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private_key.pem -out /path/to/cert.pem</programlisting>
</listitem> </para>
<listitem> </listitem>
<para> <listitem>
Register the mapping from the X.509 certificate to the API/Secret keys. <para>Register the user X.509 certificate and Access/Secret keys with the AWS compatible service.
Download the following script from http://download.cloud.com/releases/3.0.3/cloudstack-aws-api-register and run it. If you have the source code of &PRODUCT; go to the awsapi-setup/setup directory and use the Python script
Substitute the values that were obtained in step 1 in the URL below. cloudstack-aws-api-register. If you do not have the source then download the script using the following command.
</para> </para>
<para> <para>
<programlisting>$ cloudstack-aws-api-register --apikey=<replaceable>Users &PRODUCT; API key</replaceable> --secretkey=<replaceable>Users &PRODUCT; Secret key</replaceable> --cert=<replaceable>/path/to/cert.pem</replaceable> --url=http://<replaceable>&PRODUCT;.server</replaceable>:7080/awsapi</programlisting> <programlisting>wget -O cloudstack-aws-api-register <ulink url="https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=awsapi-setup/setup/cloudstack-aws-api-register;hb=HEAD">"https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=awsapi-setup/setup/cloudstack-aws-api-register;hb=HEAD"</ulink>
</para> </programlisting>
</listitem> </para>
</orderedlist> <para> Then execute it, using the parameter values that were obtained in step 1. An example is shown below.</para>
<para>
<programlisting>$ cloudstack-aws-api-register --apikey=<replaceable>Users &PRODUCT; API key</replaceable> --secretkey=<replaceable>Users &PRODUCT; Secret key</replaceable> --cert=<replaceable>/path/to/cert.pem</replaceable> --url=http://<replaceable>&PRODUCT;.server</replaceable>:7080/awsapi</programlisting>
</para>
</listitem>
</orderedlist>
<note> <note>
<para> <para>
A user with an existing AWS certificate could choose to use the same certificate with &PRODUCT;, but the public key would be uploaded to the &PRODUCT; management server database. A user with an existing AWS certificate could choose to use the same certificate with &PRODUCT;, but note that the certificate would be uploaded to the &PRODUCT; management server database.
</para> </para>
</note> </note>
</section> </section>
<section id="aws-api-tools-setup"> <section id="aws-api-tools-setup">
<title>AWS API Command-Line Tools Setup</title> <title>AWS API Command-Line Tools Setup</title>
<para>To use the EC2 command-line tools, the user must perform these steps:</para> <para>To use the EC2 command-line tools, the user must perform these steps:</para>
<orderedlist> <orderedlist>
<listitem><para>Be sure you have the right version of EC2 Tools. <listitem>
The supported version is available at <ulink url="http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip">http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip</ulink>.</para> <para>Be sure you have the right version of EC2 Tools.
</listitem> The supported version is available at <ulink url="http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip">http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip</ulink>.
<listitem> </para>
<para>Set up the environment variables that will direct the tools to the server. As a best practice, you may wish to place these commands in a script that may be sourced before using the AWS API translation feature.</para> </listitem>
<programlisting>$ export EC2_CERT=/path/to/cert.pem <listitem>
$ export EC2_PRIVATE_KEY=/path/to/private_key.pem <para>Set up the EC2 environment variables. This can be done every time you use the service or you can set them up in the proper shell profile. Replace the endpoint (i.e EC2_URL) with the proper address of your &PRODUCT; management server and port. In a bash shell do the following.
$ export EC2_URL=http://<replaceable>&PRODUCT;.server</replaceable>:7080/awsapi </para>
$ export EC2_HOME=/path/to/EC2_tools_directory</programlisting> <programlisting>
</listitem> $ export EC2_CERT=/path/to/cert.pem
</orderedlist> $ export EC2_PRIVATE_KEY=/path/to/private_key.pem
$ export EC2_URL=http://localhost:7080/awsapi
$ export EC2_HOME=/path/to/EC2_tools_directory
</programlisting>
</listitem>
</orderedlist>
</section> </section>
</section> </section>

View File

@ -23,11 +23,12 @@
--> -->
<chapter id="aws-interface-compatibility"> <chapter id="aws-interface-compatibility">
<title>Amazon Web Service Interface Compatibility</title> <title>Amazon Web Services Compatible Interface</title>
<xi:include href="aws-ec2-introduction.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> <xi:include href="aws-ec2-introduction.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="aws-ec2-requirements.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> <xi:include href="aws-ec2-requirements.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="aws-ec2-configuration.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> <xi:include href="aws-ec2-configuration.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="aws-ec2-user-setup.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> <xi:include href="aws-ec2-user-setup.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="aws-ec2-timeouts.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> <xi:include href="aws-ec2-timeouts.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="aws-ec2-supported-commands.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> <xi:include href="aws-ec2-supported-commands.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="aws-api-examples.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
</chapter> </chapter>

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

View File

@ -23,9 +23,11 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.Set;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject; import javax.inject.Inject;
@ -34,18 +36,13 @@ import javax.naming.ConfigurationException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
import com.cloud.user.Account;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.PluggableService; import com.cloud.utils.component.PluggableService;
/* // This is the default API access checker that grab's the user's account
* This is the default API access checker that grab's the user's account // based on the account type, access is granted
* based on the account type, access is granted referring to commands in all *.properties files.
*/
@Local(value=APIAccessChecker.class) @Local(value=APIAccessChecker.class)
public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIAccessChecker { public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIAccessChecker {
@ -54,53 +51,50 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
public static final short DOMAIN_ADMIN_COMMAND = 4; public static final short DOMAIN_ADMIN_COMMAND = 4;
public static final short RESOURCE_DOMAIN_ADMIN_COMMAND = 2; public static final short RESOURCE_DOMAIN_ADMIN_COMMAND = 2;
public static final short USER_COMMAND = 8; public static final short USER_COMMAND = 8;
private static List<String> s_userCommands = null;
private static List<String> s_resellerCommands = null; // AKA domain-admin
private static List<String> s_adminCommands = null;
private static List<String> s_resourceDomainAdminCommands = null;
private static List<String> s_allCommands = null;
@Inject AccountManager _accountMgr; @Inject AccountManager _accountMgr;
@Inject List<PluggableService> _services; @Inject List<PluggableService> _services;
private static Set<String> s_userCommands = null;
private static Set<String> s_resellerCommands = null; // AKA domain-admin
private static Set<String> s_adminCommands = null;
private static Set<String> s_resourceDomainAdminCommands = null;
private static Set<String> s_allCommands = null;
protected StaticRoleBasedAPIAccessChecker() { protected StaticRoleBasedAPIAccessChecker() {
super(); super();
s_allCommands = new ArrayList<String>(); s_allCommands = new HashSet<String>();
s_userCommands = new ArrayList<String>(); s_userCommands = new HashSet<String>();
s_resellerCommands = new ArrayList<String>(); s_resellerCommands = new HashSet<String>();
s_adminCommands = new ArrayList<String>(); s_adminCommands = new HashSet<String>();
s_resourceDomainAdminCommands = new ArrayList<String>(); s_resourceDomainAdminCommands = new HashSet<String>();
} }
@Override @Override
public boolean canAccessAPI(User user, String apiCommandName) public boolean canAccessAPI(RoleType roleType, String apiCommandName)
throws PermissionDeniedException{ throws PermissionDeniedException{
boolean commandExists = s_allCommands.contains(apiCommandName); boolean commandExists = s_allCommands.contains(apiCommandName);
if(commandExists && user != null){ if(commandExists) {
Long accountId = user.getAccountId(); return isCommandAvailableForAccount(roleType, apiCommandName);
Account userAccount = _accountMgr.getAccount(accountId);
short accountType = userAccount.getType();
return isCommandAvailableForAccount(accountType, apiCommandName);
} }
return commandExists; return commandExists;
} }
private static boolean isCommandAvailableForAccount(short accountType, String commandName) { private static boolean isCommandAvailableForAccount(RoleType roleType, String commandName) {
boolean isCommandAvailable = false; boolean isCommandAvailable = false;
switch (accountType) { switch (roleType) {
case Account.ACCOUNT_TYPE_ADMIN: case Admin:
isCommandAvailable = s_adminCommands.contains(commandName); isCommandAvailable = s_adminCommands.contains(commandName);
break; break;
case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: case DomainAdmin:
isCommandAvailable = s_resellerCommands.contains(commandName); isCommandAvailable = s_resellerCommands.contains(commandName);
break; break;
case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: case ResourceAdmin:
isCommandAvailable = s_resourceDomainAdminCommands.contains(commandName); isCommandAvailable = s_resourceDomainAdminCommands.contains(commandName);
break; break;
case Account.ACCOUNT_TYPE_NORMAL: case User:
isCommandAvailable = s_userCommands.contains(commandName); isCommandAvailable = s_userCommands.contains(commandName);
break; break;
} }
@ -154,16 +148,16 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA
try { try {
short cmdPermissions = Short.parseShort(mask); short cmdPermissions = Short.parseShort(mask);
if ((cmdPermissions & ADMIN_COMMAND) != 0) { if ((cmdPermissions & Admin.getValue()) != 0) {
s_adminCommands.add((String) key); s_adminCommands.add((String) key);
} }
if ((cmdPermissions & RESOURCE_DOMAIN_ADMIN_COMMAND) != 0) { if ((cmdPermissions & ResourceAdmin.getValue()) != 0) {
s_resourceDomainAdminCommands.add((String) key); s_resourceDomainAdminCommands.add((String) key);
} }
if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { if ((cmdPermissions & DomainAdmin.getValue()) != 0) {
s_resellerCommands.add((String) key); s_resellerCommands.add((String) key);
} }
if ((cmdPermissions & USER_COMMAND) != 0) { if ((cmdPermissions & User.getValue()) != 0) {
s_userCommands.add((String) key); s_userCommands.add((String) key);
} }
s_allCommands.addAll(s_adminCommands); s_allCommands.addAll(s_adminCommands);

View File

@ -16,14 +16,10 @@
// under the License. // under the License.
package org.apache.cloudstack.discovery; package org.apache.cloudstack.discovery;
import com.cloud.utils.component.Adapter;
import com.cloud.utils.component.PluggableService; import com.cloud.utils.component.PluggableService;
import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ListResponse;
import java.util.Map; public interface ApiDiscoveryService extends PluggableService {
public interface ApiDiscoveryService extends Adapter, PluggableService {
ListResponse<? extends BaseResponse> listApis(); ListResponse<? extends BaseResponse> listApis();
Map<String, Class<?>> getApiNameCmdClassMapping();
} }

View File

@ -17,7 +17,6 @@
package org.apache.cloudstack.discovery; package org.apache.cloudstack.discovery;
import com.cloud.utils.ReflectUtil; import com.cloud.utils.ReflectUtil;
import com.cloud.utils.component.AdapterBase;
import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCmd;
@ -30,7 +29,6 @@ import org.apache.cloudstack.api.response.ListResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import javax.ejb.Local; import javax.ejb.Local;
import javax.naming.ConfigurationException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -39,36 +37,28 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
@Local(value = ApiDiscoveryService.class) @Local(value = ApiDiscoveryService.class)
public class ApiDiscoveryServiceImpl extends AdapterBase implements ApiDiscoveryService { public class ApiDiscoveryServiceImpl implements ApiDiscoveryService {
private static final Logger s_logger = Logger.getLogger(ApiDiscoveryServiceImpl.class); private static final Logger s_logger = Logger.getLogger(ApiDiscoveryServiceImpl.class);
private Map<String, Class<?>> _apiNameCmdClassMap;
private ListResponse<ApiDiscoveryResponse> _discoveryResponse; private ListResponse<ApiDiscoveryResponse> _discoveryResponse = new ListResponse<ApiDiscoveryResponse>();
private Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>();
protected ApiDiscoveryServiceImpl() { protected ApiDiscoveryServiceImpl() {
super(); super();
generateApiNameCmdClassMap();
cacheListApiResponse();
} }
private void generateApiNameCmdClassMapping() { private void generateApiNameCmdClassMap() {
_apiNameCmdClassMap = new HashMap<String, Class<?>>(); Set<Class<?>> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class,
Set<Class<?>> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, new String[]{"org.apache.cloudstack.api", "com.cloud.api"}); new String[]{"org.apache.cloudstack.api", "com.cloud.api"});
for(Class<?> cmdClass: cmdClasses) { for(Class<?> cmdClass: cmdClasses)
String apiName = cmdClass.getAnnotation(APICommand.class).name(); _apiNameCmdClassMap.put(cmdClass.getAnnotation(APICommand.class).name(), cmdClass);
if (_apiNameCmdClassMap.containsKey(apiName)) {
s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName);
continue;
}
_apiNameCmdClassMap.put(apiName, cmdClass);
}
} }
private void precacheListApiResponse() { private void cacheListApiResponse() {
if(_apiNameCmdClassMap == null)
return;
_discoveryResponse = new ListResponse<ApiDiscoveryResponse>();
List<ApiDiscoveryResponse> apiDiscoveryResponses = new ArrayList<ApiDiscoveryResponse>(); List<ApiDiscoveryResponse> apiDiscoveryResponses = new ArrayList<ApiDiscoveryResponse>();
@ -117,21 +107,6 @@ public class ApiDiscoveryServiceImpl extends AdapterBase implements ApiDiscovery
_discoveryResponse.setResponses(apiDiscoveryResponses); _discoveryResponse.setResponses(apiDiscoveryResponses);
} }
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
super.configure(name, params);
generateApiNameCmdClassMapping();
precacheListApiResponse();
return true;
}
public Map<String, Class<?>> getApiNameCmdClassMapping() {
return _apiNameCmdClassMap;
}
@Override @Override
public ListResponse<? extends BaseResponse> listApis() { public ListResponse<? extends BaseResponse> listApis() {
return _discoveryResponse; return _discoveryResponse;

View File

@ -662,7 +662,7 @@ public class NetappManagerImpl implements NetappManager
lun = _lunDao.persist(lun); lun = _lunDao.persist(lun);
//Lun id created: 6 digits right justified eg. 000045 //Lun id created: 6 digits right justified eg. 000045
String lunIdStr = lun.getId().toString(); String lunIdStr = String.valueOf(lun.getId());
String zeroStr = "000000"; String zeroStr = "000000";
int length = lunIdStr.length(); int length = lunIdStr.length();
int offset = 6-length; int offset = 6-length;

View File

@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing, // Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an // software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the // KIND, either express or implied. See the License for the
// specific language governing permissions and limitations // specific language governing permissions and limitations
// under the License. // under the License.
package com.cloud.network; package com.cloud.network;
@ -49,7 +49,7 @@ import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper;
public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
@Inject @Inject
CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao; CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao;
@Inject @Inject
ClusterDao _clusterDao; ClusterDao _clusterDao;
@Inject @Inject
@ -66,9 +66,9 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
PortProfileDao _ppDao; PortProfileDao _ppDao;
@Inject @Inject
ConfigurationDao _configDao; ConfigurationDao _configDao;
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class);
@DB @DB
//public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, ServerResource resource, String vsmName) { //public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, ServerResource resource, String vsmName) {
public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, String vCenterIpaddr, String vCenterDcName) { public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, String vCenterIpaddr, String vCenterDcName) {
@ -78,7 +78,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
// First check if the cluster is of type vmware. If not, // First check if the cluster is of type vmware. If not,
// throw an exception. VSMs are tightly integrated with vmware clusters. // throw an exception. VSMs are tightly integrated with vmware clusters.
ClusterVO cluster = _clusterDao.findById(clusterId); ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null) { if (cluster == null) {
throw new InvalidParameterValueException("Cluster with specified ID not found!"); throw new InvalidParameterValueException("Cluster with specified ID not found!");
@ -91,21 +91,21 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
// Next, check if the cluster already has a VSM associated with it. // Next, check if the cluster already has a VSM associated with it.
// If so, throw an exception disallowing this operation. The user must first // If so, throw an exception disallowing this operation. The user must first
// delete the current VSM and then only attempt to add the new one. // delete the current VSM and then only attempt to add the new one.
if (_clusterVSMDao.findByClusterId(clusterId) != null) { if (_clusterVSMDao.findByClusterId(clusterId) != null) {
// We can't have two VSMs for the same cluster. Throw exception. // We can't have two VSMs for the same cluster. Throw exception.
throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation."); throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation.");
} }
// TODO: Confirm whether we should be checking for VSM reachability here. // TODO: Confirm whether we should be checking for VSM reachability here.
// Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to // Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to
// the VSM. // the VSM.
//NetconfHelper (String ip, String username, String password) //NetconfHelper (String ip, String username, String password)
NetconfHelper netconfClient; NetconfHelper netconfClient;
try { try {
netconfClient = new NetconfHelper(ipaddress, username, password); netconfClient = new NetconfHelper(ipaddress, username, password);
} catch(CloudRuntimeException e) { } catch(CloudRuntimeException e) {
String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username; String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username;
s_logger.error(msg); s_logger.error(msg);
@ -119,7 +119,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
// First, check if VSM already exists in the table "virtual_supervisor_module". // First, check if VSM already exists in the table "virtual_supervisor_module".
// If it's not there already, create it. // If it's not there already, create it.
// If it's there already, return success. // If it's there already, return success.
// TODO - Right now, we only check if the ipaddress matches for both requests. // TODO - Right now, we only check if the ipaddress matches for both requests.
// We must really check whether every field of the VSM matches. Anyway, the // We must really check whether every field of the VSM matches. Anyway, the
// advantage of our approach for now is that existing infrastructure using // advantage of our approach for now is that existing infrastructure using
@ -132,7 +132,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
if (VSMObj == null) { if (VSMObj == null) {
// Create the VSM record. For now, we aren't using the vsmName field. // Create the VSM record. For now, we aren't using the vsmName field.
VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password); VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -145,7 +145,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
} }
// At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id. // At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id.
long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId(); long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId();
ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId); ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId);
@ -158,22 +158,22 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
txn.rollback(); txn.rollback();
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
// Now, get a list of all the ESXi servers in this cluster. // Now, get a list of all the ESXi servers in this cluster.
// This is effectively a select * from host where cluster_id=clusterId; // This is effectively a select * from host where cluster_id=clusterId;
// All ESXi servers are stored in the host table, and their resource // All ESXi servers are stored in the host table, and their resource
// type is vmwareresource. // type is vmwareresource.
//List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId); //List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
//TODO: Activate the code below if we make the Nexus VSM a separate resource. //TODO: Activate the code below if we make the Nexus VSM a separate resource.
// Iterate through each of the hosts in this list. Each host has a host id. // Iterate through each of the hosts in this list. Each host has a host id.
// Given this host id, we can reconfigure the in-memory resource representing // Given this host id, we can reconfigure the in-memory resource representing
// the host via the agent manager. Thus we inject VSM related information // the host via the agent manager. Thus we inject VSM related information
// into each host's resource. Also, we first configure each resource's // into each host's resource. Also, we first configure each resource's
// entries in the database to contain this VSM information before the injection. // entries in the database to contain this VSM information before the injection.
//for (HostVO host : hosts) { //for (HostVO host : hosts) {
// Create a host details VO object and write it out for this hostid. // Create a host details VO object and write it out for this hostid.
//Long hostid = new Long(vsmId); //Long hostid = new Long(vsmId);
//DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString()); //DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString());
@ -194,28 +194,28 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
//hostDetails.put(ApiConstants.USERNAME, username); //hostDetails.put(ApiConstants.USERNAME, username);
//hostDetails.put(ApiConstants.PASSWORD, password); //hostDetails.put(ApiConstants.PASSWORD, password);
//_agentMrg.send(host.getId(), ) //_agentMrg.send(host.getId(), )
return VSMObj; return VSMObj;
} }
@DB @DB
public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException { public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) { if (cisconexusvsm == null) {
// This entry is already not present. Return success. // This entry is already not present. Return success.
return true; return true;
} }
// First, check whether this VSM is part of any non-empty cluster. // First, check whether this VSM is part of any non-empty cluster.
// Search ClusterVSMMap's table for a list of clusters using this vsmId. // Search ClusterVSMMap's table for a list of clusters using this vsmId.
List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsmId); List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsmId);
if (clusterList != null) { if (clusterList != null) {
for (ClusterVSMMapVO record : clusterList) { for (ClusterVSMMapVO record : clusterList) {
// If this cluster id has any hosts in it, fail this operation. // If this cluster id has any hosts in it, fail this operation.
Long clusterId = record.getClusterId(); Long clusterId = record.getClusterId();
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId); List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) { if (hosts != null && hosts.size() > 0) {
for (Host host: hosts) { for (Host host: hosts) {
@ -223,26 +223,26 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
} }
} }
} }
} }
} }
// Iterate through the cluster list again, this time, delete the VSM. // Iterate through the cluster list again, this time, delete the VSM.
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
txn.start(); txn.start();
// Remove the VSM entry in CiscoNexusVSMDeviceVO's table. // Remove the VSM entry in CiscoNexusVSMDeviceVO's table.
_ciscoNexusVSMDeviceDao.remove(vsmId); _ciscoNexusVSMDeviceDao.remove(vsmId);
// Remove the current record as well from ClusterVSMMapVO's table. // Remove the current record as well from ClusterVSMMapVO's table.
_clusterVSMDao.removeByVsmId(vsmId); _clusterVSMDao.removeByVsmId(vsmId);
// There are no hosts at this stage in the cluster, so we don't need // There are no hosts at this stage in the cluster, so we don't need
// to notify any resources or remove host details. // to notify any resources or remove host details.
txn.commit(); txn.commit();
} catch (Exception e) { } catch (Exception e) {
s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage()); s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete VSM"); throw new CloudRuntimeException("Failed to delete VSM");
} }
return true; return true;
} }
@ -250,10 +250,10 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(long vsmId) { public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(long vsmId) {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) { if (cisconexusvsm == null) {
throw new InvalidParameterValueException("Invalid vsm Id specified"); throw new InvalidParameterValueException("Invalid vsm Id specified");
} }
// Else, check if this db record shows that this VSM is enabled or not. // Else, check if this db record shows that this VSM is enabled or not.
if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) { if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) {
// it's currently disabled. So change it to enabled and write it out to the db. // it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled); cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -266,18 +266,18 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
} }
return cisconexusvsm; return cisconexusvsm;
} }
@DB @DB
public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(long vsmId) { public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(long vsmId) {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) { if (cisconexusvsm == null) {
throw new InvalidParameterValueException("Invalid vsm Id specified"); throw new InvalidParameterValueException("Invalid vsm Id specified");
} }
// Else, check if this db record shows that this VSM is enabled or not. // Else, check if this db record shows that this VSM is enabled or not.
if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) { if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) {
// it's currently disabled. So change it to enabled and write it out to the db. // it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled); cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -290,15 +290,15 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
throw new CloudRuntimeException(e.getMessage()); throw new CloudRuntimeException(e.getMessage());
} }
} }
return cisconexusvsm; return cisconexusvsm;
} }
@DB @DB
public CiscoNexusVSMDeviceVO getCiscoVSMbyVSMId(long vsmId) { public CiscoNexusVSMDeviceVO getCiscoVSMbyVSMId(long vsmId) {
return _ciscoNexusVSMDeviceDao.findById(vsmId); return _ciscoNexusVSMDeviceDao.findById(vsmId);
} }
@DB @DB
public CiscoNexusVSMDeviceVO getCiscoVSMbyClusId(long clusterId) { public CiscoNexusVSMDeviceVO getCiscoVSMbyClusId(long clusterId) {
ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId); ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId);
@ -310,12 +310,12 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId()); CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId());
return result; return result;
} }
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
@DB @DB
public boolean vliadateVsmCluster(String vsmIp, String vsmUser, String vsmPassword, long clusterId, String clusterName) throws ResourceInUseException { public boolean vliadateVsmCluster(String vsmIp, String vsmUser, String vsmPassword, long clusterId, String clusterName) throws ResourceInUseException {
// Check if we're associating a Cisco Nexus VSM with a vmware cluster. // Check if we're associating a Cisco Nexus VSM with a vmware cluster.
@ -343,7 +343,9 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster"); s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster");
_clusterDao.remove(clusterId); _clusterDao.remove(clusterId);
ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id"); ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id");
ex.addProxyObject("cluster", clusterList.get(0).getClusterId(), "clusterId"); // get clusterUuid to report error
ClusterVO cluster = _clusterDao.findById(clusterList.get(0).getClusterId());
ex.addProxyObject(cluster.getUuid());
throw ex; throw ex;
} }
} }

View File

@ -26,6 +26,7 @@ import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import com.cloud.host.Host; import com.cloud.host.Host;
import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.network.element.F5ExternalLoadBalancerElementService;
import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse;
@ -40,7 +41,7 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd {
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneRespones.class, @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class,
description="zone Id") description="zone Id")
private long zoneId; private long zoneId;

View File

@ -31,6 +31,7 @@ import org.apache.cloudstack.api.PlugService;
import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.NetworkResponse;
import com.cloud.api.response.F5LoadBalancerResponse;
import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;

View File

@ -262,8 +262,8 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
} }
@Override @Override
public String getPropertiesFile() { public String[] getPropertiesFiles() {
return "f5bigip_commands.properties"; return new String[] { "f5bigip_commands.properties" };
} }
@Override @Override

View File

@ -404,8 +404,8 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
} }
@Override @Override
public String getPropertiesFile() { public String[] getPropertiesFiles() {
return "junipersrx_commands.properties"; return new String[] { "junipersrx_commands.properties"};
} }
@Override @Override

View File

@ -49,7 +49,7 @@ public class ListNetscalerLoadBalancerNetworksCmd extends BaseListCmd {
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, , @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class,
required = true, description="netscaler load balancer device ID") required = true, description="netscaler load balancer device ID")
private Long lbDeviceId; private Long lbDeviceId;

View File

@ -466,8 +466,8 @@ StaticNatServiceProvider {
} }
@Override @Override
public String getPropertiesFile() { public String[] getPropertiesFiles() {
return "netscalerloadbalancer_commands.properties"; return new String[] { "netscalerloadbalancer_commands.properties" };
} }
@Override @Override

View File

@ -346,6 +346,7 @@
<exclude>scripts/vm/systemvm/id_rsa.cloud</exclude> <exclude>scripts/vm/systemvm/id_rsa.cloud</exclude>
<exclude>tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf</exclude> <exclude>tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf</exclude>
<exclude>tools/devcloud/devcloud.cfg</exclude> <exclude>tools/devcloud/devcloud.cfg</exclude>
<exclude>tools/devcloud-kvm/devcloud-kvm.cfg</exclude>
<exclude>ui/lib/flot/jquery.colorhelpers.js</exclude> <exclude>ui/lib/flot/jquery.colorhelpers.js</exclude>
<exclude>ui/lib/flot/jquery.flot.crosshair.js</exclude> <exclude>ui/lib/flot/jquery.flot.crosshair.js</exclude>
<exclude>ui/lib/flot/jquery.flot.fillbetween.js</exclude> <exclude>ui/lib/flot/jquery.flot.fillbetween.js</exclude>
@ -472,6 +473,7 @@
<module>developer</module> <module>developer</module>
<module>tools/apidoc</module> <module>tools/apidoc</module>
<module>tools/devcloud</module> <module>tools/devcloud</module>
<module>tools/devcloud-kvm</module>
<module>tools/marvin</module> <module>tools/marvin</module>
<module>tools/cli</module> <module>tools/cli</module>
</modules> </modules>

View File

@ -17,7 +17,6 @@
package com.cloud.api; package com.cloud.api;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.cloud.utils.IdentityProxy;
import org.apache.cloudstack.api.ResponseObject; import org.apache.cloudstack.api.ResponseObject;
import java.util.Map; import java.util.Map;
@ -28,7 +27,6 @@ public class ApiGsonHelper {
s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
s_gBuilder.setVersion(1.3); s_gBuilder.setVersion(1.3);
s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter()); s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter());
s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter());
s_gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter()); s_gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter());
} }

View File

@ -17,7 +17,6 @@
package com.cloud.api; package com.cloud.api;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.cloud.utils.IdentityProxy;
import org.apache.cloudstack.api.ResponseObject; import org.apache.cloudstack.api.ResponseObject;
/** /**
@ -25,13 +24,12 @@ import org.apache.cloudstack.api.ResponseObject;
*/ */
public class ApiResponseGsonHelper { public class ApiResponseGsonHelper {
private static final GsonBuilder s_gBuilder; private static final GsonBuilder s_gBuilder;
static { static {
s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
s_gBuilder.setVersion(1.3); s_gBuilder.setVersion(1.3);
s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter()); s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter());
s_gBuilder.registerTypeAdapter(String.class, new EncodedStringTypeAdapter()); s_gBuilder.registerTypeAdapter(String.class, new EncodedStringTypeAdapter());
s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter());
} }
public static GsonBuilder getBuilder() { public static GsonBuilder getBuilder() {

View File

@ -482,7 +482,7 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setEndPoint(result.getEndPoint()); response.setEndPoint(result.getEndPoint());
response.setHttpsFlag(result.getHttpsFlag()); response.setHttpsFlag(result.getHttpsFlag());
response.setMaxErrorRetry(result.getMaxErrorRetry()); response.setMaxErrorRetry(result.getMaxErrorRetry());
response.setObjectId(result.getId()); response.setObjectId(result.getUuid());
response.setSecretKey(result.getSecretKey()); response.setSecretKey(result.getSecretKey());
response.setSocketTimeout(result.getSocketTimeout()); response.setSocketTimeout(result.getSocketTimeout());
response.setTemplateBucketName(result.getBucketName()); response.setTemplateBucketName(result.getBucketName());
@ -1265,6 +1265,7 @@ public class ApiResponseHelper implements ResponseGenerator {
templateResponse.setFeatured(template.isFeatured()); templateResponse.setFeatured(template.isFeatured());
templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
templateResponse.setPasswordEnabled(template.getEnablePassword()); templateResponse.setPasswordEnabled(template.getEnablePassword());
templateResponse.setSshKeyEnabled(template.getEnableSshKey());
templateResponse.setCrossZones(template.isCrossZones()); templateResponse.setCrossZones(template.isCrossZones());
templateResponse.setFormat(template.getFormat()); templateResponse.setFormat(template.getFormat());
templateResponse.setDetails(template.getDetails()); templateResponse.setDetails(template.getDetails());
@ -1346,6 +1347,7 @@ public class ApiResponseHelper implements ResponseGenerator {
templateResponse.setFeatured(template.isFeatured()); templateResponse.setFeatured(template.isFeatured());
templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
templateResponse.setPasswordEnabled(template.getEnablePassword()); templateResponse.setPasswordEnabled(template.getEnablePassword());
templateResponse.setSshKeyEnabled(template.getEnableSshKey());
templateResponse.setCrossZones(template.isCrossZones()); templateResponse.setCrossZones(template.isCrossZones());
templateResponse.setFormat(template.getFormat()); templateResponse.setFormat(template.getFormat());
if (template.getTemplateType() != null) { if (template.getTemplateType() != null) {

View File

@ -62,6 +62,9 @@ import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.*;
import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
@ -72,9 +75,12 @@ import org.apache.cloudstack.api.command.user.tag.ListTagsCmd;
import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vm.ListVMsCmd;
import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
<<<<<<< HEAD
import org.apache.cloudstack.api.response.ExceptionResponse; import org.apache.cloudstack.api.response.ExceptionResponse;
import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.discovery.ApiDiscoveryService; import org.apache.cloudstack.discovery.ApiDiscoveryService;
=======
>>>>>>> master
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException; import org.apache.http.HttpException;
@ -149,19 +155,19 @@ public class ApiServer implements HttpRequestHandler {
@Inject DomainManager _domainMgr; @Inject DomainManager _domainMgr;
@Inject AsyncJobManager _asyncMgr; @Inject AsyncJobManager _asyncMgr;
@Inject ConfigurationDao _configDao; @Inject ConfigurationDao _configDao;
@Inject List<APIAccessChecker> _apiAccessCheckers;
@Inject List<PluggableService> _pluggableServices; @Inject List<PluggableService> _pluggableServices;
@Inject IdentityDao _identityDao; @Inject IdentityDao _identityDao;
protected List<ApiDiscoveryService> _apiDiscoveryServices; @Inject
protected List<APIAccessChecker> _apiAccessCheckers;
private Account _systemAccount = null; private Account _systemAccount = null;
private User _systemUser = null; private User _systemUser = null;
private static int _workerCount = 0; private static int _workerCount = 0;
private static ApiServer s_instance = null; private static ApiServer s_instance = null;
private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private final Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>(); private static Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>();
private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer")); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
@ -169,7 +175,7 @@ public class ApiServer implements HttpRequestHandler {
super(); super();
} }
public static void initApiServer(String[] apiConfig) { public static void initApiServer() {
if (s_instance == null) { if (s_instance == null) {
s_instance = new ApiServer(); s_instance = new ApiServer();
s_instance = ComponentContext.inject(s_instance); s_instance = ComponentContext.inject(s_instance);
@ -178,14 +184,13 @@ public class ApiServer implements HttpRequestHandler {
} }
public static ApiServer getInstance() { public static ApiServer getInstance() {
// Assumption: CloudStartupServlet would initialize ApiServer
if (s_instance == null) { if (s_instance == null) {
s_logger.fatal("ApiServer instance failed to initialize"); ApiServer.initApiServer();
} }
return s_instance; return s_instance;
} }
public void init(String[] apiConfig) { public void init() {
BaseCmd.setComponents(new ApiResponseHelper()); BaseCmd.setComponents(new ApiResponseHelper());
BaseListCmd.configure(); BaseListCmd.configure();
@ -203,13 +208,16 @@ public class ApiServer implements HttpRequestHandler {
} }
} }
for (ApiDiscoveryService discoveryService: _apiDiscoveryServices) { Set<Class<?>> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class,
_apiNameCmdClassMap.putAll(discoveryService.getApiNameCmdClassMapping()); new String[]{"org.apache.cloudstack.api", "com.cloud.api"});
}
if (_apiNameCmdClassMap.size() == 0) { for(Class<?> cmdClass: cmdClasses) {
s_logger.fatal("ApiServer failed to generate apiname, cmd class mappings." String apiName = cmdClass.getAnnotation(APICommand.class).name();
+ "Please check and enable at least one ApiDiscovery adapter."); if (_apiNameCmdClassMap.containsKey(apiName)) {
s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName);
continue;
}
_apiNameCmdClassMap.put(apiName, cmdClass);
} }
encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key())); encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key()));
@ -403,12 +411,12 @@ public class ApiServer implements HttpRequestHandler {
// BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned. // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned.
if (cmdObj instanceof BaseAsyncCmd) { if (cmdObj instanceof BaseAsyncCmd) {
Long objectId = null; Long objectId = null;
String objectEntityTable = null; String objectUuid = null;
if (cmdObj instanceof BaseAsyncCreateCmd) { if (cmdObj instanceof BaseAsyncCreateCmd) {
BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj; BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
_dispatcher.dispatchCreateCmd(createCmd, params); _dispatcher.dispatchCreateCmd(createCmd, params);
objectId = createCmd.getEntityId(); objectId = createCmd.getEntityId();
objectEntityTable = createCmd.getEntityTable(); objectUuid = createCmd.getEntityUuid();
params.put("id", objectId.toString()); params.put("id", objectId.toString());
} else { } else {
ApiDispatcher.processParameters(cmdObj, params); ApiDispatcher.processParameters(cmdObj, params);
@ -452,8 +460,8 @@ public class ApiServer implements HttpRequestHandler {
} }
if (objectId != null) { if (objectId != null) {
SerializationContext.current().setUuidTranslation(true); String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid;
return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objectId, objectEntityTable); return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objUuid);
} }
SerializationContext.current().setUuidTranslation(true); SerializationContext.current().setUuidTranslation(true);
@ -463,6 +471,7 @@ public class ApiServer implements HttpRequestHandler {
// if the command is of the listXXXCommand, we will need to also return the // if the command is of the listXXXCommand, we will need to also return the
// the job id and status if possible // the job id and status if possible
// For those listXXXCommand which we have already created DB views, this step is not needed since async job is joined in their db views.
if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd) if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd)
&& !(cmdObj instanceof ListSecurityGroupsCmd) && !(cmdObj instanceof ListSecurityGroupsCmd)
&& !(cmdObj instanceof ListTagsCmd) && !(cmdObj instanceof ListTagsCmd)
@ -790,9 +799,39 @@ public class ApiServer implements HttpRequestHandler {
} }
private boolean isCommandAvailable(User user, String commandName) { private boolean isCommandAvailable(User user, String commandName) {
if (user == null) {
return false;
}
Account account = _accountMgr.getAccount(user.getAccountId());
if (account == null) {
return false;
}
RoleType roleType = RoleType.Unknown;
short accountType = account.getType();
// Account type to role type translation
switch (accountType) {
case Account.ACCOUNT_TYPE_ADMIN:
roleType = RoleType.Admin;
break;
case Account.ACCOUNT_TYPE_DOMAIN_ADMIN:
roleType = RoleType.DomainAdmin;
break;
case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN:
roleType = RoleType.ResourceAdmin;
break;
case Account.ACCOUNT_TYPE_NORMAL:
roleType = RoleType.User;
break;
default:
return false;
}
for (APIAccessChecker apiChecker : _apiAccessCheckers) { for (APIAccessChecker apiChecker : _apiAccessCheckers) {
// Fail the checking if any checker fails to verify // Fail the checking if any checker fails to verify
if (!apiChecker.canAccessAPI(user, commandName)) if (!apiChecker.canAccessAPI(roleType, commandName))
return false; return false;
} }
return true; return true;

View File

@ -1,80 +0,0 @@
// 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.api;
import java.lang.reflect.Type;
import com.cloud.uuididentity.dao.IdentityDao;
import com.cloud.uuididentity.dao.IdentityDaoImpl;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.cloud.utils.IdentityProxy;
public class IdentityTypeAdapter implements JsonSerializer<IdentityProxy>, JsonDeserializer<IdentityProxy> {
@Override
public JsonElement serialize(IdentityProxy src, Type srcType, JsonSerializationContext context) {
if(SerializationContext.current().getUuidTranslation()) {
assert(src != null);
if(src.getValue() == null)
return context.serialize(null);
IdentityDao identityDao = new IdentityDaoImpl();
if(src.getTableName() != null) {
String uuid = identityDao.getIdentityUuid(src.getTableName(), String.valueOf(src.getValue()));
if(uuid == null)
return context.serialize(null);
// Exceptions set the _idFieldName in the IdentityProxy structure. So if this field is not
// null, prepare a structure of uuid and idFieldName and return the json representation of that.
String idName = src.getidFieldName();
if (idName != null) {
// Prepare a structure.
JsonObject jsonObj = new JsonObject();
jsonObj.add("uuid", new JsonPrimitive(uuid));
jsonObj.add("uuidProperty", new JsonPrimitive(idName));
return jsonObj;
}
return new JsonPrimitive(uuid);
} else {
return new JsonPrimitive(String.valueOf(src.getValue()));
}
} else {
return new Gson().toJsonTree(src);
}
}
@Override
public IdentityProxy deserialize(JsonElement src, Type srcType,
JsonDeserializationContext context) throws JsonParseException {
IdentityProxy obj = new IdentityProxy();
JsonObject json = src.getAsJsonObject();
obj.setTableName(json.get("_tableName").getAsString());
if(json.get("_value") != null)
obj.setValue(json.get("_value").getAsLong());
return obj;
}
}

View File

@ -37,7 +37,6 @@ import com.cloud.api.ApiResponseGsonHelper;
import com.cloud.api.ApiServer; import com.cloud.api.ApiServer;
import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.ResponseObject; import org.apache.cloudstack.api.ResponseObject;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.encoding.URLEncoder; import com.cloud.utils.encoding.URLEncoder;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDao;
@ -226,27 +225,17 @@ public class ApiResponseSerializer {
subObj.setObjectName(serializedName.value()); subObj.setObjectName(serializedName.value());
} }
serializeResponseObjXML(sb, subObj); serializeResponseObjXML(sb, subObj);
} else if (value instanceof IdentityProxy) { } else {
// Only exception reponses carry a list of IdentityProxy objects. // Only exception reponses carry a list of uuid
IdentityProxy idProxy = (IdentityProxy)value; // strings.
String id = (idProxy.getValue() != null ? String.valueOf(idProxy.getValue()) : ""); // If this is the first IdentityProxy field
if(!id.isEmpty()) { // encountered, put in a uuidList tag.
IdentityDao identityDao = new IdentityDaoImpl(); if (!usedUuidList) {
id = identityDao.getIdentityUuid(idProxy.getTableName(), id); sb.append("<").append(serializedName.value()).append(">");
} usedUuidList = true;
if(id != null && !id.isEmpty()) { }
// If this is the first IdentityProxy field encountered, put in a uuidList tag. sb.append("<uuid>").append(value).append("</uuid>");
if (!usedUuidList) { // We have removed uuid property field due to removal of IdentityProxy class.
sb.append("<").append(serializedName.value()).append(">");
usedUuidList = true;
}
sb.append("<uuid>").append(id).append("</uuid>");
}
// Append the new idFieldName property also.
String idFieldName = idProxy.getidFieldName();
if (idFieldName != null) {
sb.append("<uuidProperty>").append(idFieldName).append("</uuidProperty>");
}
} }
} }
if (usedUuidList) { if (usedUuidList) {
@ -256,19 +245,6 @@ public class ApiResponseSerializer {
} else if (fieldValue instanceof Date) { } else if (fieldValue instanceof Date) {
sb.append("<").append(serializedName.value()).append(">").append(BaseCmd.getDateString((Date) fieldValue)). sb.append("<").append(serializedName.value()).append(">").append(BaseCmd.getDateString((Date) fieldValue)).
append("</").append(serializedName.value()).append(">"); append("</").append(serializedName.value()).append(">");
} else if (fieldValue instanceof IdentityProxy) {
IdentityProxy idProxy = (IdentityProxy)fieldValue;
String id = (idProxy.getValue() != null ? String.valueOf(idProxy.getValue()) : "");
if(!id.isEmpty()) {
IdentityDao identityDao = new IdentityDaoImpl();
if(idProxy.getTableName() != null) {
id = identityDao.getIdentityUuid(idProxy.getTableName(), id);
} else {
s_logger.warn("IdentityProxy sanity check issue, invalid IdentityProxy table name found in class: " + obj.getClass().getName());
}
}
if(id != null && !id.isEmpty())
sb.append("<").append(serializedName.value()).append(">").append(id).append("</").append(serializedName.value()).append(">");
} else { } else {
String resultString = escapeSpecialXmlChars(fieldValue.toString()); String resultString = escapeSpecialXmlChars(fieldValue.toString());
if (!(obj instanceof ExceptionResponse)) { if (!(obj instanceof ExceptionResponse)) {

View File

@ -818,26 +818,29 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
String privateIP = router.getPrivateIpAddress(); String privateIP = router.getPrivateIpAddress();
if (privateIP != null) { if (privateIP != null) {
boolean forVpc = router.getVpcId() != null;
List<? extends Nic> routerNics = _nicDao.listByVmId(router.getId()); List<? extends Nic> routerNics = _nicDao.listByVmId(router.getId());
for (Nic routerNic : routerNics) { for (Nic routerNic : routerNics) {
Network network = _networkMgr.getNetwork(routerNic.getNetworkId()); Network network = _networkMgr.getNetwork(routerNic.getNetworkId());
if (network.getTrafficType() == TrafficType.Public) { //Send network usage command for public nic in VPC VR
boolean forVpc = router.getVpcId() != null; //Send network usage command for isolated guest nic of non VPC VR
if ((forVpc && network.getTrafficType() == TrafficType.Public) || (!forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated)) {
final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(), final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(),
forVpc, routerNic.getIp4Address()); forVpc, routerNic.getIp4Address());
UserStatisticsVO previousStats = _statsDao.findBy(router.getAccountId(), String routerType = router.getType().toString();
router.getDataCenterIdToDeployIn(), network.getId(), null, router.getId(), router.getType().toString()); UserStatisticsVO previousStats = _statsDao.findBy(router.getAccountId(),
router.getDataCenterIdToDeployIn(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
NetworkUsageAnswer answer = null; NetworkUsageAnswer answer = null;
try { try {
answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd); answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd);
} catch (Exception e) { } catch (Exception e) {
s_logger.warn("Error while collecting network stats from router: "+router.getInstanceName()+" from host: "+router.getHostId(), e); s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId(), e);
continue; continue;
} }
if (answer != null) { if (answer != null) {
if (!answer.getResult()) { if (!answer.getResult()) {
s_logger.warn("Error while collecting network stats from router: "+router.getInstanceName()+" from host: "+router.getHostId() + "; details: " + answer.getDetails()); s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails());
continue; continue;
} }
Transaction txn = Transaction.open(Transaction.CLOUD_DB); Transaction txn = Transaction.open(Transaction.CLOUD_DB);
@ -847,27 +850,27 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
continue; continue;
} }
txn.start(); txn.start();
UserStatisticsVO stats = _statsDao.lock(router.getAccountId(), UserStatisticsVO stats = _statsDao.lock(router.getAccountId(),
router.getDataCenterIdToDeployIn(), network.getId(), routerNic.getIp4Address(), router.getId(), router.getType().toString()); router.getDataCenterIdToDeployIn(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
if (stats == null) { if (stats == null) {
s_logger.warn("unable to find stats for account: " + router.getAccountId()); s_logger.warn("unable to find stats for account: " + router.getAccountId());
continue; continue;
} }
if(previousStats != null if (previousStats != null
&& ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived()) && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived())
|| (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))){ || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))) {
s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " + s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " +
"Ignoring current answer. Router: "+answer.getRouterName()+" Rcvd: " + "Ignoring current answer. Router: " + answer.getRouterName() + " Rcvd: " +
answer.getBytesReceived()+ "Sent: " +answer.getBytesSent()); answer.getBytesReceived() + "Sent: " + answer.getBytesSent());
continue; continue;
} }
if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) { if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Received # of bytes that's less than the last one. " + s_logger.debug("Received # of bytes that's less than the last one. " +
"Assuming something went wrong and persisting it. Router: " + "Assuming something went wrong and persisting it. Router: " +
answer.getRouterName()+" Reported: " + answer.getBytesReceived() answer.getRouterName() + " Reported: " + answer.getBytesReceived()
+ " Stored: " + stats.getCurrentBytesReceived()); + " Stored: " + stats.getCurrentBytesReceived());
} }
stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived()); stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
@ -876,8 +879,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
if (stats.getCurrentBytesSent() > answer.getBytesSent()) { if (stats.getCurrentBytesSent() > answer.getBytesSent()) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Received # of bytes that's less than the last one. " + s_logger.debug("Received # of bytes that's less than the last one. " +
"Assuming something went wrong and persisting it. Router: " + "Assuming something went wrong and persisting it. Router: " +
answer.getRouterName()+" Reported: " + answer.getBytesSent() answer.getRouterName() + " Reported: " + answer.getBytesSent()
+ " Stored: " + stats.getCurrentBytesSent()); + " Stored: " + stats.getCurrentBytesSent());
} }
stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent()); stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());

View File

@ -287,7 +287,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_identityDao.initializeDefaultUuid("user_ip_address"); _identityDao.initializeDefaultUuid("user_ip_address");
_identityDao.initializeDefaultUuid("counter"); _identityDao.initializeDefaultUuid("counter");
} }
*/ */
private String getMountParent() { private String getMountParent() {
return getEnvironmentProperty("mount.parent"); return getEnvironmentProperty("mount.parent");

View File

@ -16,22 +16,17 @@
// under the License. // under the License.
package com.cloud.servlet; package com.cloud.servlet;
import java.io.File;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import com.cloud.api.ApiServer; import com.cloud.api.ApiServer;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.server.ConfigurationServer; import com.cloud.server.ConfigurationServer;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.SerialVersionUID; import com.cloud.utils.SerialVersionUID;
import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentContext;
@ -42,17 +37,15 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi
@Override @Override
public void init() throws ServletException { public void init() throws ServletException {
initLog4j();
// Save Configuration Values // Save Configuration Values
ConfigurationServer c = ComponentContext.getComponent(ConfigurationServer.class); //ComponentLocator loc = ComponentLocator.getLocator(ConfigurationServer.Name);
ConfigurationServer c = (ConfigurationServer)ComponentContext.getComponent(ConfigurationServer.Name);
//ConfigurationServer c = new ConfigurationServerImpl();
try { try {
c.persistDefaultValues(); c.persistDefaultValues();
ManagementServer ms = (ManagementServer)ComponentContext.getComponent(ManagementServer.Name);
ManagementServer ms = ComponentContext.getComponent(ManagementServer.class);
ms.startup();
ms.enableAdminUser("password"); ms.enableAdminUser("password");
ApiServer.initApiServer(ms.getPropertiesFiles()); ApiServer.initApiServer();
} catch (InvalidParameterValueException ipve) { } catch (InvalidParameterValueException ipve) {
s_logger.error("Exception starting management server ", ipve); s_logger.error("Exception starting management server ", ipve);
throw new ServletException (ipve.getMessage()); throw new ServletException (ipve.getMessage());
@ -75,18 +68,4 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi
@Override @Override
public void contextDestroyed(ServletContextEvent sce) { public void contextDestroyed(ServletContextEvent sce) {
} }
private void initLog4j() {
File file = PropertiesUtil.findConfigFile("log4j-cloud.xml");
if (file != null) {
s_logger.info("log4j configuration found at " + file.getAbsolutePath());
DOMConfigurator.configureAndWatch(file.getAbsolutePath());
} else {
file = PropertiesUtil.findConfigFile("log4j-cloud.properties");
if (file != null) {
s_logger.info("log4j configuration found at " + file.getAbsolutePath());
PropertyConfigurator.configureAndWatch(file.getAbsolutePath());
}
}
}
} }

View File

@ -219,14 +219,14 @@ class TestISO(cloudstackTestCase):
# Finding the OsTypeId from Ostype # Finding the OsTypeId from Ostype
ostypes = list_os_types( ostypes = list_os_types(
cls.api_client, cls.api_client,
description=self.services["ostype"] description=cls.services["ostype"]
) )
if not isinstance(ostypes, list): if not isinstance(ostypes, list):
raise unittest.SkipTest("OSTypeId for given description not found") raise unittest.SkipTest("OSTypeId for given description not found")
self.services["iso_1"]["ostypeid"] = ostypes[0].id cls.services["iso_1"]["ostypeid"] = ostypes[0].id
self.services["iso_2"]["ostypeid"] = ostypes[0].id cls.services["iso_2"]["ostypeid"] = ostypes[0].id
self.services["ostypeid"] = ostypes[0].id cls.services["ostypeid"] = ostypes[0].id
cls.iso_1 = Iso.create( cls.iso_1 = Iso.create(
cls.api_client, cls.api_client,

View File

@ -0,0 +1,21 @@
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.
===========================================================
This directory hosts configs for setting up the devcloud-kvm
environment.

View File

@ -0,0 +1,97 @@
{
"zones": [
{
"name": "DevCloudKVM0",
"physical_networks": [
{
"broadcastdomainrange": "Zone",
"name": "test-network",
"traffictypes": [
{
"typ": "Guest"
},
{
"typ": "Management"
}
],
"providers": [
{
"broadcastdomainrange": "ZONE",
"name": "VirtualRouter"
},
{
"broadcastdomainrange": "Pod",
"name": "SecurityGroupProvider"
}
]
}
],
"dns2": "4.4.4.4",
"dns1": "8.8.8.8",
"securitygroupenabled": "true",
"localstorageenabled": "true",
"networktype": "Basic",
"pods": [
{
"endip": "192.168.100.250",
"name": "test00",
"startip": "192.168.100.200",
"guestIpRanges": [
{
"startip": "192.168.100.100",
"endip": "192.168.100.199",
"netmask": "255.255.255.0",
"gateway": "192.168.100.1"
}
],
"netmask": "255.255.255.0",
"clusters": [
{
"clustername": "test000",
"hypervisor": "KVM",
"hosts": [
{
"username": "root",
"url": "http://192.168.100.10/",
"password": "password"
}
],
"clustertype": "CloudManaged"
}
],
"gateway": "192.168.100.1"
}
],
"internaldns1": "192.168.100.10",
"secondaryStorages": [
{
"url": "nfs://192.168.100.10:/nfs/secondary"
}
]
}
],
"logger": [
{
"name": "TestClient",
"file": "/tmp/testclient.log"
},
{
"name": "TestCase",
"file": "/tmp/testcase.log"
}
],
"mgtSvr": [
{
"mgtSvrIp": "127.0.0.1",
"port": 8096
}
],
"dbSvr":
{
"dbSvr": "127.0.0.1",
"port": 3306,
"user": "cloud",
"passwd": "cloud",
"db": "cloud"
}
}

View File

@ -0,0 +1,40 @@
-- 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.
INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, use_local_storage, type, disk_size) VALUES (17, 'tinyOffering', UUID(), 'tinyOffering', NOW(), 1, 'Service', 0);
INSERT INTO `cloud`.`service_offering` (id, cpu, speed, ram_size) VALUES (17, 1, 100, 100);
INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, type, disk_size) VALUES (18, 'tinyDiskOffering', UUID(), 'tinyDiskOffering', NOW(), 'Disk', 1073741824);
INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','router.ram.size', '100');
INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','router.cpu.mhz','100');
INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','console.ram.size','100');
INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','console.cpu.mhz', '100');
INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','ssvm.ram.size','100');
INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','ssvm.cpu.mhz','100');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'system.vm.use.local.storage', 'true');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.workers', '3');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.delay', '60');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.interval', '60');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'enable.ec2.api', 'true');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'enable.s3.api', 'true');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'host', '192.168.100.10');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'management.network.cidr', '192.168.100.0/24');
INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'secstorage.allowed.internal.sites', '192.168.0.0/8');
UPDATE `cloud`.`configuration` SET value='10' where name = 'storage.overprovisioning.factor';
UPDATE `cloud`.`configuration` SET value='10' where name = 'cpu.overprovisioning.factor';
UPDATE `cloud`.`configuration` SET value='10' where name = 'mem.overprovisioning.factor';
UPDATE `cloud`.`vm_template` SET unique_name="tiny Linux",name="tiny Linux",url="https://dl.dropbox.com/u/678991/cloudstack-extras/ttylinux_pv.qcow2",checksum="81dcf4b4ca05a3b637a040e851568f29",display_text="tiny Linux",format='QCOW2',hypervisor_type='KVM' where id=5;

138
tools/devcloud-kvm/pom.xml Normal file
View File

@ -0,0 +1,138 @@
<!-- 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. -->
<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-devcloud-kvm</artifactId>
<name>Apache CloudStack Developer Tools</name>
<packaging>pom</packaging>
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
</build>
<profiles>
<profile>
<id>deploydb</id>
<activation>
<property>
<name>deploydb</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${project.parent.basedir}/utils/conf/db.properties</file>
<file>${project.parent.basedir}/utils/conf/db.properties.override</file>
</files>
<quiet>true</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<!-- specify the dependent jdbc driver here -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${cs.mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<driver>org.gjt.mm.mysql.Driver</driver>
<url>jdbc:mysql://${db.cloud.host}:${db.cloud.port}/cloud</url>
<username>${db.cloud.username}</username>
<password>${db.cloud.password}</password>
<!--all executions are ignored if -Dmaven.test.skip=true -->
<skip>${maven.test.skip}</skip>
<forceMojoExecution>true</forceMojoExecution>
</configuration>
<executions>
<execution>
<id>create-schema</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<srcFiles>
<srcFile>${basedir}/devcloud-kvm.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>deploysvr</id>
<activation>
<property>
<name>deploysvr</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>python</executable>
<arguments>
<argument>../marvin/marvin/deployDataCenter.py</argument>
<argument>-i</argument>
<argument>devcloud-kvm.cfg</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,60 +0,0 @@
// 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
// 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.utils;
public class IdentityProxy {
private String _tableName;
private Long _value;
private String _idFieldName;
public IdentityProxy() {
}
public IdentityProxy(String tableName) {
_tableName = tableName;
}
public IdentityProxy(String tableName, Long id, String fieldName) {
_tableName = tableName;
_value = id;
_idFieldName = fieldName;
}
public String getTableName() {
return _tableName;
}
public void setTableName(String tableName) {
_tableName = tableName;
}
public Long getValue() {
return _value;
}
public void setValue(Long value) {
_value = value;
}
public void setidFieldName(String value) {
_idFieldName = value;
}
public String getidFieldName() {
return _idFieldName;
}
}

View File

@ -17,7 +17,6 @@
package com.cloud.utils.exception; package com.cloud.utils.exception;
import com.cloud.utils.AnnotationHelper; import com.cloud.utils.AnnotationHelper;
import com.cloud.utils.IdentityProxy;
import java.util.ArrayList; import java.util.ArrayList;
/** /**

View File

@ -840,11 +840,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary();
HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor); HostHardwareSummary hardwareSummary = getHostHardwareSummary();
HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware();
// TODO: not sure how hyper-thread is counted in VMware resource pool // TODO: not sure how hyper-thread is counted in VMware resource pool
summary.setCpuCount(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); summary.setCpuCount(hardwareSummary.getNumCpuCores());
summary.setMemoryBytes(hardwareSummary.getMemorySize()); summary.setMemoryBytes(hardwareSummary.getMemorySize());
summary.setCpuSpeed(hardwareSummary.getCpuMhz()); summary.setCpuSpeed(hardwareSummary.getCpuMhz());
@ -922,14 +920,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ComputeResourceSummary resourceSummary = new ComputeResourceSummary(); ComputeResourceSummary resourceSummary = new ComputeResourceSummary();
// TODO: not sure how hyper-threading is counted in VMware // TODO: not sure how hyper-threading is counted in VMware
short totalCores = (short)(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); resourceSummary.setNumCpuCores(hardwareSummary.getNumCpuCores());
resourceSummary.setNumCpuCores(totalCores);
// Note: memory here is in Byte unit // Note: memory here is in Byte unit
resourceSummary.setTotalMemory(hardwareSummary.getMemorySize()); resourceSummary.setTotalMemory(hardwareSummary.getMemorySize());
// Total CPU is based on socket x core x Mhz // Total CPU is based on (# of cores) x Mhz
int totalCpu = hardwareSummary.getCpuMhz() * totalCores; int totalCpu = hardwareSummary.getCpuMhz() * hardwareSummary.getNumCpuCores();
resourceSummary.setTotalCpu(totalCpu); resourceSummary.setTotalCpu(totalCpu);
HostListSummaryQuickStats stats = getHostQuickStats(); HostListSummaryQuickStats stats = getHostQuickStats();