Added Mock ApiServer, Regions API calls with api keys

This commit is contained in:
Kishan Kavala 2012-10-17 14:16:36 +05:30
parent 89779cceb8
commit f0f33bf4da
70 changed files with 3814 additions and 561 deletions

View File

@ -34,6 +34,9 @@ import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.DomainRouterResponse; import com.cloud.api.response.DomainRouterResponse;
import com.cloud.api.response.EventResponse; import com.cloud.api.response.EventResponse;
import com.cloud.api.response.ExtractResponse; import com.cloud.api.response.ExtractResponse;
import com.cloud.api.response.FindAccountResponse;
import com.cloud.api.response.FindDomainResponse;
import com.cloud.api.response.FindUserResponse;
import com.cloud.api.response.FirewallResponse; import com.cloud.api.response.FirewallResponse;
import com.cloud.api.response.FirewallRuleResponse; import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.HostResponse; import com.cloud.api.response.HostResponse;
@ -344,4 +347,10 @@ public interface ResponseGenerator {
Site2SiteCustomerGatewayResponse createSite2SiteCustomerGatewayResponse(Site2SiteCustomerGateway result); Site2SiteCustomerGatewayResponse createSite2SiteCustomerGatewayResponse(Site2SiteCustomerGateway result);
Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result); Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result);
FindUserResponse createFindUserResponse(User user);
FindAccountResponse createFindAccountResponse(Account account);
FindDomainResponse createFindDomainResponse(Domain domain);
} }

View File

@ -36,8 +36,8 @@ public class AddRegionCmd extends BaseCmd {
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Region") @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="Id of the Region")
private Long id; private Integer id;
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="adds Region with this name") @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="adds Region with this name")
private String regionName; private String regionName;
@ -45,11 +45,17 @@ public class AddRegionCmd extends BaseCmd {
@Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, required=true, description="end_point of the Region") @Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, required=true, description="end_point of the Region")
private String endPoint; private String endPoint;
@Parameter(name=ApiConstants.API_KEY, type=CommandType.STRING, description="API key")
private String apiKey;
@Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="Secret Key")
private String secretKey;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public Long getId() { public Integer getId() {
return id; return id;
} }
@ -61,6 +67,14 @@ public class AddRegionCmd extends BaseCmd {
return endPoint; return endPoint;
} }
public String getApiKey() {
return apiKey;
}
public String getSecretKey() {
return secretKey;
}
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////// API Implementation/////////////////// /////////////// API Implementation///////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@ -77,7 +91,7 @@ public class AddRegionCmd extends BaseCmd {
@Override @Override
public void execute(){ public void execute(){
Region region = _regionService.addRegion(getId(), getRegionName(), getEndPoint()); Region region = _regionService.addRegion(getId(), getRegionName(), getEndPoint(), getApiKey(), getSecretKey());
if (region != null) { if (region != null) {
RegionResponse response = _responseGenerator.createRegionResponse(region); RegionResponse response = _responseGenerator.createRegionResponse(region);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());

View File

@ -86,8 +86,8 @@ public class CreateAccountCmd extends BaseCmd {
@Parameter(name=ApiConstants.USER_ID, type=CommandType.STRING, description="User UUID, required for adding account from another Region") @Parameter(name=ApiConstants.USER_ID, type=CommandType.STRING, description="User UUID, required for adding account from another Region")
private String userUUID; private String userUUID;
@Parameter(name=ApiConstants.REGION_ID, type=CommandType.LONG, description="Id of the Region creating the account") @Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, description="Id of the Region creating the account")
private Long regionId; private Integer regionId;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@ -152,7 +152,7 @@ public class CreateAccountCmd extends BaseCmd {
return userUUID; return userUUID;
} }
public Long getRegionId() { public Integer getRegionId() {
return regionId; return regionId;
} }

View File

@ -53,8 +53,8 @@ public class CreateDomainCmd extends BaseCmd {
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.STRING, description="Domain UUID, required for adding domain from another Region") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.STRING, description="Domain UUID, required for adding domain from another Region")
private String domainUUID; private String domainUUID;
@Parameter(name=ApiConstants.REGION_ID, type=CommandType.LONG, description="Id of the Region creating the Domain") @Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, description="Id of the Region creating the Domain")
private Long regionId; private Integer regionId;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
@ -76,7 +76,7 @@ public class CreateDomainCmd extends BaseCmd {
return domainUUID; return domainUUID;
} }
public Long getRegionId() { public Integer getRegionId() {
return regionId; return regionId;
} }

View File

@ -68,8 +68,8 @@ public class CreateUserCmd extends BaseCmd {
@Parameter(name=ApiConstants.USER_ID, type=CommandType.STRING, description="User UUID, required for adding account from another Region") @Parameter(name=ApiConstants.USER_ID, type=CommandType.STRING, description="User UUID, required for adding account from another Region")
private String userUUID; private String userUUID;
@Parameter(name=ApiConstants.REGION_ID, type=CommandType.LONG, description="Id of the Region creating the User") @Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, description="Id of the Region creating the User")
private Long regionId; private Integer regionId;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
@ -111,7 +111,7 @@ public class CreateUserCmd extends BaseCmd {
return userUUID; return userUUID;
} }
public Long getRegionId() { public Integer getRegionId() {
return regionId; return regionId;
} }

View File

@ -0,0 +1,77 @@
// 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.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.FindAccountResponse;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.Account;
@Implementation(description="Find account by ID", responseObject=FindAccountResponse.class)
public class FindAccountCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(FindAccountCmd.class.getName());
private static final String s_name = "findaccountresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="account")
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, required=true, description = "Id of the account")
private Long id;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return 0;
}
@Override
public void execute(){
Account result = _accountService.findAccount(getId());
if(result != null){
FindAccountResponse response = _responseGenerator.createFindAccountResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new InvalidParameterValueException("Account with specified Id does not exist");
}
}
}

View File

@ -0,0 +1,90 @@
// 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.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.FindDomainResponse;
import com.cloud.domain.Domain;
import com.cloud.exception.InvalidParameterValueException;
@Implementation(description="Find account by ID", responseObject=FindDomainResponse.class)
public class FindDomainCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(FindDomainCmd.class.getName());
private static final String s_name = "finddomainresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="domain")
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "Id of the domain")
private Long id;
@Parameter(name = ApiConstants.DOMAIN, type = CommandType.STRING, description = "Path of the domain")
private String domain;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getId() {
return id;
}
public String getDomain() {
return domain;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return 0;
}
@Override
public void execute(){
Domain result = null;
if(getId() != null){
result = _domainService.getDomain(getId());
} else if (getDomain() != null){
result = _domainService.findDomainByPath(getDomain());
}
if(result != null){
FindDomainResponse response = _responseGenerator.createFindDomainResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new InvalidParameterValueException("Domain with specified Id does not exist");
}
}
}

View File

@ -0,0 +1,84 @@
// 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.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.FindUserResponse;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.User;
@Implementation(description="Find user by name and domain", responseObject=FindUserResponse.class)
public class FindUserCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(FindUserCmd.class.getName());
private static final String s_name = "finduserresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="find user with specified username")
private String username;
@IdentityMapper(entityTableName="domain")
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, required=true, description = "Domain the user belongs to")
private Long domainId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getUserName() {
return username;
}
public Long getDomainId() {
return domainId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return 0;
}
@Override
public void execute(){
User result = _accountService.findUser(getUserName(), getDomainId());
if(result != null){
FindUserResponse response = _responseGenerator.createFindUserResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new InvalidParameterValueException("User with specified name and domainId does not exist");
}
}
}

View File

@ -25,14 +25,13 @@ import com.cloud.api.ApiConstants;
import com.cloud.api.BaseListCmd; import com.cloud.api.BaseListCmd;
import com.cloud.api.Implementation; import com.cloud.api.Implementation;
import com.cloud.api.Parameter; import com.cloud.api.Parameter;
import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.ListResponse; import com.cloud.api.response.ListResponse;
import com.cloud.api.response.RegionResponse; import com.cloud.api.response.RegionResponse;
import com.cloud.region.Region; import com.cloud.region.Region;
@Implementation(description="Lists Regions", responseObject=DomainResponse.class) @Implementation(description="Lists Regions", responseObject=RegionResponse.class)
public class ListRegionsCmd extends BaseListCmd { public class ListRegionsCmd extends BaseListCmd {
public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(ListRegionsCmd.class.getName());
private static final String s_name = "listregionsresponse"; private static final String s_name = "listregionsresponse";
@ -40,17 +39,17 @@ public class ListRegionsCmd extends BaseListCmd {
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List domain by domain ID.") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List Region by region ID.")
private Long id; private Integer id;
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List domain by domain name.") @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List Region by region name.")
private String domainName; private String domainName;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public Long getId() { public Integer getId() {
return id; return id;
} }

View File

@ -19,17 +19,12 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants; import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd; import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation; import com.cloud.api.Implementation;
import com.cloud.api.Parameter; import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException; import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse; import com.cloud.api.response.SuccessResponse;
import com.cloud.domain.Domain;
import com.cloud.event.EventTypes;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.UserContext;
@Implementation(description="Removes specified region", responseObject=SuccessResponse.class) @Implementation(description="Removes specified region", responseObject=SuccessResponse.class)
public class RemoveRegionCmd extends BaseCmd { public class RemoveRegionCmd extends BaseCmd {
@ -40,14 +35,14 @@ public class RemoveRegionCmd extends BaseCmd {
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the region to delete") @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="ID of the region to delete")
private Long id; private Integer id;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public Long getId() { public Integer getId() {
return id; return id;
} }

View File

@ -93,7 +93,7 @@ public class UpdateDomainCmd extends BaseCmd {
boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false;
Domain domain = null; Domain domain = null;
if(isPopagate){ if(isPopagate){
domain = _mgr.updateDomain(this); domain = _domainService.updateDomain(this);
} else { } else {
domain = _regionService.updateDomain(this); domain = _regionService.updateDomain(this);
} }

View File

@ -20,18 +20,14 @@ import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants; import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd; import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation; import com.cloud.api.Implementation;
import com.cloud.api.Parameter; import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException; import com.cloud.api.ServerApiException;
import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.RegionResponse; import com.cloud.api.response.RegionResponse;
import com.cloud.domain.Domain;
import com.cloud.region.Region; import com.cloud.region.Region;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.UserContext;
@Implementation(description="Updates a region", responseObject=DomainResponse.class) @Implementation(description="Updates a region", responseObject=RegionResponse.class)
public class UpdateRegionCmd extends BaseCmd { public class UpdateRegionCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdateRegionCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(UpdateRegionCmd.class.getName());
private static final String s_name = "updateregionresponse"; private static final String s_name = "updateregionresponse";
@ -40,8 +36,8 @@ public class UpdateRegionCmd extends BaseCmd {
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of region to update") @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="ID of region to update")
private Long id; private Integer id;
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates region with this name") @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates region with this name")
private String regionName; private String regionName;
@ -49,11 +45,17 @@ public class UpdateRegionCmd extends BaseCmd {
@Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, description="updates region with this end point") @Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, description="updates region with this end point")
private String endPoint; private String endPoint;
@Parameter(name=ApiConstants.API_KEY, type=CommandType.STRING, description="API key")
private String apiKey;
@Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="Secret Key")
private String secretKey;
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// /////////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
public Long getId() { public Integer getId() {
return id; return id;
} }
@ -65,6 +67,13 @@ public class UpdateRegionCmd extends BaseCmd {
return endPoint; return endPoint;
} }
public String getApiKey() {
return apiKey;
}
public String getSecretKey() {
return secretKey;
}
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/////////////// API Implementation/////////////////// /////////////// API Implementation///////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@ -81,7 +90,7 @@ public class UpdateRegionCmd extends BaseCmd {
@Override @Override
public void execute(){ public void execute(){
Region region = _regionService.updateRegion(getId(), getRegionName(), getEndPoint()); Region region = _regionService.updateRegion(getId(), getRegionName(), getEndPoint(), getApiKey(), getSecretKey());
if (region != null) { if (region != null) {
RegionResponse response = _responseGenerator.createRegionResponse(region); RegionResponse response = _responseGenerator.createRegionResponse(region);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());

View File

@ -0,0 +1,95 @@
// 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.response;
import java.util.List;
import java.util.Map;
import com.cloud.api.ApiConstants;
import com.cloud.serializer.Param;
import com.cloud.utils.IdentityProxy;
import com.google.gson.annotations.SerializedName;
@SuppressWarnings("unused")
public class FindAccountResponse extends BaseResponse {
@SerializedName(ApiConstants.ID) @Param(description="the id of the account")
private IdentityProxy id = new IdentityProxy("account");
@SerializedName(ApiConstants.NAME) @Param(description="the name of the account")
private String name;
@SerializedName(ApiConstants.ACCOUNT_TYPE) @Param(description="account type (admin, domain-admin, user)")
private Short accountType;
@SerializedName(ApiConstants.DOMAIN_ID) @Param(description="id of the Domain the account belongs too")
private IdentityProxy domainId = new IdentityProxy("domain");
@SerializedName(ApiConstants.DEFAULT_ZONE_ID) @Param(description="the default zone of the account")
private IdentityProxy defaultZoneId = new IdentityProxy("data_center");
@SerializedName(ApiConstants.STATE) @Param(description="the state of the account")
private String state;
@SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain")
private String networkDomain;
@SerializedName(ApiConstants.ACCOUNT_DETAILS) @Param(description="details for the account")
private Map<String, String> details;
@SerializedName("regionId") @Param(description="source region id of the user")
private int regionId;
public void setId(Long id) {
this.id.setValue(id);
}
public void setName(String name) {
this.name = name;
}
public void setAccountType(Short accountType) {
this.accountType = accountType;
}
public void setDomainId(Long domainId) {
this.domainId.setValue(domainId);
}
public void setState(String state) {
this.state = state;
}
public void setNetworkDomain(String networkDomain) {
this.networkDomain = networkDomain;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
public void setDefaultZone(Long defaultZoneId) {
this.defaultZoneId.setValue(defaultZoneId);
}
public int getRegionId() {
return regionId;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
}

View File

@ -0,0 +1,111 @@
// 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.response;
import com.cloud.api.ApiConstants;
import com.cloud.utils.IdentityProxy;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class FindDomainResponse extends BaseResponse {
@SerializedName(ApiConstants.ID) @Param(description="the ID of the domain")
private IdentityProxy id = new IdentityProxy("domain");
@SerializedName(ApiConstants.NAME) @Param(description="the name of the domain")
private String domainName;
@SerializedName(ApiConstants.LEVEL) @Param(description="the level of the domain")
private Integer level;
@SerializedName("parentdomainid") @Param(description="the domain ID of the parent domain")
private IdentityProxy parent = new IdentityProxy("domain");
@SerializedName("haschild") @Param(description="whether the domain has one or more sub-domains")
private boolean hasChild;
@SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain")
private String networkDomain;
@SerializedName(ApiConstants.PATH) @Param(description="the path of the domain")
private String path;
@SerializedName(ApiConstants.STATE) @Param(description="the state of the domain")
private String state;
@SerializedName("regionId") @Param(description="source region id of the user")
private int regionId;
public Long getId() {
return id.getValue();
}
public void setId(Long id) {
this.id.setValue(id);
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Long getParent() {
return parent.getValue();
}
public void setParent(Long parent) {
this.parent.setValue(parent);
}
public boolean getHasChild() {
return hasChild;
}
public void setHasChild(boolean hasChild) {
this.hasChild = hasChild;
}
public void setNetworkDomain(String networkDomain) {
this.networkDomain = networkDomain;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getRegionId() {
return regionId;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
}

View File

@ -0,0 +1,189 @@
// 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.response;
import java.util.Date;
import com.cloud.serializer.Param;
import com.cloud.utils.IdentityProxy;
import com.google.gson.annotations.SerializedName;
public class FindUserResponse extends BaseResponse {
@SerializedName("id") @Param(description="the user ID")
private IdentityProxy id = new IdentityProxy("user");
@SerializedName("username") @Param(description="the user name")
private String username;
@SerializedName("password") @Param(description="the password of the user")
private String password;
@SerializedName("firstname") @Param(description="the user firstname")
private String firstname;
@SerializedName("lastname") @Param(description="the user lastname")
private String lastname;
@SerializedName("accountId") @Param(description="the account ID of the user")
private IdentityProxy accountId = new IdentityProxy("account");
@SerializedName("email") @Param(description="the user email address")
private String email;
@SerializedName("state") @Param(description="the user state")
private String state;
@SerializedName("apikey") @Param(description="the api key of the user")
private String apiKey;
@SerializedName("secretkey") @Param(description="the secret key of the user")
private String secretKey;
@SerializedName("created") @Param(description="the date and time the user account was created")
private Date created;
@SerializedName("timezone") @Param(description="the timezone user was created in")
private String timezone;
@SerializedName("registrationtoken") @Param(description="the registration token")
private String registrationToken;
@SerializedName("registered") @Param(description="registration flag")
boolean registered;
@SerializedName("regionId") @Param(description="source region id of the user")
private int regionId;
public Long getId() {
return id.getValue();
}
public void setId(Long id) {
this.id.setValue(id);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public Long getAccountId() {
return accountId.getValue();
}
public void setAccountId(Long accountId) {
this.accountId.setValue(accountId);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRegistrationToken() {
return registrationToken;
}
public void setRegistrationToken(String registrationToken) {
this.registrationToken = registrationToken;
}
public boolean isRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
public int getRegionId() {
return regionId;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
}

View File

@ -22,7 +22,7 @@ import com.google.gson.annotations.SerializedName;
public class RegionResponse extends BaseResponse { public class RegionResponse extends BaseResponse {
@SerializedName(ApiConstants.ID) @Param(description="the ID of the region") @SerializedName(ApiConstants.ID) @Param(description="the ID of the region")
private Long id; private Integer id;
@SerializedName(ApiConstants.NAME) @Param(description="the name of the region") @SerializedName(ApiConstants.NAME) @Param(description="the name of the region")
private String name; private String name;
@ -30,11 +30,11 @@ public class RegionResponse extends BaseResponse {
@SerializedName(ApiConstants.END_POINT) @Param(description="the end point of the region") @SerializedName(ApiConstants.END_POINT) @Param(description="the end point of the region")
private String endPoint; private String endPoint;
public Long getId() { public Integer getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }

View File

@ -59,4 +59,6 @@ public interface Domain extends OwnedBy {
String getNetworkDomain(); String getNetworkDomain();
public String getUuid(); public String getUuid();
int getRegionId();
} }

View File

@ -22,19 +22,18 @@ import java.util.Date;
* *
*/ */
public interface Region { public interface Region {
public static enum State {
Up, Down
};
public long getId(); public int getId();
public String getName(); public String getName();
public void setName(String name); public void setName(String name);
public Region.State getStatus();
public Date getRemoved(); public Date getRemoved();
public String getEndPoint(); public String getEndPoint();
public String getApiKey();
public String getSecretKey();
} }

View File

@ -31,9 +31,9 @@ import com.cloud.user.UserAccount;
public interface RegionService { public interface RegionService {
public Region addRegion(long id, String name, String endPoint); public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey);
public Region updateRegion(long id, String name, String endPoint); public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey);
public boolean removeRegion(long id); public boolean removeRegion(int id);
public List<? extends Region> listRegions(ListRegionsCmd cmd); public List<? extends Region> listRegions(ListRegionsCmd cmd);
boolean deleteUserAccount(long accountId); boolean deleteUserAccount(long accountId);
Account updateAccount(UpdateAccountCmd cmd); Account updateAccount(UpdateAccountCmd cmd);

View File

@ -220,15 +220,6 @@ public interface ManagementService {
VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd); VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd);
/**
* update an existing domain
*
* @param cmd
* - the command containing domainId and new domainName
* @return Domain object if the command succeeded
*/
Domain updateDomain(UpdateDomainCmd cmd);
/** /**
* Searches for alerts * Searches for alerts
* *

View File

@ -62,7 +62,7 @@ public interface Account extends ControlledEntity {
public Long getDefaultZoneId(); public Long getDefaultZoneId();
public long getRegionId(); public int getRegionId();
public String getUuid(); public String getUuid();
} }

View File

@ -62,7 +62,7 @@ public interface AccountService {
* @return the user if created successfully, null otherwise * @return the user if created successfully, null otherwise
*/ */
UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain,
Map<String, String> details, String accountUUID, String userUUID, Long regionId); Map<String, String> details, String accountUUID, String userUUID, Integer regionId);
/** /**
* Deletes a user by userId * Deletes a user by userId
@ -163,7 +163,7 @@ public interface AccountService {
User getSystemUser(); User getSystemUser();
User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Long regionId); User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Integer regionId);
boolean deleteUser(DeleteUserCmd deleteUserCmd); boolean deleteUser(DeleteUserCmd deleteUserCmd);
@ -202,4 +202,7 @@ public interface AccountService {
void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException; void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException;
User findUser(String username, Long domainId);
Account findAccount(Long id);
} }

View File

@ -20,12 +20,13 @@ import java.util.List;
import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainChildrenCmd;
import com.cloud.api.commands.ListDomainsCmd; import com.cloud.api.commands.ListDomainsCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.domain.Domain; import com.cloud.domain.Domain;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
public interface DomainService { public interface DomainService {
Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID, Long regionId); Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID, Integer regionId);
Domain getDomain(long id); Domain getDomain(long id);
@ -44,5 +45,22 @@ public interface DomainService {
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd) List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
throws PermissionDeniedException; throws PermissionDeniedException;
/**
* update an existing domain
*
* @param cmd
* - the command containing domainId and new domainName
* @return Domain object if the command succeeded
*/
Domain updateDomain(UpdateDomainCmd cmd);
/**
* find the domain by its path
*
* @param domainPath
* the path to use to lookup a domain
* @return domainVO the domain with the matching path, or null if no domain with the given path exists
*/
Domain findDomainByPath(String domainPath);
} }

View File

@ -69,4 +69,5 @@ public interface User extends OwnedBy {
boolean isRegistered(); boolean isRegistered();
public int getRegionId();
} }

View File

@ -27,6 +27,7 @@ enableAccount=com.cloud.api.commands.EnableAccountCmd;7
###lockAccount=com.cloud.api.commands.LockAccountCmd;7 ###lockAccount=com.cloud.api.commands.LockAccountCmd;7
listAccounts=com.cloud.api.commands.ListAccountsCmd;15 listAccounts=com.cloud.api.commands.ListAccountsCmd;15
markDefaultZoneForAccount=com.cloud.api.commands.MarkDefaultZoneForAccountCmd;1 markDefaultZoneForAccount=com.cloud.api.commands.MarkDefaultZoneForAccountCmd;1
findAccount=com.cloud.api.commands.FindAccountCmd;1
#### User commands #### User commands
createUser=com.cloud.api.commands.CreateUserCmd;3 createUser=com.cloud.api.commands.CreateUserCmd;3
@ -37,6 +38,7 @@ listUsers=com.cloud.api.commands.ListUsersCmd;7
disableUser=com.cloud.api.commands.DisableUserCmd;7 disableUser=com.cloud.api.commands.DisableUserCmd;7
enableUser=com.cloud.api.commands.EnableUserCmd;7 enableUser=com.cloud.api.commands.EnableUserCmd;7
getUser=com.cloud.api.commands.GetUserCmd;1 getUser=com.cloud.api.commands.GetUserCmd;1
findUser=com.cloud.api.commands.FindUserCmd;1
#### Domain commands #### Domain commands
createDomain=com.cloud.api.commands.CreateDomainCmd;1 createDomain=com.cloud.api.commands.CreateDomainCmd;1
@ -44,6 +46,7 @@ updateDomain=com.cloud.api.commands.UpdateDomainCmd;1
deleteDomain=com.cloud.api.commands.DeleteDomainCmd;1 deleteDomain=com.cloud.api.commands.DeleteDomainCmd;1
listDomains=com.cloud.api.commands.ListDomainsCmd;7 listDomains=com.cloud.api.commands.ListDomainsCmd;7
listDomainChildren=com.cloud.api.commands.ListDomainChildrenCmd;7 listDomainChildren=com.cloud.api.commands.ListDomainChildrenCmd;7
findDomain=com.cloud.api.commands.FindDomainCmd;1
####Cloud Identifier commands ####Cloud Identifier commands
getCloudIdentifier=com.cloud.api.commands.GetCloudIdentifierCmd;15 getCloudIdentifier=com.cloud.api.commands.GetCloudIdentifierCmd;15

View File

@ -0,0 +1,52 @@
<?xml version="1.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.
-->
<!--
components.xml is the configuration file for the VM Ops
insertion servers. Someone can quickly pull together an
insertion server by selecting the correct adapters to use.
Here are some places to look for information.
- To find out the general functionality that each Manager
or Adapter provide, look at the javadoc for the interface
that it implements. The interface is usually the
"key" attribute in the declaration.
- To find specific implementation of each Manager or
Adapter, look at the javadoc for the actual class. The
class can be found in the <class> element.
- To find out the configuration parameters for each Manager
or Adapter, look at the javadoc for the actual implementation
class. It should be documented in the description of the
class.
- To know more about the components.xml in general, look for
the javadoc for ComponentLocator.java.
If you found that the Manager or Adapter are not properly
documented, please contact the author.
-->
<components.xml>
<management-server class="com.cloud.server.MockManagementServerImpl" library="com.cloud.configuration.RegionsComponentLibrary">
<dao name="Configuration configuration server" class="com.cloud.vpc.dao.MockConfigurationDaoImpl">
<param name="premium">true</param>
</dao>
<adapters key="com.cloud.acl.SecurityChecker">
<adapter name="DomainChecker" class="com.cloud.acl.DomainChecker"/>
</adapters>
</management-server>
</components.xml>

View File

@ -206,6 +206,7 @@ under the License.
<dao name="Site2SiteCustomerGatewayDao" class="com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl" singleton="false"/> <dao name="Site2SiteCustomerGatewayDao" class="com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl" singleton="false"/>
<dao name="Site2SiteVpnGatewayDao" class="com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl" singleton="false"/> <dao name="Site2SiteVpnGatewayDao" class="com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl" singleton="false"/>
<dao name="Site2SiteVpnConnectionDao" class="com.cloud.network.dao.Site2SiteVpnConnectionDaoImpl" singleton="false"/> <dao name="Site2SiteVpnConnectionDao" class="com.cloud.network.dao.Site2SiteVpnConnectionDaoImpl" singleton="false"/>
<dao name="RegionDao" class="com.cloud.region.dao.RegionDaoImpl" singleton="false"/>
</configuration-server> </configuration-server>
<awsapi-ec2server class="com.cloud.bridge.service.EC2MainServlet"> <awsapi-ec2server class="com.cloud.bridge.service.EC2MainServlet">

View File

@ -19,6 +19,7 @@
# in which the management server(Tomcat) is running # in which the management server(Tomcat) is running
cluster.node.IP=127.0.0.1 cluster.node.IP=127.0.0.1
cluster.servlet.port=9090 cluster.servlet.port=9090
region.id=1
# CloudStack database settings # CloudStack database settings
db.cloud.username=@DBUSER@ db.cloud.username=@DBUSER@

View File

@ -19,4 +19,4 @@
paths.script=@COMMONLIBDIR@ paths.script=@COMMONLIBDIR@
mount.parent=@MSMNTDIR@ mount.parent=@MSMNTDIR@
cloud-stack-components-specification=@COMPONENTS-SPEC@ cloud-stack-components-specification=components.xml

View File

@ -68,7 +68,7 @@ public class AccountVO implements Account, Identity {
private Long defaultZoneId = null; private Long defaultZoneId = null;
@Column(name="region_id") @Column(name="region_id")
private long regionId; private int regionId;
public AccountVO() { public AccountVO() {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
@ -79,7 +79,7 @@ public class AccountVO implements Account, Identity {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
} }
public AccountVO(String accountName, long domainId, String networkDomain, short type, String uuid, long regionId) { public AccountVO(String accountName, long domainId, String networkDomain, short type, String uuid, int regionId) {
this.accountName = accountName; this.accountName = accountName;
this.domainId = domainId; this.domainId = domainId;
this.networkDomain = networkDomain; this.networkDomain = networkDomain;
@ -102,7 +102,11 @@ public class AccountVO implements Account, Identity {
return id; return id;
} }
@Override public void setId(long id) {
this.id = id;
}
@Override
public String getAccountName() { public String getAccountName() {
return accountName; return accountName;
} }
@ -180,11 +184,11 @@ public class AccountVO implements Account, Identity {
this.uuid = uuid; this.uuid = uuid;
} }
public long getRegionId() { public int getRegionId() {
return regionId; return regionId;
} }
public void setRegionId(long regionId) { public void setRegionId(int regionId) {
this.regionId = regionId; this.regionId = regionId;
} }
} }

View File

@ -93,7 +93,7 @@ public class UserVO implements User, Identity {
private String uuid; private String uuid;
@Column(name="region_id") @Column(name="region_id")
private long regionId; private int regionId;
public UserVO() { public UserVO() {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
@ -104,7 +104,7 @@ public class UserVO implements User, Identity {
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
} }
public UserVO(long accountId, String username, String password, String firstName, String lastName, String email, String timezone, String uuid, long regionId) { public UserVO(long accountId, String username, String password, String firstName, String lastName, String email, String timezone, String uuid, int regionId) {
this.accountId = accountId; this.accountId = accountId;
this.username = username; this.username = username;
this.password = password; this.password = password;
@ -265,11 +265,11 @@ public class UserVO implements User, Identity {
this.uuid = uuid; this.uuid = uuid;
} }
public long getRegionId() { public int getRegionId() {
return regionId; return regionId;
} }
public void setRegionId(long regionId) { public void setRegionId(int regionId) {
this.regionId = regionId; this.regionId = regionId;
} }
} }

View File

@ -22,10 +22,12 @@ import javax.naming.ConfigurationException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.region.RegionManager;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserAccountDao;
import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
/** /**
* Simple UserAuthenticator that performs a MD5 hash of the password before * Simple UserAuthenticator that performs a MD5 hash of the password before
@ -36,14 +38,14 @@ import com.cloud.utils.component.ComponentLocator;
public class MD5UserAuthenticator extends DefaultUserAuthenticator { public class MD5UserAuthenticator extends DefaultUserAuthenticator {
public static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class); public static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class);
private UserAccountDao _userAccountDao; private RegionManager _regionMgr;
@Override @Override
public boolean authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters ) { public boolean authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters ) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Retrieving user: " + username); s_logger.debug("Retrieving user: " + username);
} }
UserAccount user = _userAccountDao.getUserAccount(username, domainId); UserAccount user = _regionMgr.getUserAccount(username, domainId);
if (user == null) { if (user == null) {
s_logger.debug("Unable to find user with " + username + " in domain " + domainId); s_logger.debug("Unable to find user with " + username + " in domain " + domainId);
return false; return false;
@ -84,7 +86,7 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator {
throws ConfigurationException { throws ConfigurationException {
super.configure(name, params); super.configure(name, params);
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
_userAccountDao = locator.getDao(UserAccountDao.class); _regionMgr = locator.getManager(RegionManager.class);
return true; return true;
} }
} }

View File

@ -50,6 +50,9 @@ import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.DomainRouterResponse; import com.cloud.api.response.DomainRouterResponse;
import com.cloud.api.response.EventResponse; import com.cloud.api.response.EventResponse;
import com.cloud.api.response.ExtractResponse; import com.cloud.api.response.ExtractResponse;
import com.cloud.api.response.FindAccountResponse;
import com.cloud.api.response.FindDomainResponse;
import com.cloud.api.response.FindUserResponse;
import com.cloud.api.response.FirewallResponse; import com.cloud.api.response.FirewallResponse;
import com.cloud.api.response.FirewallRuleResponse; import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.HostResponse; import com.cloud.api.response.HostResponse;
@ -200,6 +203,7 @@ import com.cloud.storage.snapshot.SnapshotPolicy;
import com.cloud.template.VirtualMachineTemplate; import com.cloud.template.VirtualMachineTemplate;
import com.cloud.test.PodZoneConfig; import com.cloud.test.PodZoneConfig;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.User; import com.cloud.user.User;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
@ -3927,4 +3931,55 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setObjectName("vpnconnection"); response.setObjectName("vpnconnection");
return response; return response;
} }
@Override
public FindUserResponse createFindUserResponse(User user) {
FindUserResponse userResponse = new FindUserResponse();
userResponse.setId(user.getId());
userResponse.setUsername(user.getUsername());
userResponse.setPassword(user.getPassword());
userResponse.setFirstname(user.getFirstname());
userResponse.setLastname(user.getLastname());
userResponse.setAccountId(user.getAccountId());
userResponse.setEmail(user.getEmail());
userResponse.setState(user.getState().toString());
userResponse.setApiKey(user.getApiKey());
userResponse.setSecretKey(user.getSecretKey());
userResponse.setCreated(user.getCreated());
userResponse.setTimezone(user.getTimezone());
userResponse.setRegistrationToken(user.getRegistrationToken());
userResponse.setRegistered(user.isRegistered());
userResponse.setRegionId(user.getRegionId());
userResponse.setObjectName("user");
return userResponse;
}
@Override
public FindAccountResponse createFindAccountResponse(Account account) {
FindAccountResponse accountResponse = new FindAccountResponse();
accountResponse.setId(account.getId());
accountResponse.setName(account.getAccountName());
accountResponse.setAccountType(account.getType());
accountResponse.setDefaultZone(account.getDefaultZoneId());
accountResponse.setDomainId(account.getDomainId());
accountResponse.setRegionId(account.getRegionId());
accountResponse.setState(account.getState().toString());
accountResponse.setObjectName("account");
return accountResponse;
}
@Override
public FindDomainResponse createFindDomainResponse(Domain domain) {
FindDomainResponse domainResponse = new FindDomainResponse();
domainResponse.setDomainName(domain.getName());
domainResponse.setId(domain.getId());
domainResponse.setLevel(domain.getLevel());
domainResponse.setNetworkDomain(domain.getNetworkDomain());
domainResponse.setParent(domain.getParent());
domainResponse.setPath(domain.getPath());
domainResponse.setObjectName("domain");
domainResponse.setRegionId(domain.getRegionId());
return domainResponse;
}
} }

View File

@ -97,6 +97,7 @@ import com.cloud.event.EventUtils;
import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.CloudAuthenticationException;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
import com.cloud.region.RegionManager;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
@ -133,6 +134,7 @@ public class ApiServer implements HttpRequestHandler {
private AsyncJobManager _asyncMgr = null; private AsyncJobManager _asyncMgr = null;
private Account _systemAccount = null; private Account _systemAccount = null;
private User _systemUser = null; private User _systemUser = null;
private RegionManager _regionMgr = null;
private static int _workerCount = 0; private static int _workerCount = 0;
@ -276,6 +278,7 @@ public class ApiServer implements HttpRequestHandler {
_systemUser = _accountMgr.getSystemUser(); _systemUser = _accountMgr.getSystemUser();
_dispatcher = ApiDispatcher.getInstance(); _dispatcher = ApiDispatcher.getInstance();
_domainMgr = locator.getManager(DomainManager.class); _domainMgr = locator.getManager(DomainManager.class);
_regionMgr = locator.getManager(RegionManager.class);
Integer apiPort = null; // api port, null by default Integer apiPort = null; // api port, null by default
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
@ -785,7 +788,7 @@ public class ApiServer implements HttpRequestHandler {
if (domainPath == null || domainPath.trim().length() == 0) { if (domainPath == null || domainPath.trim().length() == 0) {
domainId = DomainVO.ROOT_DOMAIN; domainId = DomainVO.ROOT_DOMAIN;
} else { } else {
Domain domainObj = _domainMgr.findDomainByPath(domainPath); Domain domainObj = _regionMgr.findDomainByPath(domainPath);
if (domainObj != null) { if (domainObj != null) {
domainId = domainObj.getId(); domainId = domainObj.getId();
} else { // if an unknown path is passed in, fail the login call } else { // if an unknown path is passed in, fail the login call

View File

@ -0,0 +1,638 @@
// 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.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.SocketHttpServerConnection;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.log4j.Logger;
import com.cloud.api.response.ApiResponseSerializer;
import com.cloud.api.response.ExceptionResponse;
import com.cloud.async.AsyncJobManager;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.region.RegionManager;
import com.cloud.server.ManagementService;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.DomainManager;
import com.cloud.user.User;
import com.cloud.user.UserContext;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.exception.CSExceptionErrorCode;
public class MockApiServer implements HttpRequestHandler {
private static final Logger s_logger = Logger.getLogger(MockApiServer.class.getName());
public static final short ADMIN_COMMAND = 1;
public static final short DOMAIN_ADMIN_COMMAND = 4;
public static final short RESOURCE_DOMAIN_ADMIN_COMMAND = 2;
public static final short USER_COMMAND = 8;
public static boolean encodeApiResponse = false;
public static String jsonContentType = "text/javascript";
private Properties _apiCommands = null;
private ApiDispatcher _dispatcher;
private AccountManager _accountMgr = null;
private Account _systemAccount = null;
private User _systemUser = null;
private static int _workerCount = 0;
private static MockApiServer s_instance = null;
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;
private static List<String> s_pluggableServiceCommands = null;
private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
static {
s_userCommands = new ArrayList<String>();
s_resellerCommands = new ArrayList<String>();
s_adminCommands = new ArrayList<String>();
s_resourceDomainAdminCommands = new ArrayList<String>();
s_allCommands = new ArrayList<String>();
s_pluggableServiceCommands = new ArrayList<String>();
}
private MockApiServer() {
}
public static void initApiServer(String[] apiConfig) {
if (s_instance == null) {
s_instance = new MockApiServer();
s_instance.init(apiConfig);
}
}
public static MockApiServer getInstance() {
// initApiServer();
return s_instance;
}
public Properties get_apiCommands() {
return _apiCommands;
}
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig) {
try {
if (_apiCommands == null) {
_apiCommands = new Properties();
}
Properties preProcessedCommands = new Properties();
if (apiConfig != null) {
for (String configFile : apiConfig) {
File commandsFile = PropertiesUtil.findConfigFile(configFile);
if (commandsFile != null) {
try {
preProcessedCommands.load(new FileInputStream(commandsFile));
} catch (FileNotFoundException fnfex) {
// in case of a file within a jar in classpath, try to open stream using url
InputStream stream = PropertiesUtil.openStreamFromURL(configFile);
if (stream != null) {
preProcessedCommands.load(stream);
} else {
s_logger.error("Unable to find properites file", fnfex);
}
}
}
}
for (Object key : preProcessedCommands.keySet()) {
String preProcessedCommand = preProcessedCommands.getProperty((String) key);
String[] commandParts = preProcessedCommand.split(";");
_apiCommands.put(key, commandParts[0]);
if (pluggableServicesConfig) {
s_pluggableServiceCommands.add(commandParts[0]);
}
if (commandParts.length > 1) {
try {
short cmdPermissions = Short.parseShort(commandParts[1]);
if ((cmdPermissions & ADMIN_COMMAND) != 0) {
s_adminCommands.add((String) key);
}
if ((cmdPermissions & RESOURCE_DOMAIN_ADMIN_COMMAND) != 0) {
s_resourceDomainAdminCommands.add((String) key);
}
if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) {
s_resellerCommands.add((String) key);
}
if ((cmdPermissions & USER_COMMAND) != 0) {
s_userCommands.add((String) key);
}
} catch (NumberFormatException nfe) {
s_logger.info("Malformed command.properties permissions value, key = " + key + ", value = " + preProcessedCommand);
}
}
}
s_allCommands.addAll(s_adminCommands);
s_allCommands.addAll(s_resourceDomainAdminCommands);
s_allCommands.addAll(s_userCommands);
s_allCommands.addAll(s_resellerCommands);
}
} catch (FileNotFoundException fnfex) {
s_logger.error("Unable to find properites file", fnfex);
} catch (IOException ioex) {
s_logger.error("Exception loading properties file", ioex);
}
}
public void init(String[] apiConfig) {
BaseCmd.setComponents(new ApiResponseHelper());
BaseListCmd.configure();
processConfigFiles(apiConfig, false);
ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
_accountMgr = locator.getManager(AccountManager.class);
_systemAccount = _accountMgr.getSystemAccount();
_systemUser = _accountMgr.getSystemUser();
_dispatcher = ApiDispatcher.getInstance();
Integer apiPort = null; // api port, null by default
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
SearchCriteria<ConfigurationVO> sc = configDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port");
List<ConfigurationVO> values = configDao.search(sc, null);
if ((values != null) && (values.size() > 0)) {
ConfigurationVO apiPortConfig = values.get(0);
if (apiPortConfig.getValue() != null) {
apiPort = Integer.parseInt(apiPortConfig.getValue());
}
}
encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key()));
String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key());
if (jsonType != null) {
jsonContentType = jsonType;
}
if (apiPort != null) {
ListenerThread listenerThread = new ListenerThread(this, apiPort);
listenerThread.start();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
// get some information for the access log...
StringBuffer sb = new StringBuffer();
HttpServerConnection connObj = (HttpServerConnection) context.getAttribute("http.connection");
if (connObj instanceof SocketHttpServerConnection) {
InetAddress remoteAddr = ((SocketHttpServerConnection) connObj).getRemoteAddress();
sb.append(remoteAddr.toString() + " -- ");
}
sb.append(request.getRequestLine());
try {
String uri = request.getRequestLine().getUri();
int requestParamsStartIndex = uri.indexOf('?');
if (requestParamsStartIndex >= 0) {
uri = uri.substring(requestParamsStartIndex + 1);
}
String[] paramArray = uri.split("&");
if (paramArray.length < 1) {
s_logger.info("no parameters received for request: " + uri + ", aborting...");
return;
}
Map parameterMap = new HashMap<String, String[]>();
String responseType = BaseCmd.RESPONSE_TYPE_XML;
for (String paramEntry : paramArray) {
String[] paramValue = paramEntry.split("=");
if (paramValue.length != 2) {
s_logger.info("malformed parameter: " + paramEntry + ", skipping");
continue;
}
if ("response".equalsIgnoreCase(paramValue[0])) {
responseType = paramValue[1];
} else {
// according to the servlet spec, the parameter map should be in the form (name=String,
// value=String[]), so
// parameter values will be stored in an array
parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] });
}
}
try {
// always trust commands from API port, user context will always be UID_SYSTEM/ACCOUNT_ID_SYSTEM
UserContext.registerContext(_systemUser.getId(), _systemAccount, null, true);
sb.insert(0, "(userId=" + User.UID_SYSTEM + " accountId=" + Account.ACCOUNT_ID_SYSTEM + " sessionId=" + null + ") ");
String responseText = handleRequest(parameterMap, true, responseType, sb);
sb.append(" 200 " + ((responseText == null) ? 0 : responseText.length()));
writeResponse(response, responseText, HttpStatus.SC_OK, responseType, null);
} catch (ServerApiException se) {
String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se);
writeResponse(response, responseText, se.getErrorCode(), responseType, se.getDescription());
sb.append(" " + se.getErrorCode() + " " + se.getDescription());
} catch (RuntimeException e) {
// log runtime exception like NullPointerException to help identify the source easier
s_logger.error("Unhandled exception, ", e);
throw e;
} catch (Exception e){
s_logger.info("Error: "+e.getMessage());
}
} finally {
UserContext.unregisterContext();
}
}
@SuppressWarnings("rawtypes")
public String handleRequest(Map params, boolean decode, String responseType, StringBuffer auditTrailSb) throws ServerApiException {
String response = null;
String[] command = null;
try {
command = (String[]) params.get("command");
if (command == null) {
s_logger.error("invalid request, no command sent");
if (s_logger.isTraceEnabled()) {
s_logger.trace("dumping request parameters");
for (Object key : params.keySet()) {
String keyStr = (String) key;
String[] value = (String[]) params.get(key);
s_logger.trace(" key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
}
}
throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
} else {
Map<String, String> paramMap = new HashMap<String, String>();
Set keys = params.keySet();
Iterator keysIter = keys.iterator();
while (keysIter.hasNext()) {
String key = (String) keysIter.next();
if ("command".equalsIgnoreCase(key)) {
continue;
}
String[] value = (String[]) params.get(key);
String decodedValue = null;
if (decode) {
try {
decodedValue = URLDecoder.decode(value[0], "UTF-8");
} catch (UnsupportedEncodingException usex) {
s_logger.warn(key + " could not be decoded, value = " + value[0]);
throw new ServerApiException(BaseCmd.PARAM_ERROR, key + " could not be decoded, received value " + value[0]);
} catch (IllegalArgumentException iae) {
s_logger.warn(key + " could not be decoded, value = " + value[0]);
throw new ServerApiException(BaseCmd.PARAM_ERROR, key + " could not be decoded, received value " + value[0] + " which contains illegal characters eg.%");
}
} else {
decodedValue = value[0];
}
paramMap.put(key, decodedValue);
}
String cmdClassName = _apiCommands.getProperty(command[0]);
if (cmdClassName != null) {
Class<?> cmdClass = Class.forName(cmdClassName);
BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
cmdObj.setFullUrlParams(paramMap);
cmdObj.setResponseType(responseType);
// This is where the command is either serialized, or directly dispatched
response = queueCommand(cmdObj, paramMap);
} else {
if (!command[0].equalsIgnoreCase("login") && !command[0].equalsIgnoreCase("logout")) {
String errorString = "Unknown API command: " + ((command == null) ? "null" : command[0]);
s_logger.warn(errorString);
auditTrailSb.append(" " + errorString);
throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, errorString);
}
}
}
} catch (Exception ex) {
if (ex instanceof InvalidParameterValueException) {
InvalidParameterValueException ref = (InvalidParameterValueException)ex;
ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage());
// copy over the IdentityProxy information as well and throw the serverapiexception.
ArrayList<IdentityProxy> idList = ref.getIdProxyList();
if (idList != null) {
// Iterate through entire arraylist and copy over each proxy id.
for (int i = 0 ; i < idList.size(); i++) {
IdentityProxy obj = idList.get(i);
e.addProxyObject(obj.getTableName(), obj.getValue(), obj.getidFieldName());
}
}
// Also copy over the cserror code and the function/layer in which it was thrown.
e.setCSErrorCode(ref.getCSErrorCode());
throw e;
} else if (ex instanceof PermissionDeniedException) {
PermissionDeniedException ref = (PermissionDeniedException)ex;
ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage());
// copy over the IdentityProxy information as well and throw the serverapiexception.
ArrayList<IdentityProxy> idList = ref.getIdProxyList();
if (idList != null) {
// Iterate through entire arraylist and copy over each proxy id.
for (int i = 0 ; i < idList.size(); i++) {
IdentityProxy obj = idList.get(i);
e.addProxyObject(obj.getTableName(), obj.getValue(), obj.getidFieldName());
}
}
e.setCSErrorCode(ref.getCSErrorCode());
throw e;
} else if (ex instanceof ServerApiException) {
throw (ServerApiException) ex;
} else {
s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex);
ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal server error, unable to execute request.");
e.setCSErrorCode(CSExceptionErrorCode.getCSErrCode("ServerApiException"));
throw e;
}
}
return response;
}
private String queueCommand(BaseCmd cmdObj, Map<String, String> params) {
params.put("ctxStartEventId", String.valueOf(0L));
_dispatcher.dispatch(cmdObj, params);
SerializationContext.current().setUuidTranslation(true);
return ApiResponseSerializer.toSerializedString((ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType());
}
// FIXME: rather than isError, we might was to pass in the status code to give more flexibility
private void writeResponse(HttpResponse resp, final String responseText, final int statusCode, String responseType, String reasonPhrase) {
try {
resp.setStatusCode(statusCode);
resp.setReasonPhrase(reasonPhrase);
BasicHttpEntity body = new BasicHttpEntity();
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
// JSON response
body.setContentType(jsonContentType);
if (responseText == null) {
body.setContent(new ByteArrayInputStream("{ \"error\" : { \"description\" : \"Internal Server Error\" } }".getBytes("UTF-8")));
}
} else {
body.setContentType("text/xml");
if (responseText == null) {
body.setContent(new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes("UTF-8")));
}
}
if (responseText != null) {
body.setContent(new ByteArrayInputStream(responseText.getBytes("UTF-8")));
}
resp.setEntity(body);
} catch (Exception ex) {
s_logger.error("error!", ex);
}
}
// FIXME: the following two threads are copied from
// http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java
// we have to cite a license if we are using this code directly, so we need to add the appropriate citation or
// modify the
// code to be very specific to our needs
static class ListenerThread extends Thread {
private HttpService _httpService = null;
private ServerSocket _serverSocket = null;
private HttpParams _params = null;
public ListenerThread(MockApiServer requestHandler, int port) {
try {
_serverSocket = new ServerSocket(port);
} catch (IOException ioex) {
s_logger.error("error initializing api server", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
@Override
public void run() {
s_logger.info("ApiServer listening on port " + _serverSocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = _serverSocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, _params);
// Execute a new worker task to handle the request
_executor.execute(new WorkerTask(_httpService, conn, _workerCount++));
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
s_logger.error("I/O error initializing connection thread", e);
break;
}
}
}
}
static class WorkerTask implements Runnable {
private final HttpService _httpService;
private final HttpServerConnection _conn;
public WorkerTask(final HttpService httpService, final HttpServerConnection conn, final int count) {
_httpService = httpService;
_conn = conn;
}
@Override
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && _conn.isOpen()) {
try {
_httpService.handleRequest(_conn, context);
_conn.close();
} finally {
StackMaid.current().exitCleanup();
}
}
} catch (ConnectionClosedException ex) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("ApiServer: Client closed connection");
}
} catch (IOException ex) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("ApiServer: IOException - " + ex);
}
} catch (HttpException ex) {
s_logger.warn("ApiServer: Unrecoverable HTTP protocol violation" + ex);
} finally {
try {
_conn.shutdown();
} catch (IOException ignore) {
}
}
}
}
public String getSerializedApiError(int errorCode, String errorText, Map<String, Object[]> apiCommandParams, String responseType, Exception ex) {
String responseName = null;
String cmdClassName = null;
String responseText = null;
try {
if (errorCode == BaseCmd.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) {
responseName = "errorresponse";
} else {
Object cmdObj = apiCommandParams.get("command");
// cmd name can be null when "command" parameter is missing in the request
if (cmdObj != null) {
String cmdName = ((String[]) cmdObj)[0];
cmdClassName = _apiCommands.getProperty(cmdName);
if (cmdClassName != null) {
Class<?> claz = Class.forName(cmdClassName);
responseName = ((BaseCmd) claz.newInstance()).getCommandName();
} else {
responseName = "errorresponse";
}
}
}
ExceptionResponse apiResponse = new ExceptionResponse();
apiResponse.setErrorCode(errorCode);
apiResponse.setErrorText(errorText);
apiResponse.setResponseName(responseName);
// Also copy over the IdentityProxy object List into this new apiResponse, from
// the exception caught. When invoked from handle(), the exception here can
// be either ServerApiException, PermissionDeniedException or InvalidParameterValue
// Exception. When invoked from ApiServlet's processRequest(), this can be
// a standard exception like NumberFormatException. We'll leave the standard ones alone.
if (ex != null) {
if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException
|| ex instanceof InvalidParameterValueException) {
// Cast the exception appropriately and retrieve the IdentityProxy
if (ex instanceof ServerApiException) {
ServerApiException ref = (ServerApiException) ex;
ArrayList<IdentityProxy> idList = ref.getIdProxyList();
if (idList != null) {
for (int i=0; i < idList.size(); i++) {
IdentityProxy id = idList.get(i);
apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName());
}
}
// Also copy over the cserror code and the function/layer in which it was thrown.
apiResponse.setCSErrorCode(ref.getCSErrorCode());
} else if (ex instanceof PermissionDeniedException) {
PermissionDeniedException ref = (PermissionDeniedException) ex;
ArrayList<IdentityProxy> idList = ref.getIdProxyList();
if (idList != null) {
for (int i=0; i < idList.size(); i++) {
IdentityProxy id = idList.get(i);
apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName());
}
}
// Also copy over the cserror code and the function/layer in which it was thrown.
apiResponse.setCSErrorCode(ref.getCSErrorCode());
} else if (ex instanceof InvalidParameterValueException) {
InvalidParameterValueException ref = (InvalidParameterValueException) ex;
ArrayList<IdentityProxy> idList = ref.getIdProxyList();
if (idList != null) {
for (int i=0; i < idList.size(); i++) {
IdentityProxy id = idList.get(i);
apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName());
}
}
// Also copy over the cserror code and the function/layer in which it was thrown.
apiResponse.setCSErrorCode(ref.getCSErrorCode());
}
}
}
SerializationContext.current().setUuidTranslation(true);
responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);
} catch (Exception e) {
s_logger.error("Exception responding to http request", e);
}
return responseText;
}
}

View File

@ -75,11 +75,11 @@ public class DomainVO implements Domain, Identity {
private String uuid; private String uuid;
@Column(name="region_id") @Column(name="region_id")
private long regionId; private int regionId;
public DomainVO() {} public DomainVO() {}
public DomainVO(String name, long owner, Long parentId, String networkDomain, Long regionId) { public DomainVO(String name, long owner, Long parentId, String networkDomain, int regionId) {
this.parent = parentId; this.parent = parentId;
this.name = name; this.name = name;
this.accountId = owner; this.accountId = owner;
@ -91,7 +91,7 @@ public class DomainVO implements Domain, Identity {
this.regionId = regionId; this.regionId = regionId;
} }
public DomainVO(String name, long owner, Long parentId, String networkDomain, String uuid, Long regionId) { public DomainVO(String name, long owner, Long parentId, String networkDomain, String uuid, int regionId) {
this.parent = parentId; this.parent = parentId;
this.name = name; this.name = name;
this.accountId = owner; this.accountId = owner;
@ -215,11 +215,11 @@ public class DomainVO implements Domain, Identity {
this.uuid = uuid; this.uuid = uuid;
} }
public long getRegionId() { public int getRegionId() {
return regionId; return regionId;
} }
public void setRegionId(long regionId) { public void setRegionId(int regionId) {
this.regionId = regionId; this.regionId = regionId;
} }
} }

View File

@ -29,10 +29,9 @@ import org.apache.log4j.Logger;
import com.cloud.domain.Domain; import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO; import com.cloud.domain.DomainVO;
import com.cloud.user.UserVO; import com.cloud.region.RegionManager;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@ -47,7 +46,6 @@ public class DomainDaoImpl extends GenericDaoBase<DomainVO, Long> implements Dom
protected SearchBuilder<DomainVO> ImmediateChildDomainSearch; protected SearchBuilder<DomainVO> ImmediateChildDomainSearch;
protected SearchBuilder<DomainVO> FindAllChildrenSearch; protected SearchBuilder<DomainVO> FindAllChildrenSearch;
protected SearchBuilder<DomainVO> AllFieldsSearch; protected SearchBuilder<DomainVO> AllFieldsSearch;
private final long _regionId = 1;
public DomainDaoImpl () { public DomainDaoImpl () {
DomainNameLikeSearch = createSearchBuilder(); DomainNameLikeSearch = createSearchBuilder();
@ -273,10 +271,4 @@ public class DomainDaoImpl extends GenericDaoBase<DomainVO, Long> implements Dom
return parentDomains; return parentDomains;
} }
@Override
@DB
public DomainVO persist(DomainVO domain) {
domain.setRegionId(_regionId);
return super.persist(domain);
}
} }

View File

@ -207,7 +207,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{
StringBuilder acctNm = new StringBuilder("PrjAcct-"); StringBuilder acctNm = new StringBuilder("PrjAcct-");
acctNm.append(name).append("-").append(owner.getDomainId()); acctNm.append(name).append("-").append(owner.getDomainId());
Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, domainId, null, null, "", 0L); Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, domainId, null, null, "", 0);
Project project = _projectDao.persist(new ProjectVO(name, displayText, owner.getDomainId(), projectAccount.getId())); Project project = _projectDao.persist(new ProjectVO(name, displayText, owner.getDomainId(), projectAccount.getId()));

View File

@ -0,0 +1,36 @@
// 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.region;
import com.cloud.domain.Domain;
public class FindDomainResponse {
private Domain domain;
public FindDomainResponse(){
}
public Domain getDomain() {
return domain;
}
public void setDomain(Domain domain) {
this.domain = domain;
}
}

View File

@ -0,0 +1,34 @@
// 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.region;
public class FindUserResponse {
private RegionUser user;
public FindUserResponse(){
}
public RegionUser getUser() {
return user;
}
public void setUser(RegionUser user) {
this.user = user;
}
}

View File

@ -0,0 +1,287 @@
// 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.region;
import com.cloud.user.AccountVO;
public class RegionAccount extends AccountVO {
String accountUuid;
String domainUuid;
String domain;
String receivedbytes;
String sentbytes;
String vmlimit;
String vmtotal;
String vmavailable;
String iplimit;
String iptotal;
String ipavailable;
String volumelimit;
String volumetotal;
String volumeavailable;
String snapshotlimit;
String snapshottotal;
String snapshotavailable;
String templatelimit;
String templatetotal;
String templateavailable;
String vmstopped;
String vmrunning;
String projectlimit;
String projecttotal;
String projectavailable;
String networklimit;
String networktotal;
String networkavailable;
RegionUser user;
public RegionAccount() {
}
public String getAccountuuid() {
return accountUuid;
}
public void setAccountuuid(String accountUuid) {
this.accountUuid = accountUuid;
}
public String getDomainUuid() {
return domainUuid;
}
public void setDomainUuid(String domainUuid) {
this.domainUuid = domainUuid;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getReceivedbytes() {
return receivedbytes;
}
public void setReceivedbytes(String receivedbytes) {
this.receivedbytes = receivedbytes;
}
public String getSentbytes() {
return sentbytes;
}
public void setSentbytes(String sentbytes) {
this.sentbytes = sentbytes;
}
public String getVmlimit() {
return vmlimit;
}
public void setVmlimit(String vmlimit) {
this.vmlimit = vmlimit;
}
public String getVmtotal() {
return vmtotal;
}
public void setVmtotal(String vmtotal) {
this.vmtotal = vmtotal;
}
public String getVmavailable() {
return vmavailable;
}
public void setVmavailable(String vmavailable) {
this.vmavailable = vmavailable;
}
public String getIplimit() {
return iplimit;
}
public void setIplimit(String iplimit) {
this.iplimit = iplimit;
}
public String getIptotal() {
return iptotal;
}
public void setIptotal(String iptotal) {
this.iptotal = iptotal;
}
public String getIpavailable() {
return ipavailable;
}
public void setIpavailable(String ipavailable) {
this.ipavailable = ipavailable;
}
public String getVolumelimit() {
return volumelimit;
}
public void setVolumelimit(String volumelimit) {
this.volumelimit = volumelimit;
}
public String getVolumetotal() {
return volumetotal;
}
public void setVolumetotal(String volumetotal) {
this.volumetotal = volumetotal;
}
public String getVolumeavailable() {
return volumeavailable;
}
public void setVolumeavailable(String volumeavailable) {
this.volumeavailable = volumeavailable;
}
public String getSnapshotlimit() {
return snapshotlimit;
}
public void setSnapshotlimit(String snapshotlimit) {
this.snapshotlimit = snapshotlimit;
}
public String getSnapshottotal() {
return snapshottotal;
}
public void setSnapshottotal(String snapshottotal) {
this.snapshottotal = snapshottotal;
}
public String getSnapshotavailable() {
return snapshotavailable;
}
public void setSnapshotavailable(String snapshotavailable) {
this.snapshotavailable = snapshotavailable;
}
public String getTemplatelimit() {
return templatelimit;
}
public void setTemplatelimit(String templatelimit) {
this.templatelimit = templatelimit;
}
public String getTemplatetotal() {
return templatetotal;
}
public void setTemplatetotal(String templatetotal) {
this.templatetotal = templatetotal;
}
public String getTemplateavailable() {
return templateavailable;
}
public void setTemplateavailable(String templateavailable) {
this.templateavailable = templateavailable;
}
public String getVmstopped() {
return vmstopped;
}
public void setVmstopped(String vmstopped) {
this.vmstopped = vmstopped;
}
public String getVmrunning() {
return vmrunning;
}
public void setVmrunning(String vmrunning) {
this.vmrunning = vmrunning;
}
public String getProjectlimit() {
return projectlimit;
}
public void setProjectlimit(String projectlimit) {
this.projectlimit = projectlimit;
}
public String getProjecttotal() {
return projecttotal;
}
public void setProjecttotal(String projecttotal) {
this.projecttotal = projecttotal;
}
public String getProjectavailable() {
return projectavailable;
}
public void setProjectavailable(String projectavailable) {
this.projectavailable = projectavailable;
}
public String getNetworklimit() {
return networklimit;
}
public void setNetworklimit(String networklimit) {
this.networklimit = networklimit;
}
public String getNetworktotal() {
return networktotal;
}
public void setNetworktotal(String networktotal) {
this.networktotal = networktotal;
}
public String getNetworkavailable() {
return networkavailable;
}
public void setNetworkavailable(String networkavailable) {
this.networkavailable = networkavailable;
}
public RegionUser getUser() {
return user;
}
public void setUser(RegionUser user) {
this.user = user;
}
}

View File

@ -0,0 +1,61 @@
// 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.region;
import com.cloud.domain.DomainVO;
public class RegionDomain extends DomainVO {
String accountUuid;
String parentUuid;
String parentdomainname;
Boolean haschild;
public RegionDomain() {
}
public String getAccountuuid() {
return accountUuid;
}
public void setAccountuuid(String accountUuid) {
this.accountUuid = accountUuid;
}
public String getParentUuid() {
return parentUuid;
}
public void setParentUuid(String parentUuid) {
this.parentUuid = parentUuid;
}
public String getParentdomainname() {
return parentdomainname;
}
public void setParentdomainname(String parentdomainname) {
this.parentdomainname = parentdomainname;
}
public Boolean getHaschild() {
return haschild;
}
public void setHaschild(Boolean haschild) {
this.haschild = haschild;
}
}

View File

@ -18,14 +18,19 @@ package com.cloud.region;
import java.util.Map; import java.util.Map;
import com.cloud.domain.DomainVO;
import com.cloud.user.UserAccount;
public interface RegionManager { public interface RegionManager {
public boolean propogateAddAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, public boolean propogateAddAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain,
Map<String, String> details, String accountUUID, String userUUID); Map<String, String> details, String accountUUID, String userUUID);
public long getId(); public int getId();
public void setId(long id); public void setId(int id);
public void propogateAddUser(String userName, String password, public void propogateAddUser(String userName, String password,
String firstName, String lastName, String email, String timeZone, String firstName, String lastName, String email, String timeZone,
String accountName, String domainUUId, String userUUID); String accountName, String domainUUId, String userUUID);
public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid); public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid);
UserAccount getUserAccount(String username, Long domainId);
DomainVO findDomainByPath(String domainPath);
} }

View File

@ -16,7 +16,6 @@
// under the License. // under the License.
package com.cloud.region; package com.cloud.region;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -24,10 +23,7 @@ import java.util.Map;
import javax.ejb.Local; import javax.ejb.Local;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants; import com.cloud.api.ApiConstants;
@ -43,7 +39,6 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.region.dao.RegionDao; import com.cloud.region.dao.RegionDao;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO; import com.cloud.user.AccountVO;
@ -51,9 +46,12 @@ import com.cloud.user.DomainManager;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserDao;
import com.cloud.utils.component.Inject; import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.uuididentity.dao.IdentityDao;
@Local(value = { RegionManager.class, RegionService.class }) @Local(value = { RegionManager.class, RegionService.class })
public class RegionManagerImpl implements RegionManager, RegionService, Manager{ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
@ -70,20 +68,19 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
@Inject @Inject
private DomainDao _domainDao; private DomainDao _domainDao;
@Inject @Inject
private ManagementServer _mgmtSrvr;
@Inject
private DomainManager _domainMgr; private DomainManager _domainMgr;
@Inject
private UserAccountDao _userAccountDao;
@Inject
private IdentityDao _identityDao;
private String _name; private String _name;
private long _id = 1; //ToDo, get this from config or db.properties private int _id;
//ToDo use API constants
//prepare API params in advance
@Override @Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
_id = _regionDao.getRegionId();
return true; return true;
} }
@ -105,45 +102,34 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
@Override @Override
public boolean propogateAddAccount(String userName, String password, String firstName, String lastName, String email, String timezone, public boolean propogateAddAccount(String userName, String password, String firstName, String lastName, String email, String timezone,
String accountName, short accountType, Long domainId, String networkDomain, Map<String, String> details, String accountUUID, String userUUID) { String accountName, short accountType, Long domainId, String networkDomain, Map<String, String> details, String accountUUID, String userUUID) {
List<RegionVO> regions = _regionDao.listAll(); String command = "createAccount";
StringBuffer params = new StringBuffer("/api?command=createAccount"); List<NameValuePair> params = new ArrayList<NameValuePair>();
params.append("&"+ApiConstants.USERNAME+"="+userName); params.add(new NameValuePair(ApiConstants.USERNAME, userName));
params.append("&"+ApiConstants.PASSWORD+"="+password); params.add(new NameValuePair(ApiConstants.PASSWORD, password));
params.append("&"+ApiConstants.FIRSTNAME+"="+firstName); params.add(new NameValuePair(ApiConstants.FIRSTNAME, firstName));
params.append("&"+ApiConstants.LASTNAME+"="+lastName); params.add(new NameValuePair(ApiConstants.LASTNAME, lastName));
params.append("&"+ApiConstants.EMAIL+"="+email); params.add(new NameValuePair(ApiConstants.EMAIL, email));
if(timezone != null){ params.add(new NameValuePair(ApiConstants.TIMEZONE, timezone));
params.append("&"+ApiConstants.TIMEZONE+"="+timezone); params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName));
} params.add(new NameValuePair(ApiConstants.ACCOUNT_TYPE, ""+accountType));
if(accountName != null){ //use domain UUID
params.append("&"+ApiConstants.ACCOUNT+"="+accountName); params.add(new NameValuePair(ApiConstants.DOMAIN_ID, ((domainId != null) ? domainId.toString() : "")));
} params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain));
params.append("&"+ApiConstants.ACCOUNT_TYPE+"="+accountType); params.add(new NameValuePair(ApiConstants.ACCOUNT_DETAILS, (details != null) ? details.toString() : ""));
if(domainId != null){ params.add(new NameValuePair(ApiConstants.ACCOUNT_ID, accountUUID));
params.append("&"+ApiConstants.DOMAIN_ID+"="+domainId); //use UUID params.add(new NameValuePair(ApiConstants.USER_ID, userUUID));
} params.add(new NameValuePair(ApiConstants.REGION_ID, ""+getId()));
if(networkDomain != null){
params.append("&"+ApiConstants.NETWORK_DOMAIN+"="+networkDomain);
}
if(details != null){
params.append("&"+ApiConstants.ACCOUNT_DETAILS+"="+details); //ToDo change to Map
}
params.append("&"+ApiConstants.ACCOUNT_ID+"="+accountUUID);
params.append("&"+ApiConstants.USER_ID+"="+userUUID);
params.append("&"+ApiConstants.REGION_ID+"="+getId());
List<RegionVO> regions = _regionDao.listAll();
for (Region region : regions){ for (Region region : regions){
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId());
String url = region.getEndPoint() + params; if (RegionsApiUtil.makeAPICall(region, command, params)) {
if (makeAPICall(url)) {
s_logger.debug("Successfully added account :"+accountName+" to Region: "+region.getId()); s_logger.debug("Successfully added account :"+accountName+" to Region: "+region.getId());
} else { } else {
s_logger.error("Error while Adding account :"+accountName+" to Region: "+region.getId()); s_logger.error("Error while Adding account :"+accountName+" to Region: "+region.getId());
//Send Account delete to all Regions where account is added successfully
break;
} }
} }
return true; return true;
@ -156,8 +142,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
return false; return false;
} }
String accountUUID = account.getUuid(); String accountUUID = account.getUuid();
long regionId = account.getRegionId(); int regionId = account.getRegionId();
String params = "/api?command=deleteAccount&"+ApiConstants.ID+"="+accountUUID;
String command = "deleteAccount";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.ID, accountUUID));
if(getId() == regionId){ if(getId() == regionId){
if(_accountMgr.deleteUserAccount(accountId)){ if(_accountMgr.deleteUserAccount(accountId)){
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
@ -165,8 +155,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params+"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while deleting account :"+accountUUID+" in Region: "+region.getId()); s_logger.error("Error while deleting account :"+accountUUID+" in Region: "+region.getId());
@ -179,8 +169,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First delete in the Region where account is created //First delete in the Region where account is created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; if (RegionsApiUtil.makeAPICall(region, command, params)) {
if (makeAPICall(url)) {
s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId());
return true; return true;
} else { } else {
@ -198,6 +187,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
String accountName = cmd.getAccountName(); String accountName = cmd.getAccountName();
String newAccountName = cmd.getNewName(); String newAccountName = cmd.getNewName();
String networkDomain = cmd.getNetworkDomain(); String networkDomain = cmd.getNetworkDomain();
//ToDo send details
Map<String, String> details = cmd.getDetails(); Map<String, String> details = cmd.getDetails();
Account account = null; Account account = null;
@ -213,87 +203,70 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
} }
StringBuffer params = new StringBuffer("/api?command=updateAccount"); String command = "updateAccount";
params.append("&"+ApiConstants.NEW_NAME+"="+newAccountName); List<NameValuePair> params = new ArrayList<NameValuePair>();
if(account != null){ params.add(new NameValuePair(ApiConstants.NEW_NAME, newAccountName));
params.append("&"+ApiConstants.ID+"="+account.getUuid()); params.add(new NameValuePair(ApiConstants.ID, account.getUuid()));
} params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName));
if(accountName != null){ params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid()));
params.append("&"+ApiConstants.ACCOUNT+"="+accountName); params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain));
} params.add(new NameValuePair(ApiConstants.NEW_NAME, newAccountName));
if(domain != null){ if(details != null){
params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); params.add(new NameValuePair(ApiConstants.ACCOUNT_DETAILS, details.toString()));
} }
if(networkDomain != null){ int regionId = account.getRegionId();
params.append("&"+ApiConstants.NETWORK_DOMAIN+"="+networkDomain);
}
if(details != null){
params.append("&"+ApiConstants.ACCOUNT_DETAILS+"="+details);
}
long regionId = account.getRegionId();
if(getId() == regionId){ if(getId() == regionId){
Account updateAccount = _accountMgr.updateAccount(cmd); Account updatedAccount = _accountMgr.updateAccount(cmd);
if(updateAccount != null){ if(updatedAccount != null){
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
for (Region region : regions){ for (Region region : regions){
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params+"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully updated account :"+account.getUuid()+" in Region: "+region.getId()); s_logger.debug("Successfully updated account :"+account.getUuid()+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while updating account :"+account.getUuid()+" in Region: "+region.getId()); s_logger.error("Error while updating account :"+account.getUuid()+" in Region: "+region.getId());
} }
} }
} }
return updateAccount; return updatedAccount;
} else { } else {
//First update in the Region where account is created //First update in the Region where account is created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; RegionAccount updatedAccount = RegionsApiUtil.makeAccountAPICall(region, command, params);
if (makeAPICall(url)) { if (updatedAccount != null) {
Long id = _identityDao.getIdentityId("account", updatedAccount.getUuid());
updatedAccount.setId(id);
Long domainID = _identityDao.getIdentityId("domain", updatedAccount.getDomainUuid());
updatedAccount.setDomainId(domainID);
s_logger.debug("Successfully updated account :"+account.getUuid()+" in source Region: "+region.getId()); s_logger.debug("Successfully updated account :"+account.getUuid()+" in source Region: "+region.getId());
//return Account object return updatedAccount;
return null;
} else { } else {
s_logger.error("Error while updating account :"+account.getUuid()+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while updating account :"+account.getUuid()+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
private boolean makeAPICall(String url){ @Override
try { public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey) {
if( _regionDao.findById(id) == null ){
HttpClient client = new HttpClient(); RegionVO region = new RegionVO(id, name, endPoint, apiKey, secretKey);
HttpMethod method = new GetMethod(url); return _regionDao.persist(region);
if( client.executeMethod(method) == 200){ } else {
return true; throw new InvalidParameterValueException("Region with id: "+id+" already exists");
} else {
return false;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return false;
} catch (IOException e) {
s_logger.error(e.getMessage());
return false;
} }
} }
@Override @Override
public Region addRegion(long id, String name, String endPoint) { public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey) {
RegionVO region = new RegionVO(id, name, endPoint);
return _regionDao.persist(region);
}
@Override
public Region updateRegion(long id, String name, String endPoint) {
RegionVO region = _regionDao.findById(id); RegionVO region = _regionDao.findById(id);
if(region == null){
throw new InvalidParameterValueException("Region with id: "+id+" does not exist");
}
if(name != null){ if(name != null){
region.setName(name); region.setName(name);
} }
@ -302,12 +275,20 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
region.setEndPoint(endPoint); region.setEndPoint(endPoint);
} }
if(apiKey != null){
region.setApiKey(apiKey);
}
if(secretKey != null){
region.setSecretKey(secretKey);
}
_regionDao.update(id, region); _regionDao.update(id, region);
return _regionDao.findById(id); return _regionDao.findById(id);
} }
@Override @Override
public boolean removeRegion(long id) { public boolean removeRegion(int id) {
RegionVO region = _regionDao.findById(id); RegionVO region = _regionDao.findById(id);
if(region != null){ if(region != null){
return _regionDao.remove(id); return _regionDao.remove(id);
@ -316,11 +297,11 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} }
} }
public long getId() { public int getId() {
return _id; return _id;
} }
public void setId(long _id) { public void setId(int _id) {
this._id = _id; this._id = _id;
} }
@ -347,16 +328,17 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
} }
String accountUUID = account.getUuid(); String accountUUID = account.getUuid();
StringBuffer params = new StringBuffer("/api?command=disableAccount"+"&"+ApiConstants.LOCK+"="+lockRequested);
params.append("&"+ApiConstants.ID+"="+accountUUID); String command = "disableAccount";
if(accountName != null){ List<NameValuePair> params = new ArrayList<NameValuePair>();
params.append("&"+ApiConstants.ACCOUNT+"="+accountName); params.add(new NameValuePair(ApiConstants.LOCK, lockRequested.toString()));
} params.add(new NameValuePair(ApiConstants.ID, accountUUID));
DomainVO domain = _domainDao.findById(domainId); DomainVO domain = _domainDao.findById(domainId);
if(domain != null){ if(domain != null){
params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid()));
} }
long regionId = account.getRegionId();
int regionId = account.getRegionId();
if(getId() == regionId){ if(getId() == regionId){
Account retAccount = null; Account retAccount = null;
if(lockRequested){ if(lockRequested){
@ -370,8 +352,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully disabled account :"+accountUUID+" in Region: "+region.getId()); s_logger.debug("Successfully disabled account :"+accountUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while disabling account :"+accountUUID+" in Region: "+region.getId()); s_logger.error("Error while disabling account :"+accountUUID+" in Region: "+region.getId());
@ -382,15 +364,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First disable account in the Region where account is created //First disable account in the Region where account is created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; Account retAccount = RegionsApiUtil.makeAccountAPICall(region, command, params);
if (makeAPICall(url)) { if (retAccount != null) {
s_logger.debug("Successfully disabled account :"+accountUUID+" in source Region: "+region.getId()); s_logger.debug("Successfully disabled account :"+accountUUID+" in source Region: "+region.getId());
//return Account object return retAccount;
return null;
} else { } else {
s_logger.error("Error while disabling account :"+accountUUID+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while disabling account :"+accountUUID+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
@ -409,17 +388,17 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
} }
String accountUUID = account.getUuid(); String accountUUID = account.getUuid();
StringBuffer params = new StringBuffer("/api?command=enableAccount");
params.append("&"+ApiConstants.ID+"="+accountUUID); String command = "enableAccount";
if(accountName != null){ List<NameValuePair> params = new ArrayList<NameValuePair>();
params.append("&"+ApiConstants.ACCOUNT+"="+accountName); params.add(new NameValuePair(ApiConstants.ID, accountUUID));
} params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName));
DomainVO domain = _domainDao.findById(domainId); DomainVO domain = _domainDao.findById(domainId);
if(domain != null){ if(domain != null){
params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid()));
} }
long regionId = account.getRegionId(); int regionId = account.getRegionId();
if(getId() == regionId){ if(getId() == regionId){
Account retAccount = _accountMgr.enableAccount(accountName, domainId, accountId); Account retAccount = _accountMgr.enableAccount(accountName, domainId, accountId);
if(retAccount != null){ if(retAccount != null){
@ -429,8 +408,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully enabled account :"+accountUUID+" in Region: "+region.getId()); s_logger.debug("Successfully enabled account :"+accountUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while enabling account :"+accountUUID+" in Region: "+region.getId()); s_logger.error("Error while enabling account :"+accountUUID+" in Region: "+region.getId());
@ -441,15 +420,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First disable account in the Region where account is created //First disable account in the Region where account is created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; Account retAccount = RegionsApiUtil.makeAccountAPICall(region, command, params);
if (makeAPICall(url)) { if (retAccount != null) {
s_logger.debug("Successfully enabled account :"+accountUUID+" in source Region: "+region.getId()); s_logger.debug("Successfully enabled account :"+accountUUID+" in source Region: "+region.getId());
//return Account object return retAccount;
return null;
} else { } else {
s_logger.error("Error while enabling account :"+accountUUID+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while enabling account :"+accountUUID+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
@ -465,8 +441,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} }
String userUUID = user.getUuid(); String userUUID = user.getUuid();
long regionId = user.getRegionId(); int regionId = user.getRegionId();
String params = "/api?command=deleteUser&id="+userUUID;
String command = "deleteUser";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.ID, userUUID));
if(getId() == regionId){ if(getId() == regionId){
if(_accountMgr.deleteUser(cmd)){ if(_accountMgr.deleteUser(cmd)){
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
@ -474,8 +454,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while deleting account :"+userUUID+" in Region: "+region.getId()); s_logger.error("Error while deleting account :"+userUUID+" in Region: "+region.getId());
@ -488,8 +468,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First delete in the Region where account is created //First delete in the Region where account is created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; if (RegionsApiUtil.makeAPICall(region, command, params)) {
if (makeAPICall(url)) {
s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId());
return true; return true;
} else { } else {
@ -507,10 +486,13 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); throw new InvalidParameterValueException("The specified domain doesn't exist in the system");
} }
String domainUUID = domain.getUuid(); String domainUUID = domain.getUuid();
StringBuffer params = new StringBuffer("/api?command=deleteDomain");
params.append("&"+ApiConstants.ID+"="+domainUUID); String command = "deleteDomain";
params.append("&"+ApiConstants.CLEANUP+"="+cleanup); List<NameValuePair> params = new ArrayList<NameValuePair>();
long regionId = domain.getRegionId(); params.add(new NameValuePair(ApiConstants.ID, domainUUID));
params.add(new NameValuePair(ApiConstants.CLEANUP, cleanup.toString()));
int regionId = domain.getRegionId();
if(getId() == regionId){ if(getId() == regionId){
if(_domainMgr.deleteDomain(id, cleanup)){ if(_domainMgr.deleteDomain(id, cleanup)){
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
@ -518,8 +500,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId()); s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while deleting domain :"+domainUUID+" in Region: "+region.getId()); s_logger.error("Error while deleting domain :"+domainUUID+" in Region: "+region.getId());
@ -532,8 +514,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First delete in the Region where domain is created //First delete in the Region where domain is created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; if (RegionsApiUtil.makeAPICall(region, command, params)) {
if (makeAPICall(url)) {
s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId()); s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId());
return true; return true;
} else { } else {
@ -553,34 +534,20 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
throw new InvalidParameterValueException("The specified user doesn't exist in the system"); throw new InvalidParameterValueException("The specified user doesn't exist in the system");
} }
String userUUID = user.getUuid(); String userUUID = user.getUuid();
StringBuffer params = new StringBuffer("/api?command=updateUser");
params.append("&"+ApiConstants.ID+"="+userUUID);
if(cmd.getApiKey() != null){
params.append("&"+ApiConstants.API_KEY+"="+cmd.getApiKey());
}
if(cmd.getEmail() != null){
params.append("&"+ApiConstants.EMAIL+"="+cmd.getEmail());
}
if(cmd.getFirstname() != null){
params.append("&"+ApiConstants.FIRSTNAME+"="+cmd.getFirstname());
}
if(cmd.getLastname() != null){
params.append("&"+ApiConstants.LASTNAME+"="+cmd.getLastname());
}
if(cmd.getPassword() != null){
params.append("&"+ApiConstants.PASSWORD+"="+cmd.getPassword());
}
if(cmd.getSecretKey() != null){
params.append("&"+ApiConstants.SECRET_KEY+"="+cmd.getSecretKey());
}
if(cmd.getTimezone() != null){
params.append("&"+ApiConstants.TIMEZONE+"="+cmd.getTimezone());
}
if(cmd.getUsername() != null){
params.append("&"+ApiConstants.USERNAME+"="+cmd.getUsername());
}
long regionId = user.getRegionId(); String command = "updateUser";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.ID, userUUID));
params.add(new NameValuePair(ApiConstants.API_KEY, cmd.getApiKey()));
params.add(new NameValuePair(ApiConstants.EMAIL, cmd.getEmail()));
params.add(new NameValuePair(ApiConstants.FIRSTNAME, cmd.getFirstname()));
params.add(new NameValuePair(ApiConstants.LASTNAME, cmd.getLastname()));
params.add(new NameValuePair(ApiConstants.PASSWORD, cmd.getPassword()));
params.add(new NameValuePair(ApiConstants.SECRET_KEY, cmd.getSecretKey()));
params.add(new NameValuePair(ApiConstants.TIMEZONE, cmd.getTimezone()));
params.add(new NameValuePair(ApiConstants.USERNAME, cmd.getUsername()));
int regionId = user.getRegionId();
if(getId() == regionId){ if(getId() == regionId){
UserAccount updateUser = _accountMgr.updateUser(cmd); UserAccount updateUser = _accountMgr.updateUser(cmd);
if(updateUser != null){ if(updateUser != null){
@ -589,8 +556,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully updated user :"+userUUID+" in Region: "+region.getId()); s_logger.debug("Successfully updated user :"+userUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while updating user :"+userUUID+" in Region: "+region.getId()); s_logger.error("Error while updating user :"+userUUID+" in Region: "+region.getId());
@ -601,15 +568,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First update in the Region where user was created //First update in the Region where user was created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; UserAccount updateUser = RegionsApiUtil.makeUserAccountAPICall(region, command, params);
if (makeAPICall(url)) { if (updateUser != null) {
s_logger.debug("Successfully updated user :"+userUUID+" in source Region: "+region.getId()); s_logger.debug("Successfully updated user :"+userUUID+" in source Region: "+region.getId());
//return object return updateUser;
return null;
} else { } else {
s_logger.error("Error while updating user :"+userUUID+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while updating user :"+userUUID+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
@ -622,26 +586,24 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); throw new InvalidParameterValueException("The specified domain doesn't exist in the system");
} }
String domainUUID = domain.getUuid(); String domainUUID = domain.getUuid();
StringBuffer params = new StringBuffer("/api?command=updateDomain");
params.append("&"+ApiConstants.ID+"="+domainUUID);
if(cmd.getDomainName() != null){
params.append("&"+ApiConstants.NAME+"="+cmd.getDomainName());
}
if(cmd.getNetworkDomain() != null){
params.append("&"+ApiConstants.NETWORK_DOMAIN+"="+cmd.getNetworkDomain());
}
long regionId = domain.getRegionId(); String command = "updateDomain";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.ID, domainUUID));
params.add(new NameValuePair(ApiConstants.NAME, cmd.getDomainName()));
params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, cmd.getNetworkDomain()));
int regionId = domain.getRegionId();
if(getId() == regionId){ if(getId() == regionId){
Domain updatedDomain = _mgmtSrvr.updateDomain(cmd); Domain updatedDomain = _domainMgr.updateDomain(cmd);
if(updatedDomain != null){ if(updatedDomain != null){
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
for (Region region : regions){ for (Region region : regions){
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully updated updatedDomain :"+domainUUID+" in Region: "+region.getId()); s_logger.debug("Successfully updated updatedDomain :"+domainUUID+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while updating updatedDomain :"+domainUUID+" in Region: "+region.getId()); s_logger.error("Error while updating updatedDomain :"+domainUUID+" in Region: "+region.getId());
@ -652,15 +614,14 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First update in the Region where domain was created //First update in the Region where domain was created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; RegionDomain updatedDomain = RegionsApiUtil.makeDomainAPICall(region, command, params);
if (makeAPICall(url)) { if (updatedDomain != null) {
Long parentId = _identityDao.getIdentityId("domain", updatedDomain.getParentUuid());
updatedDomain.setParent(parentId);
s_logger.debug("Successfully updated user :"+domainUUID+" in source Region: "+region.getId()); s_logger.debug("Successfully updated user :"+domainUUID+" in source Region: "+region.getId());
//return object return (DomainVO)updatedDomain;
return null;
} else { } else {
s_logger.error("Error while updating user :"+domainUUID+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while updating user :"+domainUUID+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
@ -671,8 +632,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if (user == null || user.getRemoved() != null) { if (user == null || user.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find active user by id " + userId); throw new InvalidParameterValueException("Unable to find active user by id " + userId);
} }
long regionId = user.getRegionId(); int regionId = user.getRegionId();
StringBuffer params = new StringBuffer("/api?command=disableUser&id="+user.getUuid());
String command = "disableUser";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.ID, user.getUuid()));
if(getId() == regionId){ if(getId() == regionId){
UserAccount disabledUser = _accountMgr.disableUser(userId); UserAccount disabledUser = _accountMgr.disableUser(userId);
if(disabledUser != null){ if(disabledUser != null){
@ -681,8 +646,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully disabled user :"+user.getUuid()+" in Region: "+region.getId()); s_logger.debug("Successfully disabled user :"+user.getUuid()+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while disabling user :"+user.getUuid()+" in Region: "+region.getId()); s_logger.error("Error while disabling user :"+user.getUuid()+" in Region: "+region.getId());
@ -693,15 +658,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First disable in the Region where user was created //First disable in the Region where user was created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; UserAccount disabledUser = RegionsApiUtil.makeUserAccountAPICall(region, command, params);
if (makeAPICall(url)) { if (disabledUser != null) {
s_logger.debug("Successfully disabled user :"+user.getUuid()+" in source Region: "+region.getId()); s_logger.debug("Successfully disabled user :"+user.getUuid()+" in source Region: "+region.getId());
//return object return disabledUser;
return null;
} else { } else {
s_logger.error("Error while disabling user :"+user.getUuid()+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while disabling user :"+user.getUuid()+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
@ -712,8 +674,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if (user == null || user.getRemoved() != null) { if (user == null || user.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find active user by id " + userId); throw new InvalidParameterValueException("Unable to find active user by id " + userId);
} }
long regionId = user.getRegionId(); int regionId = user.getRegionId();
StringBuffer params = new StringBuffer("/api?command=enableUser&id="+user.getUuid());
String command = "enableUser";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.ID, user.getUuid()));
if(getId() == regionId){ if(getId() == regionId){
UserAccount enabledUser = _accountMgr.enableUser(userId); UserAccount enabledUser = _accountMgr.enableUser(userId);
if(enabledUser != null){ if(enabledUser != null){
@ -722,8 +688,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
if(region.getId() == getId()){ if(region.getId() == getId()){
continue; continue;
} }
String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true"));
if (makeAPICall(url)) { if (RegionsApiUtil.makeAPICall(region, command, params)) {
s_logger.debug("Successfully enabled user :"+user.getUuid()+" in Region: "+region.getId()); s_logger.debug("Successfully enabled user :"+user.getUuid()+" in Region: "+region.getId());
} else { } else {
s_logger.error("Error while disabling user :"+user.getUuid()+" in Region: "+region.getId()); s_logger.error("Error while disabling user :"+user.getUuid()+" in Region: "+region.getId());
@ -734,15 +700,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
} else { } else {
//First enable in the Region where user was created //First enable in the Region where user was created
Region region = _regionDao.findById(regionId); Region region = _regionDao.findById(regionId);
String url = region.getEndPoint() + params; UserAccount enabledUser = RegionsApiUtil.makeUserAccountAPICall(region, command, params);
if (makeAPICall(url)) { if (enabledUser != null) {
s_logger.debug("Successfully enabled user :"+user.getUuid()+" in source Region: "+region.getId()); s_logger.debug("Successfully enabled user :"+user.getUuid()+" in source Region: "+region.getId());
//return object return enabledUser;
return null;
} else { } else {
s_logger.error("Error while enabling user :"+user.getUuid()+" in source Region: "+region.getId()); throw new CloudRuntimeException("Error while enabling user :"+user.getUuid()+" in source Region: "+region.getId());
//throw exception;
return null;
} }
} }
} }
@ -752,23 +715,18 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
String firstName, String lastName, String email, String timezone, String firstName, String lastName, String email, String timezone,
String accountName, String domainUUId, String userUUID) { String accountName, String domainUUId, String userUUID) {
StringBuffer params = new StringBuffer("/api?command=createUser"); String command = "createUser";
params.append("&"+ApiConstants.USERNAME+"="+userName); List<NameValuePair> params = new ArrayList<NameValuePair>();
params.append("&"+ApiConstants.PASSWORD+"="+password); params.add(new NameValuePair(ApiConstants.USERNAME, userName));
params.append("&"+ApiConstants.FIRSTNAME+"="+firstName); params.add(new NameValuePair(ApiConstants.PASSWORD, password));
params.append("&"+ApiConstants.LASTNAME+"="+lastName); params.add(new NameValuePair(ApiConstants.FIRSTNAME, firstName));
params.append("&"+ApiConstants.EMAIL+"="+email); params.add(new NameValuePair(ApiConstants.LASTNAME, lastName));
if(timezone != null){ params.add(new NameValuePair(ApiConstants.EMAIL, email));
params.append("&"+ApiConstants.TIMEZONE+"="+timezone); params.add(new NameValuePair(ApiConstants.TIMEZONE, timezone));
} params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName));
if(accountName != null){ params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domainUUId));
params.append("&"+ApiConstants.ACCOUNT+"="+accountName); params.add(new NameValuePair(ApiConstants.USER_ID, userUUID));
} params.add(new NameValuePair(ApiConstants.REGION_ID, ""+getId()));
if(domainUUId != null){
params.append("&"+ApiConstants.DOMAIN_ID+"="+domainUUId); //use UUID
}
params.append("&"+ApiConstants.USER_ID+"="+userUUID);
params.append("&"+ApiConstants.REGION_ID+"="+getId());
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
for (Region region : regions){ for (Region region : regions){
@ -776,13 +734,10 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
continue; continue;
} }
s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId());
String url = region.getEndPoint() + params; if (RegionsApiUtil.makeAPICall(region, command, params)) {
if (makeAPICall(url)) {
s_logger.debug("Successfully added user :"+userName+" to Region: "+region.getId()); s_logger.debug("Successfully added user :"+userName+" to Region: "+region.getId());
} else { } else {
s_logger.error("Error while Adding user :"+userName+" to Region: "+region.getId()); s_logger.error("Error while Adding user :"+userName+" to Region: "+region.getId());
//Send User delete to all Regions where account is added successfully
break;
} }
} }
return; return;
@ -790,21 +745,19 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
@Override @Override
public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid) { public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid) {
StringBuffer params = new StringBuffer("/api?command=createDomain");
params.append("&ApiConstants.NAME="+name); String command = "createDomain";
String parentUUID = null; List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.NAME, name));
if(parentId != null){ if(parentId != null){
DomainVO domain = _domainDao.findById(parentId); DomainVO domain = _domainDao.findById(parentId);
if(domain != null){ if(domain != null){
parentUUID = domain.getUuid(); params.add(new NameValuePair(ApiConstants.PARENT_DOMAIN_ID, domain.getUuid()));
params.append("&ApiConstants.PARENT_DOMAIN_ID="+parentUUID);
} }
} }
if(networkDomain != null){ params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain));
params.append("&ApiConstants.NETWORK_DOMAIN="+networkDomain); params.add(new NameValuePair(ApiConstants.DOMAIN_ID, uuid));
} params.add(new NameValuePair(ApiConstants.REGION_ID, ""+getId()));
params.append("&ApiConstants.DOMAIN_ID="+uuid);
params.append("&ApiConstants.REGION_ID="+getId());
List<RegionVO> regions = _regionDao.listAll(); List<RegionVO> regions = _regionDao.listAll();
for (Region region : regions){ for (Region region : regions){
@ -812,17 +765,157 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{
continue; continue;
} }
s_logger.debug("Adding domain :"+name+" to Region: "+region.getId()); s_logger.debug("Adding domain :"+name+" to Region: "+region.getId());
String url = region.getEndPoint() + params; if (RegionsApiUtil.makeAPICall(region, command, params)) {
if (makeAPICall(url)) {
s_logger.debug("Successfully added domain :"+name+" to Region: "+region.getId()); s_logger.debug("Successfully added domain :"+name+" to Region: "+region.getId());
} else { } else {
s_logger.error("Error while Adding domain :"+name+" to Region: "+region.getId()); s_logger.error("Error while Adding domain :"+name+" to Region: "+region.getId());
//Send User delete to all Regions where account is added successfully
break;
} }
} }
return; return;
} }
@Override
public UserAccount getUserAccount(String username, Long domainId) {
UserAccount user = _userAccountDao.getUserAccount(username, domainId);
if(user != null){
return user;
} else {
DomainVO domain = _domainDao.findById(domainId);
if(domain == null){
//Lookup Domain
s_logger.debug("Domain with Id :"+domainId+" doesn't exist");
}
String command = "findUser";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.USERNAME, username));
params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid()));
RegionUser regionuser = null;
List<RegionVO> regions = _regionDao.listAll();
boolean sourceCheck = false;
for (Region region : regions){
if(region.getId() == getId()){
continue;
}
s_logger.debug("Looking up user :"+username+" in Region: "+region.getId());
regionuser = RegionsApiUtil.makeUserAPICall(region, command, params);
if(regionuser != null){
s_logger.debug("Found user :"+username+" in Region: "+region.getId());
if(regionuser.getRegionId() != region.getId()){
sourceCheck = true;
}
break;
}
}
if(regionuser == null){
s_logger.debug("User :"+username+" not found in any Region");
return null;
}
if(sourceCheck){
if(regionuser.getRegionId() == getId()){
s_logger.debug("Current Region is the source Region for found user: " +username+ ". Ignoring..");
return null;
}
s_logger.debug("Verifying user: " +username+ " in source Region: "+regionuser.getRegionId());
//Verify user in source Region
Region sourceRegion = _regionDao.findById(regionuser.getRegionId());
if(sourceRegion != null){
regionuser = RegionsApiUtil.makeUserAPICall(sourceRegion, command, params);
if(regionuser != null && sourceRegion.getId() == regionuser.getRegionId()){
s_logger.debug("Found User :"+username+" in Source Region: "+sourceRegion.getId()+" Add to local Region");
} else {
s_logger.debug("User :"+username+" not found in Source Region: "+sourceRegion.getId());
return null;
}
} else {
s_logger.debug("Source Region :"+regionuser.getRegionId()+" not found");
return null;
}
}
if(regionuser != null){
Long accountId = _identityDao.getIdentityId("account", regionuser.getAccountuuid());
if(accountId == null){
//Lookup Account
}
regionuser.setAccountId(accountId);
UserVO newuser = (UserVO)regionuser;
_userDao.persist(newuser);
return _userAccountDao.getUserAccount(username, domainId);
}
return null;
}
}
@Override
public DomainVO findDomainByPath(String domainPath) {
DomainVO domain = (DomainVO)_domainMgr.findDomainByPath(domainPath);
if(domain != null){
return domain;
} else {
String command = "findDomain";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair(ApiConstants.DOMAIN, domainPath));
boolean sourceCheck = false;
RegionDomain regiondomain = null;
List<RegionVO> regions = _regionDao.listAll();
for (Region region : regions){
if(region.getId() == getId()){
continue;
}
s_logger.debug("Looking up domain :"+domainPath+" in Region: "+region.getId());
regiondomain = RegionsApiUtil.makeDomainAPICall(region, command, params);
if(regiondomain != null){
s_logger.debug("Found domain :"+domainPath+" in Region: "+region.getId());
if(regiondomain.getRegionId() != region.getId()){
sourceCheck = true;
}
break;
}
}
if(regiondomain == null){
s_logger.debug("Domain :"+domainPath+" not found in any Region");
return null;
}
if(sourceCheck){
if(regiondomain.getRegionId() == getId()){
s_logger.debug("Current Region is the source Region for found domain: " +domainPath+ ". Ignoring..");
return null;
}
s_logger.debug("Verifying domain: " +domainPath+ " in source Region: "+regiondomain.getRegionId());
//Verify user in source Region
Region sourceRegion = _regionDao.findById(regiondomain.getRegionId());
if(sourceRegion != null){
DomainVO sourceDomain = RegionsApiUtil.makeDomainAPICall(sourceRegion, command, params);
if(sourceDomain != null && sourceRegion.getId() == sourceDomain.getRegionId()){
s_logger.debug("Found Domain :"+domainPath+" in Source Region: "+sourceRegion.getId()+" Add to local Region");
} else {
s_logger.debug("Domain :"+domainPath+" not found in Source Region: "+sourceRegion.getId());
return null;
}
} else {
s_logger.debug("Source Region :"+regiondomain.getRegionId()+" not found");
return null;
}
}
if(regiondomain != null){
Long parentId = _identityDao.getIdentityId("domain", regiondomain.getParentUuid());
if(parentId == null){
//lookup ParentDomain
}
regiondomain.setParent(parentId);
regiondomain.setState(Domain.State.Active);
_domainDao.persist((DomainVO)regiondomain);
}
return (DomainVO)_domainMgr.findDomainByPath(domainPath);
}
}
} }

View File

@ -0,0 +1,76 @@
// 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.region;
import com.cloud.user.UserVO;
public class RegionUser extends UserVO {
String accountUuid;
String created;
String account;
String accounttype;
String domainid;
String domain;
public RegionUser() {
}
public String getAccountuuid() {
return accountUuid;
}
public void setAccountuuid(String accountUuid) {
this.accountUuid = accountUuid;
}
public void setCreated(String created) {
this.created = created;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getAccounttype() {
return accounttype;
}
public void setAccounttype(String accounttype) {
this.accounttype = accounttype;
}
public String getDomainid() {
return domainid;
}
public void setDomainid(String domainid) {
this.domainid = domainid;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}

View File

@ -20,12 +20,9 @@ import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
import com.cloud.region.Region;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
@Entity @Entity
@ -34,7 +31,7 @@ public class RegionVO implements Region{
@Id @Id
@Column(name="id") @Column(name="id")
private long id; private int id;
@Column(name="name") @Column(name="name")
private String name; private String name;
@ -42,9 +39,11 @@ public class RegionVO implements Region{
@Column(name="end_point") @Column(name="end_point")
private String endPoint; private String endPoint;
@Column(name="status") @Column(name="api_key")
@Enumerated(value=EnumType.STRING) private String apiKey;
private Region.State status;
@Column(name="secret_key")
private String secretKey;
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name=GenericDao.REMOVED_COLUMN)
private Date removed; private Date removed;
@ -52,14 +51,15 @@ public class RegionVO implements Region{
public RegionVO() { public RegionVO() {
} }
public RegionVO(long id, String name, String endPoint) { public RegionVO(int id, String name, String endPoint, String apiKey, String secretKey) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.endPoint = endPoint; this.endPoint = endPoint;
this.status = Region.State.Down; this.apiKey = apiKey;
this.secretKey = secretKey;
} }
public long getId() { public int getId() {
return id; return id;
} }
@ -71,14 +71,6 @@ public class RegionVO implements Region{
this.name = name; this.name = name;
} }
public Region.State getStatus() {
return status;
}
public void setStatus(Region.State status) {
this.status = status;
}
public Date getRemoved() { public Date getRemoved() {
return removed; return removed;
} }
@ -91,5 +83,21 @@ public class RegionVO implements Region{
this.endPoint = endPoint; this.endPoint = endPoint;
} }
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
} }

View File

@ -0,0 +1,285 @@
// 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.region;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.UserAccount;
import com.cloud.user.UserAccountVO;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class RegionsApiUtil {
public static final Logger s_logger = Logger.getLogger(RegionsApiUtil.class);
protected static boolean makeAPICall(Region region, String command, List<NameValuePair> params){
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if( client.executeMethod(method) == 200){
return true;
} else {
return false;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return false;
} catch (IOException e) {
s_logger.error(e.getMessage());
return false;
}
}
protected static RegionAccount makeAccountAPICall(Region region, String command, List<NameValuePair> params){
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if( client.executeMethod(method) == 200){
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
xstream.alias("account", RegionAccount.class);
xstream.alias("user", RegionUser.class);
xstream.aliasField("id", RegionAccount.class, "uuid");
xstream.aliasField("name", RegionAccount.class, "accountName");
xstream.aliasField("accounttype", RegionAccount.class, "type");
xstream.aliasField("domainid", RegionAccount.class, "domainUuid");
xstream.aliasField("networkdomain", RegionAccount.class, "networkDomain");
xstream.aliasField("id", RegionUser.class, "uuid");
xstream.aliasField("accountId", RegionUser.class, "accountUuid");
ObjectInputStream in = xstream.createObjectInputStream(is);
return (RegionAccount)in.readObject();
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
} catch (ClassNotFoundException e) {
s_logger.error(e.getMessage());
return null;
}
}
protected static RegionDomain makeDomainAPICall(Region region, String command, List<NameValuePair> params){
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if( client.executeMethod(method) == 200){
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
xstream.alias("domain", RegionDomain.class);
xstream.aliasField("id", RegionDomain.class, "uuid");
xstream.aliasField("parentdomainid", RegionDomain.class, "parentUuid");
xstream.aliasField("networkdomain", DomainVO.class, "networkDomain");
ObjectInputStream in = xstream.createObjectInputStream(is);
return (RegionDomain)in.readObject();
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
} catch (ClassNotFoundException e) {
s_logger.error(e.getMessage());
return null;
}
}
protected static UserAccount makeUserAccountAPICall(Region region, String command, List<NameValuePair> params){
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if( client.executeMethod(method) == 200){
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
xstream.alias("useraccount", UserAccountVO.class);
xstream.aliasField("id", UserAccountVO.class, "uuid");
ObjectInputStream in = xstream.createObjectInputStream(is);
return (UserAccountVO)in.readObject();
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
} catch (ClassNotFoundException e) {
s_logger.error(e.getMessage());
return null;
}
}
protected static RegionUser makeUserAPICall(Region region, String command, List<NameValuePair> params){
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if( client.executeMethod(method) == 200){
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
xstream.alias("finduserresponse", FindUserResponse.class);
xstream.alias("user", RegionUser.class);
xstream.aliasField("id", RegionUser.class, "uuid");
xstream.aliasField("accountId", RegionUser.class, "accountUuid");
xstream.registerConverter(new ISO8601DateConverter());
FindUserResponse response = (FindUserResponse)xstream.fromXML(is);
return response.getUser();
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
}
}
private static String buildParams(String command, List<NameValuePair> params) {
StringBuffer paramString = new StringBuffer("command="+command);
Iterator<NameValuePair> iter = params.iterator();
try {
while(iter.hasNext()){
NameValuePair param = iter.next();
if(param.getValue() != null && !(param.getValue().isEmpty())){
paramString.append("&"+param.getName()+"="+URLEncoder.encode(param.getValue(), "UTF-8"));
}
}
}
catch (UnsupportedEncodingException e) {
s_logger.error(e.getMessage());
return null;
}
return paramString.toString();
}
private static String buildUrl(String apiParams, Region region) {
String apiKey = region.getApiKey();
String secretKey = region.getSecretKey();
if (apiKey == null || secretKey == null) {
return region.getEndPoint() +"?"+ apiParams;
}
String encodedApiKey;
try {
encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
List<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey=" + encodedApiKey.toLowerCase());
StringTokenizer st = new StringTokenizer(apiParams, "&");
String url = null;
boolean first = true;
while (st.hasMoreTokens()) {
String paramValue = st.nextToken();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length());
if (first) {
url = param + "=" + value;
first = false;
} else {
url = url + "&" + param + "=" + value;
}
sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase());
}
Collections.sort(sortedParams);
//Construct the sorted URL and sign and URL encode the sorted URL with your secret key
String sortedUrl = null;
first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = region.getEndPoint() +"?"+apiParams+ "&apiKey=" + apiKey + "&signature=" + encodedSignature;
return finalUrl;
} catch (UnsupportedEncodingException e) {
s_logger.error(e.getMessage());
return null;
}
}
/**
* 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result
*
* @param request
* @param key
* @return
*/
private static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8");
} catch (Exception ex) {
s_logger.error(ex.getMessage());
return null;
}
}
}

View File

@ -19,5 +19,5 @@ package com.cloud.region.dao;
import com.cloud.region.RegionVO; import com.cloud.region.RegionVO;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
public interface RegionDao extends GenericDao<RegionVO, Long> { public interface RegionDao extends GenericDao<RegionVO, Integer> {
} }

View File

@ -24,7 +24,7 @@ import com.cloud.region.RegionVO;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
@Local(value={RegionDao.class}) @Local(value={RegionDao.class})
public class RegionDaoImpl extends GenericDaoBase<RegionVO, Long> implements RegionDao { public class RegionDaoImpl extends GenericDaoBase<RegionVO, Integer> implements RegionDao {
private static final Logger s_logger = Logger.getLogger(RegionDaoImpl.class); private static final Logger s_logger = Logger.getLogger(RegionDaoImpl.class);
public RegionDaoImpl(){ public RegionDaoImpl(){

View File

@ -85,6 +85,8 @@ import com.cloud.offerings.NetworkOfferingServiceMapVO;
import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.region.RegionVO;
import com.cloud.region.dao.RegionDao;
import com.cloud.service.ServiceOfferingVO; import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.DiskOfferingVO;
@ -123,6 +125,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
private final ResourceCountDao _resourceCountDao; private final ResourceCountDao _resourceCountDao;
private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao; private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao;
private final IdentityDao _identityDao; private final IdentityDao _identityDao;
private final RegionDao _regionDao;
public ConfigurationServerImpl() { public ConfigurationServerImpl() {
ComponentLocator locator = ComponentLocator.getLocator(Name); ComponentLocator locator = ComponentLocator.getLocator(Name);
@ -140,6 +143,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_resourceCountDao = locator.getDao(ResourceCountDao.class); _resourceCountDao = locator.getDao(ResourceCountDao.class);
_ntwkOfferingServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class); _ntwkOfferingServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class);
_identityDao = locator.getDao(IdentityDao.class); _identityDao = locator.getDao(IdentityDao.class);
_regionDao = locator.getDao(RegionDao.class);
} }
@Override @Override
@ -228,6 +232,8 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// Create default networks // Create default networks
createDefaultNetworks(); createDefaultNetworks();
createDefaultRegion();
// Create userIpAddress ranges // Create userIpAddress ranges
// Update existing vlans with networkId // Update existing vlans with networkId
@ -324,6 +330,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
@DB @DB
protected void saveUser() { protected void saveUser() {
//ToDo: Add regionId to default users and accounts
// insert system account // insert system account
String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')"; String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')";
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -1273,4 +1280,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
return svcProviders; return svcProviders;
} }
private void createDefaultRegion(){
//Get Region name and URL from db.properties
_regionDao.persist(new RegionVO(_regionDao.getRegionId(), "Local", "http://localhost:8080/client/api", "", ""));
//Default account, user and domain should share same uuid
}
} }

View File

@ -1969,99 +1969,6 @@ public class ManagementServerImpl implements ManagementServer {
return new Pair<String, Integer>(null, -1); return new Pair<String, Integer>(null, -1);
} }
@Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
@DB
public DomainVO updateDomain(UpdateDomainCmd cmd) {
Long domainId = cmd.getId();
String domainName = cmd.getDomainName();
String networkDomain = cmd.getNetworkDomain();
// check if domain exists in the system
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
ex.addProxyObject(domain, domainId, "domainId");
throw ex;
} else if (domain.getParent() == null && domainName != null) {
// check if domain is ROOT domain - and deny to edit it with the new name
throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
}
// check permissions
Account caller = UserContext.current().getCaller();
_accountMgr.checkAccess(caller, domain);
// domain name is unique in the cloud
if (domainName != null) {
SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
List<DomainVO> domains = _domainDao.search(sc, null);
boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
if (!domains.isEmpty() && !sameDomain) {
InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
ex.addProxyObject(domain, domainId, "domainId");
throw ex;
}
}
// validate network domain
if (networkDomain != null && !networkDomain.isEmpty()) {
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException(
"Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
Transaction txn = Transaction.currentTxn();
txn.start();
if (domainName != null) {
String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
updateDomainChildren(domain, updatedDomainPath);
domain.setName(domainName);
domain.setPath(updatedDomainPath);
}
if (networkDomain != null) {
if (networkDomain.isEmpty()) {
domain.setNetworkDomain(null);
} else {
domain.setNetworkDomain(networkDomain);
}
}
_domainDao.update(domainId, domain);
txn.commit();
return _domainDao.findById(domainId);
}
private String getUpdatedDomainPath(String oldPath, String newName) {
String[] tokenizedPath = oldPath.split("/");
tokenizedPath[tokenizedPath.length - 1] = newName;
StringBuilder finalPath = new StringBuilder();
for (String token : tokenizedPath) {
finalPath.append(token);
finalPath.append("/");
}
return finalPath.toString();
}
private void updateDomainChildren(DomainVO domain, String updatedDomainPrefix) {
List<DomainVO> domainChildren = _domainDao.findAllChildren(domain.getPath(), domain.getId());
// for each child, update the path
for (DomainVO dom : domainChildren) {
dom.setPath(dom.getPath().replaceFirst(domain.getPath(), updatedDomainPrefix));
_domainDao.update(dom.getId(), dom);
}
}
@Override @Override
public List<? extends Alert> searchForAlerts(ListAlertsCmd cmd) { public List<? extends Alert> searchForAlerts(ListAlertsCmd cmd) {
Filter searchFilter = new Filter(AlertVO.class, "lastSent", false, cmd.getStartIndex(), cmd.getPageSizeVal()); Filter searchFilter = new Filter(AlertVO.class, "lastSent", false, cmd.getStartIndex(), cmd.getPageSizeVal());

View File

@ -49,7 +49,7 @@ public interface AccountManager extends AccountService {
Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId); Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId);
Account createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details, String uuid, long regionId); Account createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details, String uuid, int regionId);
UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone); UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone);

View File

@ -759,7 +759,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
@DB @DB
@ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account") @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account")
public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain,
Map<String, String> details, String accountUUID, String userUUID, Long regionId) { Map<String, String> details, String accountUUID, String userUUID, Integer regionId) {
if (accountName == null) { if (accountName == null) {
accountName = userName; accountName = userName;
@ -849,7 +849,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
@Override @Override
public UserVO createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Long regionId) { public UserVO createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Integer regionId) {
// default domain to ROOT if not specified // default domain to ROOT if not specified
if (domainId == null) { if (domainId == null) {
@ -1629,7 +1629,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
@Override @Override
@DB @DB
public AccountVO createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details, String uuid, long regionId) { public AccountVO createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details, String uuid, int regionId) {
// Validate domain // Validate domain
Domain domain = _domainMgr.getDomain(domainId); Domain domain = _domainMgr.getDomain(domainId);
if (domain == null) { if (domain == null) {
@ -1709,7 +1709,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} }
//ToDo Add events?? //ToDo Add events??
public UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone, String uuid, long regionId) { public UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone, String uuid, int regionId) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone); s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone);
} }
@ -2377,4 +2377,19 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
public UserAccount getUserByApiKey(String apiKey) { public UserAccount getUserByApiKey(String apiKey) {
return _userAccountDao.getUserByApiKey(apiKey); return _userAccountDao.getUserByApiKey(apiKey);
} }
@Override
public User findUser(String username, Long domainId) {
UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId);
User user = _userDao.findById(userAccount.getId());
if(user == null){
throw new InvalidParameterValueException("Unable to find user by name: "+username);
}
return user;
}
@Override
public Account findAccount(Long id) {
return _accountDao.findById(id);
}
} }

View File

@ -25,16 +25,7 @@ import com.cloud.domain.DomainVO;
public interface DomainManager extends DomainService { public interface DomainManager extends DomainService {
Set<Long> getDomainChildrenIds(String parentDomainPath); Set<Long> getDomainChildrenIds(String parentDomainPath);
Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Long regionId); Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Integer regionId);
/**
* find the domain by its path
*
* @param domainPath
* the path to use to lookup a domain
* @return domainVO the domain with the matching path, or null if no domain with the given path exists
*/
DomainVO findDomainByPath(String domainPath);
Set<Long> getDomainParentIds(long domainId); Set<Long> getDomainParentIds(long domainId);

View File

@ -28,6 +28,7 @@ import org.apache.log4j.Logger;
import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainChildrenCmd;
import com.cloud.api.commands.ListDomainsCmd; import com.cloud.api.commands.ListDomainsCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.ResourceLimit;
import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.domain.Domain; import com.cloud.domain.Domain;
@ -131,7 +132,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain") @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain")
public Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID, Long regionId) { public Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID, Integer regionId) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
if (parentId == null) { if (parentId == null) {
@ -155,7 +156,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager
@Override @Override
@DB @DB
public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Long regionId) { public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Integer regionId) {
// Verify network domain // Verify network domain
if (networkDomain != null) { if (networkDomain != null) {
if (!NetUtils.verifyDomainName(networkDomain)) { if (!NetUtils.verifyDomainName(networkDomain)) {
@ -483,4 +484,97 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager
return _domainDao.search(sc, searchFilter); return _domainDao.search(sc, searchFilter);
} }
@Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
@DB
public DomainVO updateDomain(UpdateDomainCmd cmd) {
Long domainId = cmd.getId();
String domainName = cmd.getDomainName();
String networkDomain = cmd.getNetworkDomain();
// check if domain exists in the system
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
ex.addProxyObject(domain, domainId, "domainId");
throw ex;
} else if (domain.getParent() == null && domainName != null) {
// check if domain is ROOT domain - and deny to edit it with the new name
throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
}
// check permissions
Account caller = UserContext.current().getCaller();
_accountMgr.checkAccess(caller, domain);
// domain name is unique in the cloud
if (domainName != null) {
SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
List<DomainVO> domains = _domainDao.search(sc, null);
boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
if (!domains.isEmpty() && !sameDomain) {
InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
ex.addProxyObject(domain, domainId, "domainId");
throw ex;
}
}
// validate network domain
if (networkDomain != null && !networkDomain.isEmpty()) {
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException(
"Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
Transaction txn = Transaction.currentTxn();
txn.start();
if (domainName != null) {
String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
updateDomainChildren(domain, updatedDomainPath);
domain.setName(domainName);
domain.setPath(updatedDomainPath);
}
if (networkDomain != null) {
if (networkDomain.isEmpty()) {
domain.setNetworkDomain(null);
} else {
domain.setNetworkDomain(networkDomain);
}
}
_domainDao.update(domainId, domain);
txn.commit();
return _domainDao.findById(domainId);
}
private String getUpdatedDomainPath(String oldPath, String newName) {
String[] tokenizedPath = oldPath.split("/");
tokenizedPath[tokenizedPath.length - 1] = newName;
StringBuilder finalPath = new StringBuilder();
for (String token : tokenizedPath) {
finalPath.append(token);
finalPath.append("/");
}
return finalPath.toString();
}
private void updateDomainChildren(DomainVO domain, String updatedDomainPrefix) {
List<DomainVO> domainChildren = _domainDao.findAllChildren(domain.getPath(), domain.getId());
// for each child, update the path
for (DomainVO dom : domainChildren) {
dom.setPath(dom.getPath().replaceFirst(domain.getPath(), updatedDomainPrefix));
_domainDao.update(dom.getId(), dom);
}
}
} }

View File

@ -32,7 +32,6 @@ import com.cloud.user.User;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;

View File

@ -62,4 +62,5 @@ public class UserAccountDaoImpl extends GenericDaoBase<UserAccountVO, Long> impl
sc.setParameters("apiKey",apiKey); sc.setParameters("apiKey",apiKey);
return findOneBy(sc); return findOneBy(sc);
} }
} }

View File

@ -20,7 +20,9 @@ import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import com.cloud.region.RegionManager;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
@ -35,7 +37,6 @@ public class UserDaoImpl extends GenericDaoBase<UserVO, Long> implements UserDao
protected SearchBuilder<UserVO> AccountIdSearch; protected SearchBuilder<UserVO> AccountIdSearch;
protected SearchBuilder<UserVO> SecretKeySearch; protected SearchBuilder<UserVO> SecretKeySearch;
protected SearchBuilder<UserVO> RegistrationTokenSearch; protected SearchBuilder<UserVO> RegistrationTokenSearch;
private final long _regionId = 1;
protected UserDaoImpl () { protected UserDaoImpl () {
UsernameSearch = createSearchBuilder(); UsernameSearch = createSearchBuilder();
@ -125,10 +126,4 @@ public class UserDaoImpl extends GenericDaoBase<UserVO, Long> implements UserDao
return listBy(sc); return listBy(sc);
} }
@Override
@DB
public UserVO persist(UserVO user) {
user.setRegionId(_regionId);
return super.persist(user);
}
} }

View File

@ -228,25 +228,25 @@ public class TestAsyncJobManager extends ComponentTestCase {
getRandomMilliseconds(1, 100); getRandomMilliseconds(1, 100);
DomainDao domainDao = new DomainDaoImpl(); DomainDao domainDao = new DomainDaoImpl();
DomainVO domain1 = new DomainVO("d1", 2L, 1L, null); DomainVO domain1 = new DomainVO("d1", 2L, 1L, null, 1);
domainDao.create(domain1); domainDao.create(domain1);
DomainVO domain2 = new DomainVO("d2", 2L, 1L, null); DomainVO domain2 = new DomainVO("d2", 2L, 1L, null, 1);
domainDao.create(domain2); domainDao.create(domain2);
DomainVO domain3 = new DomainVO("d3", 2L, 1L, null); DomainVO domain3 = new DomainVO("d3", 2L, 1L, null, 1);
domainDao.create(domain3); domainDao.create(domain3);
DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null); DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null, 1);
domainDao.create(domain11); domainDao.create(domain11);
domainDao.remove(domain11.getId()); domainDao.remove(domain11.getId());
DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null); DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null, 1);
domainDao.create(domain12); domainDao.create(domain12);
domainDao.remove(domain3.getId()); domainDao.remove(domain3.getId());
DomainVO domain4 = new DomainVO("d4", 2L, 1L, null); DomainVO domain4 = new DomainVO("d4", 2L, 1L, null, 1);
domainDao.create(domain4); domainDao.create(domain4);
} }
} }

View File

@ -0,0 +1,198 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network.security;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd;
import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;
import com.cloud.api.commands.CreateSecurityGroupCmd;
import com.cloud.api.commands.DeleteSecurityGroupCmd;
import com.cloud.api.commands.ListSecurityGroupsCmd;
import com.cloud.api.commands.RevokeSecurityGroupEgressCmd;
import com.cloud.api.commands.RevokeSecurityGroupIngressCmd;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Manager;
import com.cloud.utils.fsm.StateListener;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
@Local(value = { SecurityGroupManager.class, SecurityGroupService.class })
public class MockSecurityGroupManagerImpl implements SecurityGroupManager, SecurityGroupService, Manager, StateListener<State, VirtualMachine.Event, VirtualMachine> {
@Override
public boolean preStateTransitionEvent(State oldState, Event event,
State newState, VirtualMachine vo, boolean status, Object opaque) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean postStateTransitionEvent(State oldState, Event event,
State newState, VirtualMachine vo, boolean status, Object opaque) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return false;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public SecurityGroup createSecurityGroup(CreateSecurityGroupCmd command)
throws PermissionDeniedException, InvalidParameterValueException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean revokeSecurityGroupEgress(RevokeSecurityGroupEgressCmd cmd) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd)
throws ResourceInUseException {
// TODO Auto-generated method stub
return false;
}
@Override
public List<? extends SecurityGroupRules> searchForSecurityGroupRules(
ListSecurityGroupsCmd cmd) throws PermissionDeniedException,
InvalidParameterValueException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<? extends SecurityRule> authorizeSecurityGroupIngress(
AuthorizeSecurityGroupIngressCmd cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<? extends SecurityRule> authorizeSecurityGroupEgress(
AuthorizeSecurityGroupEgressCmd cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public SecurityGroupVO createSecurityGroup(String name, String description,
Long domainId, Long accountId, String accountName) {
// TODO Auto-generated method stub
return null;
}
@Override
public SecurityGroupVO createDefaultSecurityGroup(Long accountId) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean addInstanceToGroups(Long userVmId, List<Long> groups) {
// TODO Auto-generated method stub
return false;
}
@Override
public void removeInstanceFromGroups(long userVmId) {
// TODO Auto-generated method stub
}
@Override
public void fullSync(long agentId,
HashMap<String, Pair<Long, Long>> newGroupStates) {
// TODO Auto-generated method stub
}
@Override
public String getSecurityGroupsNamesForVm(long vmId) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<SecurityGroupVO> getSecurityGroupsForVm(long vmId) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isVmSecurityGroupEnabled(Long vmId) {
// TODO Auto-generated method stub
return false;
}
@Override
public SecurityGroup getDefaultSecurityGroup(long accountId) {
// TODO Auto-generated method stub
return null;
}
@Override
public SecurityGroup getSecurityGroup(String name, long accountId) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isVmMappedToDefaultSecurityGroup(long vmId) {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -0,0 +1,679 @@
// 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.storage;
import java.math.BigDecimal;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.CleanupSnapshotBackupCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.ManageSnapshotCommand;
import com.cloud.agent.api.ModifyStoragePoolAnswer;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.DeleteTemplateCommand;
import com.cloud.agent.api.storage.DeleteVolumeCommand;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd;
import com.cloud.api.commands.CreateStoragePoolCmd;
import com.cloud.api.commands.CreateVolumeCmd;
import com.cloud.api.commands.DeletePoolCmd;
import com.cloud.api.commands.ListVolumesCmd;
import com.cloud.api.commands.UpdateStoragePoolCmd;
import com.cloud.api.commands.UploadVolumeCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityManager;
import com.cloud.capacity.CapacityState;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.CheckPointManager;
import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Pod;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DeployDestination;
import com.cloud.domain.Domain;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientStorageCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.network.NetworkManager;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Grouping;
import com.cloud.org.Grouping.AllocationState;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.server.ManagementServer;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.server.StatsCollector;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.Volume.Event;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.allocator.StoragePoolAllocator;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.SnapshotPolicyDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.StoragePoolWorkDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VMTemplateSwiftDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.dao.VolumeHostDao;
import com.cloud.storage.download.DownloadMonitor;
import com.cloud.storage.listener.StoragePoolMonitor;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.storage.snapshot.SnapshotScheduler;
import com.cloud.tags.ResourceTagVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.template.TemplateManager;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.EnumUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.UriUtils;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.ConsoleProxyVO;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.VirtualMachineProfileImpl;
import com.cloud.vm.dao.ConsoleProxyDao;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.SecondaryStorageVmDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value = { StorageManager.class, StorageService.class })
public class MockStorageManagerImpl implements StorageManager, Manager, ClusterManagerListener {
@Override
public StoragePool createPool(CreateStoragePoolCmd cmd)
throws ResourceInUseException, IllegalArgumentException,
UnknownHostException, ResourceUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Volume allocVolume(CreateVolumeCmd cmd)
throws ResourceAllocationException {
// TODO Auto-generated method stub
return null;
}
@Override
public Volume createVolume(CreateVolumeCmd cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean deleteVolume(long volumeId)
throws ConcurrentOperationException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean deletePool(DeletePoolCmd cmd) {
// TODO Auto-generated method stub
return false;
}
@Override
public StoragePool preparePrimaryStorageForMaintenance(Long primaryStorageId)
throws ResourceUnavailableException, InsufficientCapacityException {
// TODO Auto-generated method stub
return null;
}
@Override
public StoragePool cancelPrimaryStorageForMaintenance(
CancelPrimaryStorageMaintenanceCmd cmd)
throws ResourceUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public StoragePool updateStoragePool(UpdateStoragePoolCmd cmd)
throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
@Override
public StoragePool getStoragePool(long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public Volume migrateVolume(Long volumeId, Long storagePoolId)
throws ConcurrentOperationException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<? extends Volume> searchForVolumes(ListVolumesCmd cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public Volume uploadVolume(UploadVolumeCmd cmd)
throws ResourceAllocationException {
// TODO Auto-generated method stub
return null;
}
@Override
public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList,
long selfNodeId) {
// TODO Auto-generated method stub
}
@Override
public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList,
long selfNodeId) {
// TODO Auto-generated method stub
}
@Override
public void onManagementNodeIsolated() {
// TODO Auto-generated method stub
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return false;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean canVmRestartOnAnotherServer(long vmId) {
// TODO Auto-generated method stub
return false;
}
@Override
public Pair<String, String> getAbsoluteIsoPath(long templateId,
long dataCenterId) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getSecondaryStorageURL(long zoneId) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getStoragePoolTags(long poolId) {
// TODO Auto-generated method stub
return null;
}
@Override
public HostVO getSecondaryStorageHost(long zoneId) {
// TODO Auto-generated method stub
return null;
}
@Override
public VMTemplateHostVO findVmTemplateHost(long templateId, StoragePool pool) {
// TODO Auto-generated method stub
return null;
}
@Override
public VolumeVO moveVolume(VolumeVO volume, long destPoolDcId,
Long destPoolPodId, Long destPoolClusterId,
HypervisorType dataDiskHyperType)
throws ConcurrentOperationException {
// TODO Auto-generated method stub
return null;
}
@Override
public VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm,
VMTemplateVO template, DataCenterVO dc, HostPodVO pod,
Long clusterId, ServiceOfferingVO offering,
DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size,
HypervisorType hyperType) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean destroyVolume(VolumeVO volume)
throws ConcurrentOperationException {
// TODO Auto-generated method stub
return false;
}
@Override
public void createCapacityEntry(StoragePoolVO storagePool) {
// TODO Auto-generated method stub
}
@Override
public boolean volumeOnSharedStoragePool(VolumeVO volume) {
// TODO Auto-generated method stub
return false;
}
@Override
public Answer sendToPool(long poolId, Command cmd)
throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Answer sendToPool(StoragePool pool, Command cmd)
throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Answer[] sendToPool(long poolId, Commands cmd)
throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Answer[] sendToPool(StoragePool pool, Commands cmds)
throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Pair<Long, Answer[]> sendToPool(StoragePool pool,
long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid, Commands cmds)
throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Pair<Long, Answer> sendToPool(StoragePool pool,
long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid, Command cmd)
throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean volumeInactive(VolumeVO volume) {
// TODO Auto-generated method stub
return false;
}
@Override
public String getVmNameOnVolume(VolumeVO volume) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isLocalStorageActiveOnHost(Host host) {
// TODO Auto-generated method stub
return false;
}
@Override
public void cleanupStorage(boolean recurring) {
// TODO Auto-generated method stub
}
@Override
public String getPrimaryStorageNameLabel(VolumeVO volume) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends VMInstanceVO> DiskProfile allocateRawVolume(Type type,
String name, DiskOfferingVO offering, Long size, T vm, Account owner) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends VMInstanceVO> DiskProfile allocateTemplatedVolume(
Type type, String name, DiskOfferingVO offering,
VMTemplateVO template, T vm, Account owner) {
// TODO Auto-generated method stub
return null;
}
@Override
public void createCapacityEntry(StoragePoolVO storagePool,
short capacityType, long allocated) {
// TODO Auto-generated method stub
}
@Override
public void prepare(VirtualMachineProfile<? extends VirtualMachine> vm,
DeployDestination dest) throws StorageUnavailableException,
InsufficientStorageCapacityException, ConcurrentOperationException {
// TODO Auto-generated method stub
}
@Override
public void release(VirtualMachineProfile<? extends VMInstanceVO> profile) {
// TODO Auto-generated method stub
}
@Override
public void cleanupVolumes(long vmId) throws ConcurrentOperationException {
// TODO Auto-generated method stub
}
@Override
public void prepareForMigration(
VirtualMachineProfile<? extends VirtualMachine> vm,
DeployDestination dest) {
// TODO Auto-generated method stub
}
@Override
public Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst,
Command cmd) throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId) {
// TODO Auto-generated method stub
return null;
}
@Override
public CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId,
Long podId, Long zoneId) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean createStoragePool(long hostId, StoragePoolVO pool) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean delPoolFromHost(long hostId) {
// TODO Auto-generated method stub
return false;
}
@Override
public HostVO getSecondaryStorageHost(long zoneId, long tmpltId) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<HostVO> getSecondaryStorageHosts(long zoneId) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<StoragePoolVO> ListByDataCenterHypervisor(long datacenterId,
HypervisorType type) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<VMInstanceVO> listByStoragePool(long storagePoolId) {
// TODO Auto-generated method stub
return null;
}
@Override
public StoragePoolVO findLocalStorageOnHost(long hostId) {
// TODO Auto-generated method stub
return null;
}
@Override
public VMTemplateHostVO getTemplateHostRef(long zoneId, long tmpltId,
boolean readyOnly) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean StorageMigration(
VirtualMachineProfile<? extends VirtualMachine> vm,
StoragePool destPool) throws ConcurrentOperationException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean stateTransitTo(Volume vol, Event event)
throws NoTransitionException {
// TODO Auto-generated method stub
return false;
}
@Override
public VolumeVO allocateDuplicateVolume(VolumeVO oldVol, Long templateId) {
// TODO Auto-generated method stub
return null;
}
@Override
public Host updateSecondaryStorage(long secStorageId, String newUrl) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Long> getUpHostsInPool(long poolId) {
// TODO Auto-generated method stub
return null;
}
@Override
public void cleanupSecondaryStorage(boolean recurring) {
// TODO Auto-generated method stub
}
@Override
public VolumeVO copyVolumeFromSecToPrimary(VolumeVO volume,
VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc,
HostPodVO pod, Long clusterId, ServiceOfferingVO offering,
DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size,
HypervisorType hyperType) throws NoTransitionException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getSupportedImageFormatForCluster(Long clusterId) {
// TODO Auto-generated method stub
return null;
}
@Override
public HypervisorType getHypervisorTypeFromFormat(ImageFormat format) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean storagePoolHasEnoughSpace(List<Volume> volume,
StoragePool pool) {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -206,12 +206,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS
return false; return false;
} }
@Override
public UserVO createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId) { public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -280,23 +274,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS
return true; return true;
} }
@Override
public UserAccount createUserAccount(String userName, String password,
String firstName, String lastName, String email, String timezone,
String accountName, short accountType, Long domainId,
String networkDomain, Map<String, String> details) {
// TODO Auto-generated method stub
return null;
}
@Override
public Account createAccount(String accountName, short accountType,
Long domainId, String networkDomain, Map details) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
public List<? extends Account> searchForAccounts(ListAccountsCmd cmd) { public List<? extends Account> searchForAccounts(ListAccountsCmd cmd) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -343,4 +320,42 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS
return null; return null;
} }
@Override
public UserAccount createUserAccount(String userName, String password,
String firstName, String lastName, String email, String timezone,
String accountName, short accountType, Long domainId,
String networkDomain, Map<String, String> details,
String accountUUID, String userUUID, Integer regionId) {
// TODO Auto-generated method stub
return null;
}
@Override
public User createUser(String userName, String password, String firstName,
String lastName, String email, String timeZone, String accountName,
Long domainId, String userUUID, Integer regionId) {
// TODO Auto-generated method stub
return null;
}
@Override
public User findUser(String username, Long domainId) {
// TODO Auto-generated method stub
return null;
}
@Override
public Account findAccount(Long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public Account createAccount(String accountName, short accountType,
Long domainId, String networkDomain, Map details, String uuid,
int regionId) {
// TODO Auto-generated method stub
return null;
}
} }

View File

@ -25,6 +25,7 @@ import javax.naming.ConfigurationException;
import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainChildrenCmd;
import com.cloud.api.commands.ListDomainsCmd; import com.cloud.api.commands.ListDomainsCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.domain.Domain; import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO; import com.cloud.domain.DomainVO;
import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.PermissionDeniedException;
@ -33,12 +34,6 @@ import com.cloud.utils.component.Manager;
@Local(value = { DomainManager.class }) @Local(value = { DomainManager.class })
public class MockDomainManagerImpl implements Manager, DomainManager { public class MockDomainManagerImpl implements Manager, DomainManager {
@Override
public Domain createDomain(String name, Long parentId, String networkDomain) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
public Domain getDomain(long id) { public Domain getDomain(long id) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -77,13 +72,6 @@ public class MockDomainManagerImpl implements Manager, DomainManager {
return null; return null;
} }
@Override
public Domain createDomain(String name, Long parentId, Long ownerId,
String networkDomain) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
public DomainVO findDomainByPath(String domainPath) { public DomainVO findDomainByPath(String domainPath) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -138,4 +126,24 @@ public class MockDomainManagerImpl implements Manager, DomainManager {
return null; return null;
} }
@Override
public Domain createDomain(String name, Long parentId,
String networkDomain, String domainUUID, Integer regionId) {
// TODO Auto-generated method stub
return null;
}
@Override
public Domain updateDomain(UpdateDomainCmd cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public Domain createDomain(String name, Long parentId, Long ownerId,
String networkDomain, String domainUUID, Integer regionId) {
// TODO Auto-generated method stub
return null;
}
} }

View File

@ -16,6 +16,7 @@
// under the License. // under the License.
package com.cloud.vm; package com.cloud.vm;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -194,7 +195,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana
@Override @Override
public List<UserVmVO> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List<Long> permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) { public List<UserVmVO> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List<Long> permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return new ArrayList<UserVmVO>();
} }
@Override @Override

View File

@ -321,8 +321,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi
*/ */
@Override @Override
public Long getDefaultPageSize() { public Long getDefaultPageSize() {
// TODO Auto-generated method stub return 500L;
return null;
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@ -891,7 +891,7 @@ CREATE TABLE `cloud`.`user` (
`timezone` varchar(30) default NULL, `timezone` varchar(30) default NULL,
`registration_token` varchar(255) default NULL, `registration_token` varchar(255) default NULL,
`is_registered` tinyint NOT NULL DEFAULT 0 COMMENT '1: yes, 0: no', `is_registered` tinyint NOT NULL DEFAULT 0 COMMENT '1: yes, 0: no',
`region_id` bigint unsigned, `region_id` int unsigned,
`incorrect_login_attempts` integer unsigned NOT NULL DEFAULT 0, `incorrect_login_attempts` integer unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
INDEX `i_user__removed`(`removed`), INDEX `i_user__removed`(`removed`),
@ -1241,7 +1241,7 @@ CREATE TABLE `cloud`.`domain` (
`state` char(32) NOT NULL default 'Active' COMMENT 'state of the domain', `state` char(32) NOT NULL default 'Active' COMMENT 'state of the domain',
`network_domain` varchar(255), `network_domain` varchar(255),
`type` varchar(255) NOT NULL DEFAULT 'Normal' COMMENT 'type of the domain - can be Normal or Project', `type` varchar(255) NOT NULL DEFAULT 'Normal' COMMENT 'type of the domain - can be Normal or Project',
`region_id` bigint unsigned, `region_id` int unsigned,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE (parent, name, removed), UNIQUE (parent, name, removed),
INDEX `i_domain__path`(`path`), INDEX `i_domain__path`(`path`),
@ -1260,7 +1260,7 @@ CREATE TABLE `cloud`.`account` (
`cleanup_needed` tinyint(1) NOT NULL default '0', `cleanup_needed` tinyint(1) NOT NULL default '0',
`network_domain` varchar(255), `network_domain` varchar(255),
`default_zone_id` bigint unsigned, `default_zone_id` bigint unsigned,
`region_id` bigint unsigned, `region_id` int unsigned,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
INDEX i_account__removed(`removed`), INDEX i_account__removed(`removed`),
CONSTRAINT `fk_account__default_zone_id` FOREIGN KEY `fk_account__default_zone_id`(`default_zone_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_account__default_zone_id` FOREIGN KEY `fk_account__default_zone_id`(`default_zone_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE,
@ -2214,10 +2214,11 @@ CREATE TABLE `cloud`.`netscaler_pod_ref` (
CREATE TABLE `cloud`.`region` ( CREATE TABLE `cloud`.`region` (
`id` bigint unsigned NOT NULL UNIQUE, `id` int unsigned NOT NULL UNIQUE,
`name` varchar(255), `name` varchar(255) NOT NULL,
`end_point` varchar(255), `end_point` varchar(255) NOT NULL,
`status` varchar(32) NOT NULL, `api_key` varchar(255),
`secret_key` varchar(255),
`removed` datetime COMMENT 'date removed if not null', `removed` datetime COMMENT 'date removed if not null',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -20,6 +20,7 @@
# in which the management server(Tomcat) is running # in which the management server(Tomcat) is running
cluster.node.IP=127.0.0.1 cluster.node.IP=127.0.0.1
cluster.servlet.port=9090 cluster.servlet.port=9090
region.id=1
# CloudStack database settings # CloudStack database settings
db.cloud.username=cloud db.cloud.username=cloud

View File

@ -260,4 +260,6 @@ public interface GenericDao<T, ID extends Serializable> {
* @return * @return
*/ */
Class<T> getEntityBeanType(); Class<T> getEntityBeanType();
public int getRegionId();
} }

View File

@ -1769,4 +1769,9 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
factory.setCallback(0, sc); factory.setCallback(0, sc);
return sc; return sc;
} }
@Override
public int getRegionId(){
return Transaction.s_region_id;
}
} }

View File

@ -82,6 +82,7 @@ public class Transaction {
public static final short AWSAPI_DB = 2; public static final short AWSAPI_DB = 2;
public static final short SIMULATOR_DB = 3; public static final short SIMULATOR_DB = 3;
public static final short CONNECTED_DB = -1; public static final short CONNECTED_DB = -1;
public static int s_region_id;
private static AtomicLong s_id = new AtomicLong(); private static AtomicLong s_id = new AtomicLong();
private static final TransactionMBeanImpl s_mbean = new TransactionMBeanImpl(); private static final TransactionMBeanImpl s_mbean = new TransactionMBeanImpl();
@ -1057,6 +1058,12 @@ public class Transaction {
System.setProperty("javax.net.ssl.trustStorePassword", dbProps.getProperty("db.cloud.trustStorePassword")); System.setProperty("javax.net.ssl.trustStorePassword", dbProps.getProperty("db.cloud.trustStorePassword"));
} }
String regionId = dbProps.getProperty("region.id");
if(regionId == null){
s_region_id = 1;
} else {
s_region_id = Integer.parseInt(regionId);
}
final GenericObjectPool cloudConnectionPool = new GenericObjectPool(null, cloudMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, final GenericObjectPool cloudConnectionPool = new GenericObjectPool(null, cloudMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION,
cloudMaxWait, cloudMaxIdle, cloudTestOnBorrow, false, cloudTimeBtwEvictionRunsMillis, 1, cloudMinEvcitableIdleTimeMillis, cloudTestWhileIdle); cloudMaxWait, cloudMaxIdle, cloudTestOnBorrow, false, cloudTimeBtwEvictionRunsMillis, 1, cloudMinEvcitableIdleTimeMillis, cloudTestWhileIdle);
final ConnectionFactory cloudConnectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://"+cloudHost + ":" + cloudPort + "/" + cloudDbName + final ConnectionFactory cloudConnectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://"+cloudHost + ":" + cloudPort + "/" + cloudDbName +