From f0f33bf4da7948f2109d0e07a4d80c4e362d86b8 Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Wed, 17 Oct 2012 14:16:36 +0530 Subject: [PATCH] Added Mock ApiServer, Regions API calls with api keys --- api/src/com/cloud/api/ResponseGenerator.java | 9 + .../com/cloud/api/commands/AddRegionCmd.java | 24 +- .../cloud/api/commands/CreateAccountCmd.java | 6 +- .../cloud/api/commands/CreateDomainCmd.java | 6 +- .../com/cloud/api/commands/CreateUserCmd.java | 6 +- .../cloud/api/commands/FindAccountCmd.java | 77 ++ .../com/cloud/api/commands/FindDomainCmd.java | 90 +++ .../com/cloud/api/commands/FindUserCmd.java | 84 +++ .../cloud/api/commands/ListRegionsCmd.java | 13 +- .../cloud/api/commands/RemoveRegionCmd.java | 11 +- .../cloud/api/commands/UpdateDomainCmd.java | 2 +- .../cloud/api/commands/UpdateRegionCmd.java | 27 +- .../api/response/FindAccountResponse.java | 95 +++ .../api/response/FindDomainResponse.java | 111 +++ .../cloud/api/response/FindUserResponse.java | 189 +++++ .../cloud/api/response/RegionResponse.java | 6 +- api/src/com/cloud/domain/Domain.java | 2 + api/src/com/cloud/region/Region.java | 11 +- api/src/com/cloud/region/RegionService.java | 6 +- .../com/cloud/server/ManagementService.java | 9 - api/src/com/cloud/user/Account.java | 2 +- api/src/com/cloud/user/AccountService.java | 7 +- api/src/com/cloud/user/DomainService.java | 20 +- api/src/com/cloud/user/User.java | 3 +- client/tomcatconf/commands.properties.in | 3 + client/tomcatconf/components-regions.xml.in | 52 ++ client/tomcatconf/components.xml.in | 1 + client/tomcatconf/db.properties.in | 1 + client/tomcatconf/environment.properties.in | 2 +- core/src/com/cloud/user/AccountVO.java | 14 +- core/src/com/cloud/user/UserVO.java | 8 +- .../server/auth/MD5UserAuthenticator.java | 8 +- .../src/com/cloud/api/ApiResponseHelper.java | 55 ++ server/src/com/cloud/api/ApiServer.java | 7 +- server/src/com/cloud/api/MockApiServer.java | 638 ++++++++++++++++ server/src/com/cloud/domain/DomainVO.java | 10 +- .../com/cloud/domain/dao/DomainDaoImpl.java | 10 +- .../cloud/projects/ProjectManagerImpl.java | 2 +- .../com/cloud/region/FindDomainResponse.java | 36 + .../com/cloud/region/FindUserResponse.java | 34 + .../src/com/cloud/region/RegionAccount.java | 287 ++++++++ server/src/com/cloud/region/RegionDomain.java | 61 ++ .../src/com/cloud/region/RegionManager.java | 9 +- .../com/cloud/region/RegionManagerImpl.java | 639 +++++++++------- server/src/com/cloud/region/RegionUser.java | 76 ++ server/src/com/cloud/region/RegionVO.java | 44 +- .../src/com/cloud/region/RegionsApiUtil.java | 285 ++++++++ .../src/com/cloud/region/dao/RegionDao.java | 2 +- .../com/cloud/region/dao/RegionDaoImpl.java | 2 +- .../cloud/server/ConfigurationServerImpl.java | 15 +- .../cloud/server/ManagementServerImpl.java | 93 --- server/src/com/cloud/user/AccountManager.java | 2 +- .../com/cloud/user/AccountManagerImpl.java | 23 +- server/src/com/cloud/user/DomainManager.java | 11 +- .../src/com/cloud/user/DomainManagerImpl.java | 98 ++- .../com/cloud/user/dao/AccountDaoImpl.java | 1 - .../cloud/user/dao/UserAccountDaoImpl.java | 1 + .../src/com/cloud/user/dao/UserDaoImpl.java | 9 +- .../com/cloud/async/TestAsyncJobManager.java | 12 +- .../MockSecurityGroupManagerImpl.java | 198 +++++ .../cloud/storage/MockStorageManagerImpl.java | 679 ++++++++++++++++++ .../cloud/user/MockAccountManagerImpl.java | 61 +- .../com/cloud/user/MockDomainManagerImpl.java | 34 +- .../com/cloud/vm/MockUserVmManagerImpl.java | 3 +- .../vpc/MockConfigurationManagerImpl.java | 3 +- setup/db/create-schema.sql | 15 +- utils/conf/db.properties | 1 + utils/src/com/cloud/utils/db/GenericDao.java | 2 + .../com/cloud/utils/db/GenericDaoBase.java | 5 + utils/src/com/cloud/utils/db/Transaction.java | 7 + 70 files changed, 3814 insertions(+), 561 deletions(-) create mode 100644 api/src/com/cloud/api/commands/FindAccountCmd.java create mode 100644 api/src/com/cloud/api/commands/FindDomainCmd.java create mode 100644 api/src/com/cloud/api/commands/FindUserCmd.java create mode 100755 api/src/com/cloud/api/response/FindAccountResponse.java create mode 100644 api/src/com/cloud/api/response/FindDomainResponse.java create mode 100644 api/src/com/cloud/api/response/FindUserResponse.java create mode 100755 client/tomcatconf/components-regions.xml.in create mode 100755 server/src/com/cloud/api/MockApiServer.java create mode 100644 server/src/com/cloud/region/FindDomainResponse.java create mode 100644 server/src/com/cloud/region/FindUserResponse.java create mode 100644 server/src/com/cloud/region/RegionAccount.java create mode 100644 server/src/com/cloud/region/RegionDomain.java create mode 100644 server/src/com/cloud/region/RegionUser.java create mode 100644 server/src/com/cloud/region/RegionsApiUtil.java create mode 100755 server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java create mode 100755 server/test/com/cloud/storage/MockStorageManagerImpl.java diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java index b245e423747..b61922e8576 100755 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/com/cloud/api/ResponseGenerator.java @@ -34,6 +34,9 @@ import com.cloud.api.response.DomainResponse; import com.cloud.api.response.DomainRouterResponse; import com.cloud.api.response.EventResponse; 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.FirewallRuleResponse; import com.cloud.api.response.HostResponse; @@ -344,4 +347,10 @@ public interface ResponseGenerator { Site2SiteCustomerGatewayResponse createSite2SiteCustomerGatewayResponse(Site2SiteCustomerGateway result); Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result); + + FindUserResponse createFindUserResponse(User user); + + FindAccountResponse createFindAccountResponse(Account account); + + FindDomainResponse createFindDomainResponse(Domain domain); } diff --git a/api/src/com/cloud/api/commands/AddRegionCmd.java b/api/src/com/cloud/api/commands/AddRegionCmd.java index 0338b915c03..f2fd91f0221 100644 --- a/api/src/com/cloud/api/commands/AddRegionCmd.java +++ b/api/src/com/cloud/api/commands/AddRegionCmd.java @@ -36,20 +36,26 @@ public class AddRegionCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Region") - private Long id; + @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="Id of the Region") + private Integer id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="adds Region with this name") private String regionName; @Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, required=true, description="end_point of the Region") 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 /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { + public Integer getId() { return id; } @@ -59,8 +65,16 @@ public class AddRegionCmd extends BaseCmd { public String getEndPoint() { return endPoint; - } + } + public String getApiKey() { + return apiKey; + } + + public String getSecretKey() { + return secretKey; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -77,7 +91,7 @@ public class AddRegionCmd extends BaseCmd { @Override public void execute(){ - Region region = _regionService.addRegion(getId(), getRegionName(), getEndPoint()); + Region region = _regionService.addRegion(getId(), getRegionName(), getEndPoint(), getApiKey(), getSecretKey()); if (region != null) { RegionResponse response = _responseGenerator.createRegionResponse(region); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/CreateAccountCmd.java b/api/src/com/cloud/api/commands/CreateAccountCmd.java index 21a51a65c97..e778a02c545 100755 --- a/api/src/com/cloud/api/commands/CreateAccountCmd.java +++ b/api/src/com/cloud/api/commands/CreateAccountCmd.java @@ -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") private String userUUID; - @Parameter(name=ApiConstants.REGION_ID, type=CommandType.LONG, description="Id of the Region creating the account") - private Long regionId; + @Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, description="Id of the Region creating the account") + private Integer regionId; ///////////////////////////////////////////////////// @@ -152,7 +152,7 @@ public class CreateAccountCmd extends BaseCmd { return userUUID; } - public Long getRegionId() { + public Integer getRegionId() { return regionId; } diff --git a/api/src/com/cloud/api/commands/CreateDomainCmd.java b/api/src/com/cloud/api/commands/CreateDomainCmd.java index 29fd05018f8..7644dbaf2ad 100644 --- a/api/src/com/cloud/api/commands/CreateDomainCmd.java +++ b/api/src/com/cloud/api/commands/CreateDomainCmd.java @@ -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") private String domainUUID; - @Parameter(name=ApiConstants.REGION_ID, type=CommandType.LONG, description="Id of the Region creating the Domain") - private Long regionId; + @Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, description="Id of the Region creating the Domain") + private Integer regionId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -76,7 +76,7 @@ public class CreateDomainCmd extends BaseCmd { return domainUUID; } - public Long getRegionId() { + public Integer getRegionId() { return regionId; } diff --git a/api/src/com/cloud/api/commands/CreateUserCmd.java b/api/src/com/cloud/api/commands/CreateUserCmd.java index 66a27f08f9d..dcc75aaa74f 100644 --- a/api/src/com/cloud/api/commands/CreateUserCmd.java +++ b/api/src/com/cloud/api/commands/CreateUserCmd.java @@ -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") private String userUUID; - @Parameter(name=ApiConstants.REGION_ID, type=CommandType.LONG, description="Id of the Region creating the User") - private Long regionId; + @Parameter(name=ApiConstants.REGION_ID, type=CommandType.INTEGER, description="Id of the Region creating the User") + private Integer regionId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -111,7 +111,7 @@ public class CreateUserCmd extends BaseCmd { return userUUID; } - public Long getRegionId() { + public Integer getRegionId() { return regionId; } diff --git a/api/src/com/cloud/api/commands/FindAccountCmd.java b/api/src/com/cloud/api/commands/FindAccountCmd.java new file mode 100644 index 00000000000..3c8610a71d9 --- /dev/null +++ b/api/src/com/cloud/api/commands/FindAccountCmd.java @@ -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"); + } + } +} diff --git a/api/src/com/cloud/api/commands/FindDomainCmd.java b/api/src/com/cloud/api/commands/FindDomainCmd.java new file mode 100644 index 00000000000..cb299d12399 --- /dev/null +++ b/api/src/com/cloud/api/commands/FindDomainCmd.java @@ -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"); + } + } +} diff --git a/api/src/com/cloud/api/commands/FindUserCmd.java b/api/src/com/cloud/api/commands/FindUserCmd.java new file mode 100644 index 00000000000..cd46ffd7f6d --- /dev/null +++ b/api/src/com/cloud/api/commands/FindUserCmd.java @@ -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"); + } + } +} diff --git a/api/src/com/cloud/api/commands/ListRegionsCmd.java b/api/src/com/cloud/api/commands/ListRegionsCmd.java index 38f24d42701..53b7a6e307e 100644 --- a/api/src/com/cloud/api/commands/ListRegionsCmd.java +++ b/api/src/com/cloud/api/commands/ListRegionsCmd.java @@ -25,14 +25,13 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; -import com.cloud.api.response.DomainResponse; import com.cloud.api.response.ListResponse; import com.cloud.api.response.RegionResponse; 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 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"; @@ -40,17 +39,17 @@ public class ListRegionsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List domain by domain ID.") - private Long id; + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List Region by region 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; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { + public Integer getId() { return id; } diff --git a/api/src/com/cloud/api/commands/RemoveRegionCmd.java b/api/src/com/cloud/api/commands/RemoveRegionCmd.java index 2facc1010a1..a42ce4b36e9 100644 --- a/api/src/com/cloud/api/commands/RemoveRegionCmd.java +++ b/api/src/com/cloud/api/commands/RemoveRegionCmd.java @@ -19,17 +19,12 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; 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.UserContext; @Implementation(description="Removes specified region", responseObject=SuccessResponse.class) public class RemoveRegionCmd extends BaseCmd { @@ -40,14 +35,14 @@ public class RemoveRegionCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the region to delete") - private Long id; + @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="ID of the region to delete") + private Integer id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { + public Integer getId() { return id; } diff --git a/api/src/com/cloud/api/commands/UpdateDomainCmd.java b/api/src/com/cloud/api/commands/UpdateDomainCmd.java index 20a0664f5bb..0152aa60627 100644 --- a/api/src/com/cloud/api/commands/UpdateDomainCmd.java +++ b/api/src/com/cloud/api/commands/UpdateDomainCmd.java @@ -93,7 +93,7 @@ public class UpdateDomainCmd extends BaseCmd { boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; Domain domain = null; if(isPopagate){ - domain = _mgr.updateDomain(this); + domain = _domainService.updateDomain(this); } else { domain = _regionService.updateDomain(this); } diff --git a/api/src/com/cloud/api/commands/UpdateRegionCmd.java b/api/src/com/cloud/api/commands/UpdateRegionCmd.java index bbdb3b03a92..f1f1dbad50d 100644 --- a/api/src/com/cloud/api/commands/UpdateRegionCmd.java +++ b/api/src/com/cloud/api/commands/UpdateRegionCmd.java @@ -20,18 +20,14 @@ 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.ServerApiException; -import com.cloud.api.response.DomainResponse; import com.cloud.api.response.RegionResponse; -import com.cloud.domain.Domain; import com.cloud.region.Region; 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 static final Logger s_logger = Logger.getLogger(UpdateRegionCmd.class.getName()); private static final String s_name = "updateregionresponse"; @@ -40,8 +36,8 @@ public class UpdateRegionCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of region to update") - private Long id; + @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="ID of region to update") + private Integer id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates region with this name") 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") 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 /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { + public Integer getId() { return id; } @@ -65,6 +67,13 @@ public class UpdateRegionCmd extends BaseCmd { return endPoint; } + public String getApiKey() { + return apiKey; + } + + public String getSecretKey() { + return secretKey; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -81,7 +90,7 @@ public class UpdateRegionCmd extends BaseCmd { @Override public void execute(){ - Region region = _regionService.updateRegion(getId(), getRegionName(), getEndPoint()); + Region region = _regionService.updateRegion(getId(), getRegionName(), getEndPoint(), getApiKey(), getSecretKey()); if (region != null) { RegionResponse response = _responseGenerator.createRegionResponse(region); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/response/FindAccountResponse.java b/api/src/com/cloud/api/response/FindAccountResponse.java new file mode 100755 index 00000000000..bf79abdaf2c --- /dev/null +++ b/api/src/com/cloud/api/response/FindAccountResponse.java @@ -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 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 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; + } +} diff --git a/api/src/com/cloud/api/response/FindDomainResponse.java b/api/src/com/cloud/api/response/FindDomainResponse.java new file mode 100644 index 00000000000..befb6329052 --- /dev/null +++ b/api/src/com/cloud/api/response/FindDomainResponse.java @@ -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; + } +} diff --git a/api/src/com/cloud/api/response/FindUserResponse.java b/api/src/com/cloud/api/response/FindUserResponse.java new file mode 100644 index 00000000000..3532f2c472c --- /dev/null +++ b/api/src/com/cloud/api/response/FindUserResponse.java @@ -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; + } +} diff --git a/api/src/com/cloud/api/response/RegionResponse.java b/api/src/com/cloud/api/response/RegionResponse.java index c507621cb5d..92f97c728da 100644 --- a/api/src/com/cloud/api/response/RegionResponse.java +++ b/api/src/com/cloud/api/response/RegionResponse.java @@ -22,7 +22,7 @@ import com.google.gson.annotations.SerializedName; public class RegionResponse extends BaseResponse { @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") private String name; @@ -30,11 +30,11 @@ public class RegionResponse extends BaseResponse { @SerializedName(ApiConstants.END_POINT) @Param(description="the end point of the region") private String endPoint; - public Long getId() { + public Integer getId() { return id; } - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } diff --git a/api/src/com/cloud/domain/Domain.java b/api/src/com/cloud/domain/Domain.java index 59863471b8e..4c713ea6a9c 100644 --- a/api/src/com/cloud/domain/Domain.java +++ b/api/src/com/cloud/domain/Domain.java @@ -59,4 +59,6 @@ public interface Domain extends OwnedBy { String getNetworkDomain(); public String getUuid(); + + int getRegionId(); } diff --git a/api/src/com/cloud/region/Region.java b/api/src/com/cloud/region/Region.java index 5fb8d327d1e..3096af59317 100644 --- a/api/src/com/cloud/region/Region.java +++ b/api/src/com/cloud/region/Region.java @@ -22,19 +22,18 @@ import java.util.Date; * */ public interface Region { - public static enum State { - Up, Down - }; - public long getId(); + public int getId(); public String getName(); public void setName(String name); - public Region.State getStatus(); - public Date getRemoved(); public String getEndPoint(); + + public String getApiKey(); + + public String getSecretKey(); } diff --git a/api/src/com/cloud/region/RegionService.java b/api/src/com/cloud/region/RegionService.java index 8fa505821c1..a10bcfac3d8 100644 --- a/api/src/com/cloud/region/RegionService.java +++ b/api/src/com/cloud/region/RegionService.java @@ -31,9 +31,9 @@ import com.cloud.user.UserAccount; public interface RegionService { - public Region addRegion(long id, String name, String endPoint); - public Region updateRegion(long id, String name, String endPoint); - public boolean removeRegion(long id); + public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey); + public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey); + public boolean removeRegion(int id); public List listRegions(ListRegionsCmd cmd); boolean deleteUserAccount(long accountId); Account updateAccount(UpdateAccountCmd cmd); diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 8dcc3983599..25d62508ba7 100755 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -220,15 +220,6 @@ public interface ManagementService { 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 * diff --git a/api/src/com/cloud/user/Account.java b/api/src/com/cloud/user/Account.java index 6ae93e2b3e4..d7d67ac5a6a 100755 --- a/api/src/com/cloud/user/Account.java +++ b/api/src/com/cloud/user/Account.java @@ -62,7 +62,7 @@ public interface Account extends ControlledEntity { public Long getDefaultZoneId(); - public long getRegionId(); + public int getRegionId(); public String getUuid(); } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index a389dd2b7db..b1682059c90 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -62,7 +62,7 @@ public interface AccountService { * @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, - Map details, String accountUUID, String userUUID, Long regionId); + Map details, String accountUUID, String userUUID, Integer regionId); /** * Deletes a user by userId @@ -163,7 +163,7 @@ public interface AccountService { 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); @@ -202,4 +202,7 @@ public interface AccountService { void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException; + User findUser(String username, Long domainId); + + Account findAccount(Long id); } diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 4de14d1f210..e2221b6b21f 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -20,12 +20,13 @@ import java.util.List; import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainsCmd; +import com.cloud.api.commands.UpdateDomainCmd; import com.cloud.domain.Domain; import com.cloud.exception.PermissionDeniedException; 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); @@ -44,5 +45,22 @@ public interface DomainService { List searchForDomainChildren(ListDomainChildrenCmd cmd) 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); } diff --git a/api/src/com/cloud/user/User.java b/api/src/com/cloud/user/User.java index c625c168d0d..916ce601814 100644 --- a/api/src/com/cloud/user/User.java +++ b/api/src/com/cloud/user/User.java @@ -68,5 +68,6 @@ public interface User extends OwnedBy { String getRegistrationToken(); boolean isRegistered(); - + + public int getRegionId(); } diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index 5ee333c4377..f873b1a9b33 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -27,6 +27,7 @@ enableAccount=com.cloud.api.commands.EnableAccountCmd;7 ###lockAccount=com.cloud.api.commands.LockAccountCmd;7 listAccounts=com.cloud.api.commands.ListAccountsCmd;15 markDefaultZoneForAccount=com.cloud.api.commands.MarkDefaultZoneForAccountCmd;1 +findAccount=com.cloud.api.commands.FindAccountCmd;1 #### User commands 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 enableUser=com.cloud.api.commands.EnableUserCmd;7 getUser=com.cloud.api.commands.GetUserCmd;1 +findUser=com.cloud.api.commands.FindUserCmd;1 #### Domain commands 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 listDomains=com.cloud.api.commands.ListDomainsCmd;7 listDomainChildren=com.cloud.api.commands.ListDomainChildrenCmd;7 +findDomain=com.cloud.api.commands.FindDomainCmd;1 ####Cloud Identifier commands getCloudIdentifier=com.cloud.api.commands.GetCloudIdentifierCmd;15 diff --git a/client/tomcatconf/components-regions.xml.in b/client/tomcatconf/components-regions.xml.in new file mode 100755 index 00000000000..60a2d00d542 --- /dev/null +++ b/client/tomcatconf/components-regions.xml.in @@ -0,0 +1,52 @@ + + + + + + + true + + + + + + diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index 5730b832075..99a2eabc21d 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -206,6 +206,7 @@ under the License. + diff --git a/client/tomcatconf/db.properties.in b/client/tomcatconf/db.properties.in index f39d8fe4097..5582ecc3988 100644 --- a/client/tomcatconf/db.properties.in +++ b/client/tomcatconf/db.properties.in @@ -19,6 +19,7 @@ # in which the management server(Tomcat) is running cluster.node.IP=127.0.0.1 cluster.servlet.port=9090 +region.id=1 # CloudStack database settings db.cloud.username=@DBUSER@ diff --git a/client/tomcatconf/environment.properties.in b/client/tomcatconf/environment.properties.in index 49544a1aed6..f2956cc4abb 100644 --- a/client/tomcatconf/environment.properties.in +++ b/client/tomcatconf/environment.properties.in @@ -19,4 +19,4 @@ paths.script=@COMMONLIBDIR@ mount.parent=@MSMNTDIR@ -cloud-stack-components-specification=@COMPONENTS-SPEC@ +cloud-stack-components-specification=components.xml diff --git a/core/src/com/cloud/user/AccountVO.java b/core/src/com/cloud/user/AccountVO.java index 9848306c3f1..644e091f7f0 100644 --- a/core/src/com/cloud/user/AccountVO.java +++ b/core/src/com/cloud/user/AccountVO.java @@ -68,7 +68,7 @@ public class AccountVO implements Account, Identity { private Long defaultZoneId = null; @Column(name="region_id") - private long regionId; + private int regionId; public AccountVO() { this.uuid = UUID.randomUUID().toString(); @@ -79,7 +79,7 @@ public class AccountVO implements Account, Identity { 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.domainId = domainId; this.networkDomain = networkDomain; @@ -102,7 +102,11 @@ public class AccountVO implements Account, Identity { return id; } - @Override + public void setId(long id) { + this.id = id; + } + + @Override public String getAccountName() { return accountName; } @@ -180,11 +184,11 @@ public class AccountVO implements Account, Identity { this.uuid = uuid; } - public long getRegionId() { + public int getRegionId() { return regionId; } - public void setRegionId(long regionId) { + public void setRegionId(int regionId) { this.regionId = regionId; } } diff --git a/core/src/com/cloud/user/UserVO.java b/core/src/com/cloud/user/UserVO.java index f227f31ba77..eb5aeae4d6d 100644 --- a/core/src/com/cloud/user/UserVO.java +++ b/core/src/com/cloud/user/UserVO.java @@ -93,7 +93,7 @@ public class UserVO implements User, Identity { private String uuid; @Column(name="region_id") - private long regionId; + private int regionId; public UserVO() { this.uuid = UUID.randomUUID().toString(); @@ -104,7 +104,7 @@ public class UserVO implements User, Identity { 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.username = username; this.password = password; @@ -265,11 +265,11 @@ public class UserVO implements User, Identity { this.uuid = uuid; } - public long getRegionId() { + public int getRegionId() { return regionId; } - public void setRegionId(long regionId) { + public void setRegionId(int regionId) { this.regionId = regionId; } } diff --git a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java index f4b6f021f3b..cd6d7242ce3 100644 --- a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java +++ b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java @@ -22,10 +22,12 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; +import com.cloud.region.RegionManager; import com.cloud.server.ManagementServer; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; /** * 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 static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class); - private UserAccountDao _userAccountDao; + private RegionManager _regionMgr; @Override public boolean authenticate(String username, String password, Long domainId, Map requestParameters ) { if (s_logger.isDebugEnabled()) { s_logger.debug("Retrieving user: " + username); } - UserAccount user = _userAccountDao.getUserAccount(username, domainId); + UserAccount user = _regionMgr.getUserAccount(username, domainId); if (user == null) { s_logger.debug("Unable to find user with " + username + " in domain " + domainId); return false; @@ -84,7 +86,7 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator { throws ConfigurationException { super.configure(name, params); ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - _userAccountDao = locator.getDao(UserAccountDao.class); + _regionMgr = locator.getManager(RegionManager.class); return true; } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index f66480ea1e4..6b84ac0055f 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -50,6 +50,9 @@ import com.cloud.api.response.DomainResponse; import com.cloud.api.response.DomainRouterResponse; import com.cloud.api.response.EventResponse; 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.FirewallRuleResponse; import com.cloud.api.response.HostResponse; @@ -200,6 +203,7 @@ import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.template.VirtualMachineTemplate; import com.cloud.test.PodZoneConfig; import com.cloud.user.Account; +import com.cloud.user.AccountVO; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; @@ -3927,4 +3931,55 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("vpnconnection"); 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; + } } diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index eb5e7705a5d..50c01253bb3 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -97,6 +97,7 @@ import com.cloud.event.EventUtils; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; +import com.cloud.region.RegionManager; import com.cloud.server.ManagementServer; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -133,7 +134,8 @@ public class ApiServer implements HttpRequestHandler { private AsyncJobManager _asyncMgr = null; private Account _systemAccount = null; private User _systemUser = null; - + private RegionManager _regionMgr = null; + private static int _workerCount = 0; private static ApiServer s_instance = null; @@ -276,6 +278,7 @@ public class ApiServer implements HttpRequestHandler { _systemUser = _accountMgr.getSystemUser(); _dispatcher = ApiDispatcher.getInstance(); _domainMgr = locator.getManager(DomainManager.class); + _regionMgr = locator.getManager(RegionManager.class); Integer apiPort = null; // api port, null by default ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); @@ -785,7 +788,7 @@ public class ApiServer implements HttpRequestHandler { if (domainPath == null || domainPath.trim().length() == 0) { domainId = DomainVO.ROOT_DOMAIN; } else { - Domain domainObj = _domainMgr.findDomainByPath(domainPath); + Domain domainObj = _regionMgr.findDomainByPath(domainPath); if (domainObj != null) { domainId = domainObj.getId(); } else { // if an unknown path is passed in, fail the login call diff --git a/server/src/com/cloud/api/MockApiServer.java b/server/src/com/cloud/api/MockApiServer.java new file mode 100755 index 00000000000..23b78a4c808 --- /dev/null +++ b/server/src/com/cloud/api/MockApiServer.java @@ -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 s_userCommands = null; + private static List s_resellerCommands = null; // AKA domain-admin + private static List s_adminCommands = null; + private static List s_resourceDomainAdminCommands = null; + private static List s_allCommands = null; + private static List s_pluggableServiceCommands = null; + + private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("ApiServer")); + + static { + s_userCommands = new ArrayList(); + s_resellerCommands = new ArrayList(); + s_adminCommands = new ArrayList(); + s_resourceDomainAdminCommands = new ArrayList(); + s_allCommands = new ArrayList(); + s_pluggableServiceCommands = new ArrayList(); + } + + 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 sc = configDao.createSearchCriteria(); + sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port"); + List 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 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 paramMap = new HashMap(); + 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 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 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 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("Internal Server 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 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 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 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 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; + } + +} diff --git a/server/src/com/cloud/domain/DomainVO.java b/server/src/com/cloud/domain/DomainVO.java index 87bc559b3d3..bab1dd710b7 100644 --- a/server/src/com/cloud/domain/DomainVO.java +++ b/server/src/com/cloud/domain/DomainVO.java @@ -75,11 +75,11 @@ public class DomainVO implements Domain, Identity { private String uuid; @Column(name="region_id") - private long regionId; + private int regionId; 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.name = name; this.accountId = owner; @@ -91,7 +91,7 @@ public class DomainVO implements Domain, Identity { 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.name = name; this.accountId = owner; @@ -215,11 +215,11 @@ public class DomainVO implements Domain, Identity { this.uuid = uuid; } - public long getRegionId() { + public int getRegionId() { return regionId; } - public void setRegionId(long regionId) { + public void setRegionId(int regionId) { this.regionId = regionId; } } diff --git a/server/src/com/cloud/domain/dao/DomainDaoImpl.java b/server/src/com/cloud/domain/dao/DomainDaoImpl.java index 90e289175d8..ecf83258b1e 100644 --- a/server/src/com/cloud/domain/dao/DomainDaoImpl.java +++ b/server/src/com/cloud/domain/dao/DomainDaoImpl.java @@ -29,10 +29,9 @@ import org.apache.log4j.Logger; import com.cloud.domain.Domain; 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.GenericDaoBase; -import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @@ -47,7 +46,6 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom protected SearchBuilder ImmediateChildDomainSearch; protected SearchBuilder FindAllChildrenSearch; protected SearchBuilder AllFieldsSearch; - private final long _regionId = 1; public DomainDaoImpl () { DomainNameLikeSearch = createSearchBuilder(); @@ -273,10 +271,4 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom return parentDomains; } - @Override - @DB - public DomainVO persist(DomainVO domain) { - domain.setRegionId(_regionId); - return super.persist(domain); - } } diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 68b113cfcaa..daf185fc07b 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -207,7 +207,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ StringBuilder acctNm = new StringBuilder("PrjAcct-"); 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())); diff --git a/server/src/com/cloud/region/FindDomainResponse.java b/server/src/com/cloud/region/FindDomainResponse.java new file mode 100644 index 00000000000..075bcf220f1 --- /dev/null +++ b/server/src/com/cloud/region/FindDomainResponse.java @@ -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; + } +} \ No newline at end of file diff --git a/server/src/com/cloud/region/FindUserResponse.java b/server/src/com/cloud/region/FindUserResponse.java new file mode 100644 index 00000000000..b6eba46ac2f --- /dev/null +++ b/server/src/com/cloud/region/FindUserResponse.java @@ -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; + } +} \ No newline at end of file diff --git a/server/src/com/cloud/region/RegionAccount.java b/server/src/com/cloud/region/RegionAccount.java new file mode 100644 index 00000000000..cb942100077 --- /dev/null +++ b/server/src/com/cloud/region/RegionAccount.java @@ -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; + } + +} diff --git a/server/src/com/cloud/region/RegionDomain.java b/server/src/com/cloud/region/RegionDomain.java new file mode 100644 index 00000000000..de82654c8bc --- /dev/null +++ b/server/src/com/cloud/region/RegionDomain.java @@ -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; + } +} diff --git a/server/src/com/cloud/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java index d74633de1d2..20e24bacec0 100644 --- a/server/src/com/cloud/region/RegionManager.java +++ b/server/src/com/cloud/region/RegionManager.java @@ -18,14 +18,19 @@ package com.cloud.region; import java.util.Map; +import com.cloud.domain.DomainVO; +import com.cloud.user.UserAccount; + 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, Map details, String accountUUID, String userUUID); - public long getId(); - public void setId(long id); + public int getId(); + public void setId(int id); public void propogateAddUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, String domainUUId, String userUUID); public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid); + UserAccount getUserAccount(String username, Long domainId); + DomainVO findDomainByPath(String domainPath); } diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index 96ff28e0d49..0311780125e 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.region; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -24,10 +23,7 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.NameValuePair; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; @@ -43,7 +39,6 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.region.dao.RegionDao; -import com.cloud.server.ManagementServer; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -51,9 +46,12 @@ import com.cloud.user.DomainManager; import com.cloud.user.UserAccount; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; +import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.uuididentity.dao.IdentityDao; @Local(value = { RegionManager.class, RegionService.class }) public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @@ -70,20 +68,19 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @Inject private DomainDao _domainDao; @Inject - private ManagementServer _mgmtSrvr; - @Inject private DomainManager _domainMgr; - + @Inject + private UserAccountDao _userAccountDao; + @Inject + private IdentityDao _identityDao; private String _name; - private long _id = 1; //ToDo, get this from config or db.properties - - //ToDo use API constants - //prepare API params in advance + private int _id; @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; + _id = _regionDao.getRegionId(); return true; } @@ -105,45 +102,34 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @Override public boolean propogateAddAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, Map details, String accountUUID, String userUUID) { + String command = "createAccount"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.USERNAME, userName)); + params.add(new NameValuePair(ApiConstants.PASSWORD, password)); + params.add(new NameValuePair(ApiConstants.FIRSTNAME, firstName)); + params.add(new NameValuePair(ApiConstants.LASTNAME, lastName)); + params.add(new NameValuePair(ApiConstants.EMAIL, email)); + params.add(new NameValuePair(ApiConstants.TIMEZONE, timezone)); + params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName)); + params.add(new NameValuePair(ApiConstants.ACCOUNT_TYPE, ""+accountType)); + //use domain UUID + params.add(new NameValuePair(ApiConstants.DOMAIN_ID, ((domainId != null) ? domainId.toString() : ""))); + params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain)); + params.add(new NameValuePair(ApiConstants.ACCOUNT_DETAILS, (details != null) ? details.toString() : "")); + params.add(new NameValuePair(ApiConstants.ACCOUNT_ID, accountUUID)); + params.add(new NameValuePair(ApiConstants.USER_ID, userUUID)); + params.add(new NameValuePair(ApiConstants.REGION_ID, ""+getId())); + List regions = _regionDao.listAll(); - StringBuffer params = new StringBuffer("/api?command=createAccount"); - params.append("&"+ApiConstants.USERNAME+"="+userName); - params.append("&"+ApiConstants.PASSWORD+"="+password); - params.append("&"+ApiConstants.FIRSTNAME+"="+firstName); - params.append("&"+ApiConstants.LASTNAME+"="+lastName); - params.append("&"+ApiConstants.EMAIL+"="+email); - if(timezone != null){ - params.append("&"+ApiConstants.TIMEZONE+"="+timezone); - } - if(accountName != null){ - params.append("&"+ApiConstants.ACCOUNT+"="+accountName); - } - params.append("&"+ApiConstants.ACCOUNT_TYPE+"="+accountType); - if(domainId != null){ - params.append("&"+ApiConstants.DOMAIN_ID+"="+domainId); //use UUID - } - 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()); - for (Region region : regions){ if(region.getId() == getId()){ continue; } s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added account :"+accountName+" to Region: "+region.getId()); } else { 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; @@ -156,8 +142,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ return false; } String accountUUID = account.getUuid(); - long regionId = account.getRegionId(); - String params = "/api?command=deleteAccount&"+ApiConstants.ID+"="+accountUUID; + int regionId = account.getRegionId(); + + String command = "deleteAccount"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.ID, accountUUID)); + if(getId() == regionId){ if(_accountMgr.deleteUserAccount(accountId)){ List regions = _regionDao.listAll(); @@ -165,8 +155,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params+"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while deleting account :"+accountUUID+" in Region: "+region.getId()); @@ -179,8 +169,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First delete in the Region where account is created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); return true; } else { @@ -198,6 +187,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ String accountName = cmd.getAccountName(); String newAccountName = cmd.getNewName(); String networkDomain = cmd.getNetworkDomain(); + //ToDo send details Map details = cmd.getDetails(); 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); } - StringBuffer params = new StringBuffer("/api?command=updateAccount"); - params.append("&"+ApiConstants.NEW_NAME+"="+newAccountName); - if(account != null){ - params.append("&"+ApiConstants.ID+"="+account.getUuid()); - } - if(accountName != null){ - params.append("&"+ApiConstants.ACCOUNT+"="+accountName); - } - if(domain != null){ - params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); - } - if(networkDomain != null){ - params.append("&"+ApiConstants.NETWORK_DOMAIN+"="+networkDomain); - } - if(details != null){ - params.append("&"+ApiConstants.ACCOUNT_DETAILS+"="+details); - } - - long regionId = account.getRegionId(); + String command = "updateAccount"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.NEW_NAME, newAccountName)); + params.add(new NameValuePair(ApiConstants.ID, account.getUuid())); + params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName)); + params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid())); + params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain)); + params.add(new NameValuePair(ApiConstants.NEW_NAME, newAccountName)); + if(details != null){ + params.add(new NameValuePair(ApiConstants.ACCOUNT_DETAILS, details.toString())); + } + int regionId = account.getRegionId(); if(getId() == regionId){ - Account updateAccount = _accountMgr.updateAccount(cmd); - if(updateAccount != null){ + Account updatedAccount = _accountMgr.updateAccount(cmd); + if(updatedAccount != null){ List regions = _regionDao.listAll(); for (Region region : regions){ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params+"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully updated account :"+account.getUuid()+" in Region: "+region.getId()); } else { s_logger.error("Error while updating account :"+account.getUuid()+" in Region: "+region.getId()); } } } - return updateAccount; + return updatedAccount; } else { //First update in the Region where account is created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + RegionAccount updatedAccount = RegionsApiUtil.makeAccountAPICall(region, command, params); + 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()); - //return Account object - return null; + return updatedAccount; } else { - s_logger.error("Error while updating account :"+account.getUuid()+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while updating account :"+account.getUuid()+" in source Region: "+region.getId()); } } } - private boolean makeAPICall(String url){ - try { + @Override + public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey) { + if( _regionDao.findById(id) == null ){ + RegionVO region = new RegionVO(id, name, endPoint, apiKey, secretKey); + return _regionDao.persist(region); + } else { + throw new InvalidParameterValueException("Region with id: "+id+" already exists"); + } + } - 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; + @Override + public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey) { + RegionVO region = _regionDao.findById(id); + + if(region == null){ + throw new InvalidParameterValueException("Region with id: "+id+" does not exist"); } - } - - @Override - public Region addRegion(long id, String name, String endPoint) { - 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); if(name != null){ region.setName(name); } @@ -302,12 +275,20 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ region.setEndPoint(endPoint); } + if(apiKey != null){ + region.setApiKey(apiKey); + } + + if(secretKey != null){ + region.setSecretKey(secretKey); + } + _regionDao.update(id, region); return _regionDao.findById(id); } @Override - public boolean removeRegion(long id) { + public boolean removeRegion(int id) { RegionVO region = _regionDao.findById(id); if(region != null){ return _regionDao.remove(id); @@ -316,11 +297,11 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } - public long getId() { + public int getId() { return _id; } - public void setId(long _id) { + public void setId(int _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); } String accountUUID = account.getUuid(); - StringBuffer params = new StringBuffer("/api?command=disableAccount"+"&"+ApiConstants.LOCK+"="+lockRequested); - params.append("&"+ApiConstants.ID+"="+accountUUID); - if(accountName != null){ - params.append("&"+ApiConstants.ACCOUNT+"="+accountName); + + String command = "disableAccount"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.LOCK, lockRequested.toString())); + params.add(new NameValuePair(ApiConstants.ID, accountUUID)); + DomainVO domain = _domainDao.findById(domainId); + if(domain != null){ + params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid())); } - DomainVO domain = _domainDao.findById(domainId); - if(domain != null){ - params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); - } - long regionId = account.getRegionId(); + + int regionId = account.getRegionId(); if(getId() == regionId){ Account retAccount = null; if(lockRequested){ @@ -370,8 +352,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully disabled account :"+accountUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while disabling account :"+accountUUID+" in Region: "+region.getId()); @@ -382,15 +364,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First disable account in the Region where account is created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + Account retAccount = RegionsApiUtil.makeAccountAPICall(region, command, params); + if (retAccount != null) { s_logger.debug("Successfully disabled account :"+accountUUID+" in source Region: "+region.getId()); - //return Account object - return null; + return retAccount; } else { - s_logger.error("Error while disabling account :"+accountUUID+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while disabling account :"+accountUUID+" in source Region: "+region.getId()); } } } @@ -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); } String accountUUID = account.getUuid(); - StringBuffer params = new StringBuffer("/api?command=enableAccount"); - params.append("&"+ApiConstants.ID+"="+accountUUID); - if(accountName != null){ - params.append("&"+ApiConstants.ACCOUNT+"="+accountName); - } + + String command = "enableAccount"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.ID, accountUUID)); + params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName)); DomainVO domain = _domainDao.findById(domainId); 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){ Account retAccount = _accountMgr.enableAccount(accountName, domainId, accountId); if(retAccount != null){ @@ -429,8 +408,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully enabled account :"+accountUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while enabling account :"+accountUUID+" in Region: "+region.getId()); @@ -441,15 +420,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First disable account in the Region where account is created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + Account retAccount = RegionsApiUtil.makeAccountAPICall(region, command, params); + if (retAccount != null) { s_logger.debug("Successfully enabled account :"+accountUUID+" in source Region: "+region.getId()); - //return Account object - return null; + return retAccount; } else { - s_logger.error("Error while enabling account :"+accountUUID+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while enabling account :"+accountUUID+" in source Region: "+region.getId()); } } } @@ -465,8 +441,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } String userUUID = user.getUuid(); - long regionId = user.getRegionId(); - String params = "/api?command=deleteUser&id="+userUUID; + int regionId = user.getRegionId(); + + String command = "deleteUser"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.ID, userUUID)); + if(getId() == regionId){ if(_accountMgr.deleteUser(cmd)){ List regions = _regionDao.listAll(); @@ -474,8 +454,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while deleting account :"+userUUID+" in Region: "+region.getId()); @@ -488,8 +468,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First delete in the Region where account is created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); return true; } else { @@ -507,10 +486,13 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); } String domainUUID = domain.getUuid(); - StringBuffer params = new StringBuffer("/api?command=deleteDomain"); - params.append("&"+ApiConstants.ID+"="+domainUUID); - params.append("&"+ApiConstants.CLEANUP+"="+cleanup); - long regionId = domain.getRegionId(); + + String command = "deleteDomain"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.ID, domainUUID)); + params.add(new NameValuePair(ApiConstants.CLEANUP, cleanup.toString())); + + int regionId = domain.getRegionId(); if(getId() == regionId){ if(_domainMgr.deleteDomain(id, cleanup)){ List regions = _regionDao.listAll(); @@ -518,8 +500,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while deleting domain :"+domainUUID+" in Region: "+region.getId()); @@ -532,8 +514,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First delete in the Region where domain is created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId()); return true; } else { @@ -553,34 +534,20 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ throw new InvalidParameterValueException("The specified user doesn't exist in the system"); } 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 params = new ArrayList(); + 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){ UserAccount updateUser = _accountMgr.updateUser(cmd); if(updateUser != null){ @@ -589,8 +556,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully updated user :"+userUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while updating user :"+userUUID+" in Region: "+region.getId()); @@ -601,15 +568,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First update in the Region where user was created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + UserAccount updateUser = RegionsApiUtil.makeUserAccountAPICall(region, command, params); + if (updateUser != null) { s_logger.debug("Successfully updated user :"+userUUID+" in source Region: "+region.getId()); - //return object - return null; + return updateUser; } else { - s_logger.error("Error while updating user :"+userUUID+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while updating user :"+userUUID+" in source Region: "+region.getId()); } } } @@ -622,26 +586,24 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); } 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 params = new ArrayList(); + 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){ - Domain updatedDomain = _mgmtSrvr.updateDomain(cmd); + Domain updatedDomain = _domainMgr.updateDomain(cmd); if(updatedDomain != null){ List regions = _regionDao.listAll(); for (Region region : regions){ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully updated updatedDomain :"+domainUUID+" in Region: "+region.getId()); } else { s_logger.error("Error while updating updatedDomain :"+domainUUID+" in Region: "+region.getId()); @@ -652,15 +614,14 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { //First update in the Region where domain was created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + RegionDomain updatedDomain = RegionsApiUtil.makeDomainAPICall(region, command, params); + 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()); - //return object - return null; + return (DomainVO)updatedDomain; } else { - s_logger.error("Error while updating user :"+domainUUID+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while updating user :"+domainUUID+" in source Region: "+region.getId()); } } } @@ -671,8 +632,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - long regionId = user.getRegionId(); - StringBuffer params = new StringBuffer("/api?command=disableUser&id="+user.getUuid()); + int regionId = user.getRegionId(); + + String command = "disableUser"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.ID, user.getUuid())); + if(getId() == regionId){ UserAccount disabledUser = _accountMgr.disableUser(userId); if(disabledUser != null){ @@ -681,8 +646,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully disabled user :"+user.getUuid()+" in Region: "+region.getId()); } else { 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 { //First disable in the Region where user was created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + UserAccount disabledUser = RegionsApiUtil.makeUserAccountAPICall(region, command, params); + if (disabledUser != null) { s_logger.debug("Successfully disabled user :"+user.getUuid()+" in source Region: "+region.getId()); - //return object - return null; + return disabledUser; } else { - s_logger.error("Error while disabling user :"+user.getUuid()+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while disabling user :"+user.getUuid()+" in source Region: "+region.getId()); } } } @@ -712,8 +674,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - long regionId = user.getRegionId(); - StringBuffer params = new StringBuffer("/api?command=enableUser&id="+user.getUuid()); + int regionId = user.getRegionId(); + + String command = "enableUser"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.ID, user.getUuid())); + if(getId() == regionId){ UserAccount enabledUser = _accountMgr.enableUser(userId); if(enabledUser != null){ @@ -722,8 +688,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params +"&"+ApiConstants.IS_PROPAGATE+"=true"; - if (makeAPICall(url)) { + params.add(new NameValuePair(ApiConstants.IS_PROPAGATE, "true")); + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully enabled user :"+user.getUuid()+" in Region: "+region.getId()); } else { 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 { //First enable in the Region where user was created Region region = _regionDao.findById(regionId); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + UserAccount enabledUser = RegionsApiUtil.makeUserAccountAPICall(region, command, params); + if (enabledUser != null) { s_logger.debug("Successfully enabled user :"+user.getUuid()+" in source Region: "+region.getId()); - //return object - return null; + return enabledUser; } else { - s_logger.error("Error while enabling user :"+user.getUuid()+" in source Region: "+region.getId()); - //throw exception; - return null; + throw new CloudRuntimeException("Error while enabling user :"+user.getUuid()+" in source Region: "+region.getId()); } } } @@ -752,23 +715,18 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ String firstName, String lastName, String email, String timezone, String accountName, String domainUUId, String userUUID) { - StringBuffer params = new StringBuffer("/api?command=createUser"); - params.append("&"+ApiConstants.USERNAME+"="+userName); - params.append("&"+ApiConstants.PASSWORD+"="+password); - params.append("&"+ApiConstants.FIRSTNAME+"="+firstName); - params.append("&"+ApiConstants.LASTNAME+"="+lastName); - params.append("&"+ApiConstants.EMAIL+"="+email); - if(timezone != null){ - params.append("&"+ApiConstants.TIMEZONE+"="+timezone); - } - if(accountName != null){ - params.append("&"+ApiConstants.ACCOUNT+"="+accountName); - } - if(domainUUId != null){ - params.append("&"+ApiConstants.DOMAIN_ID+"="+domainUUId); //use UUID - } - params.append("&"+ApiConstants.USER_ID+"="+userUUID); - params.append("&"+ApiConstants.REGION_ID+"="+getId()); + String command = "createUser"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.USERNAME, userName)); + params.add(new NameValuePair(ApiConstants.PASSWORD, password)); + params.add(new NameValuePair(ApiConstants.FIRSTNAME, firstName)); + params.add(new NameValuePair(ApiConstants.LASTNAME, lastName)); + params.add(new NameValuePair(ApiConstants.EMAIL, email)); + params.add(new NameValuePair(ApiConstants.TIMEZONE, timezone)); + params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName)); + params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domainUUId)); + params.add(new NameValuePair(ApiConstants.USER_ID, userUUID)); + params.add(new NameValuePair(ApiConstants.REGION_ID, ""+getId())); List regions = _regionDao.listAll(); for (Region region : regions){ @@ -776,13 +734,10 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ continue; } s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added user :"+userName+" to Region: "+region.getId()); } else { 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; @@ -790,21 +745,19 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @Override public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid) { - StringBuffer params = new StringBuffer("/api?command=createDomain"); - params.append("&ApiConstants.NAME="+name); - String parentUUID = null; + + String command = "createDomain"; + List params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.NAME, name)); if(parentId != null){ DomainVO domain = _domainDao.findById(parentId); if(domain != null){ - parentUUID = domain.getUuid(); - params.append("&ApiConstants.PARENT_DOMAIN_ID="+parentUUID); + params.add(new NameValuePair(ApiConstants.PARENT_DOMAIN_ID, domain.getUuid())); } } - if(networkDomain != null){ - params.append("&ApiConstants.NETWORK_DOMAIN="+networkDomain); - } - params.append("&ApiConstants.DOMAIN_ID="+uuid); - params.append("&ApiConstants.REGION_ID="+getId()); + params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain)); + params.add(new NameValuePair(ApiConstants.DOMAIN_ID, uuid)); + params.add(new NameValuePair(ApiConstants.REGION_ID, ""+getId())); List regions = _regionDao.listAll(); for (Region region : regions){ @@ -812,17 +765,157 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ continue; } s_logger.debug("Adding domain :"+name+" to Region: "+region.getId()); - String url = region.getEndPoint() + params; - if (makeAPICall(url)) { + if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added domain :"+name+" to Region: "+region.getId()); } else { 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; - } + @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 params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.USERNAME, username)); + params.add(new NameValuePair(ApiConstants.DOMAIN_ID, domain.getUuid())); + RegionUser regionuser = null; + List 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 params = new ArrayList(); + params.add(new NameValuePair(ApiConstants.DOMAIN, domainPath)); + boolean sourceCheck = false; + RegionDomain regiondomain = null; + List 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); + } + } } diff --git a/server/src/com/cloud/region/RegionUser.java b/server/src/com/cloud/region/RegionUser.java new file mode 100644 index 00000000000..878655837cb --- /dev/null +++ b/server/src/com/cloud/region/RegionUser.java @@ -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; + } + +} diff --git a/server/src/com/cloud/region/RegionVO.java b/server/src/com/cloud/region/RegionVO.java index 483659470f1..c54dea23154 100644 --- a/server/src/com/cloud/region/RegionVO.java +++ b/server/src/com/cloud/region/RegionVO.java @@ -20,12 +20,9 @@ import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.region.Region; import com.cloud.utils.db.GenericDao; @Entity @@ -34,7 +31,7 @@ public class RegionVO implements Region{ @Id @Column(name="id") - private long id; + private int id; @Column(name="name") private String name; @@ -42,9 +39,11 @@ public class RegionVO implements Region{ @Column(name="end_point") private String endPoint; - @Column(name="status") - @Enumerated(value=EnumType.STRING) - private Region.State status; + @Column(name="api_key") + private String apiKey; + + @Column(name="secret_key") + private String secretKey; @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @@ -52,14 +51,15 @@ public class RegionVO implements Region{ 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.name = name; this.endPoint = endPoint; - this.status = Region.State.Down; + this.apiKey = apiKey; + this.secretKey = secretKey; } - public long getId() { + public int getId() { return id; } @@ -71,14 +71,6 @@ public class RegionVO implements Region{ this.name = name; } - public Region.State getStatus() { - return status; - } - - public void setStatus(Region.State status) { - this.status = status; - } - public Date getRemoved() { return removed; } @@ -91,5 +83,21 @@ public class RegionVO implements Region{ 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; + } + } diff --git a/server/src/com/cloud/region/RegionsApiUtil.java b/server/src/com/cloud/region/RegionsApiUtil.java new file mode 100644 index 00000000000..3e20fd37f21 --- /dev/null +++ b/server/src/com/cloud/region/RegionsApiUtil.java @@ -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 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 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 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 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 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 params) { + StringBuffer paramString = new StringBuffer("command="+command); + Iterator 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 sortedParams = new ArrayList(); + 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; + } + } +} \ No newline at end of file diff --git a/server/src/com/cloud/region/dao/RegionDao.java b/server/src/com/cloud/region/dao/RegionDao.java index 829b8a6b467..e334ef8f6eb 100644 --- a/server/src/com/cloud/region/dao/RegionDao.java +++ b/server/src/com/cloud/region/dao/RegionDao.java @@ -19,5 +19,5 @@ package com.cloud.region.dao; import com.cloud.region.RegionVO; import com.cloud.utils.db.GenericDao; -public interface RegionDao extends GenericDao { +public interface RegionDao extends GenericDao { } diff --git a/server/src/com/cloud/region/dao/RegionDaoImpl.java b/server/src/com/cloud/region/dao/RegionDaoImpl.java index 79d6d92592c..0d8a69d5620 100644 --- a/server/src/com/cloud/region/dao/RegionDaoImpl.java +++ b/server/src/com/cloud/region/dao/RegionDaoImpl.java @@ -24,7 +24,7 @@ import com.cloud.region.RegionVO; import com.cloud.utils.db.GenericDaoBase; @Local(value={RegionDao.class}) -public class RegionDaoImpl extends GenericDaoBase implements RegionDao { +public class RegionDaoImpl extends GenericDaoBase implements RegionDao { private static final Logger s_logger = Logger.getLogger(RegionDaoImpl.class); public RegionDaoImpl(){ diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index a0d10b6d515..43fe57ac265 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -85,6 +85,8 @@ import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; 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.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; @@ -123,6 +125,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { private final ResourceCountDao _resourceCountDao; private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao; private final IdentityDao _identityDao; + private final RegionDao _regionDao; public ConfigurationServerImpl() { ComponentLocator locator = ComponentLocator.getLocator(Name); @@ -140,6 +143,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _resourceCountDao = locator.getDao(ResourceCountDao.class); _ntwkOfferingServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class); _identityDao = locator.getDao(IdentityDao.class); + _regionDao = locator.getDao(RegionDao.class); } @Override @@ -228,6 +232,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { // Create default networks createDefaultNetworks(); + createDefaultRegion(); + // Create userIpAddress ranges // Update existing vlans with networkId @@ -274,7 +280,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { updateCloudIdentifier(); updateUuids(); - + // Set init to true _configDao.update("init", "Hidden", "true"); } @@ -324,6 +330,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { @DB protected void saveUser() { + //ToDo: Add regionId to default users and accounts // insert system account String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')"; Transaction txn = Transaction.currentTxn(); @@ -1272,5 +1279,11 @@ public class ConfigurationServerImpl implements ConfigurationServer { 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 + } } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 4f489bc15f9..3aa04bf1386 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -1969,99 +1969,6 @@ public class ManagementServerImpl implements ManagementServer { return new Pair(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 sc = _domainDao.createSearchCriteria(); - sc.addAnd("name", SearchCriteria.Op.EQ, domainName); - List 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 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 public List searchForAlerts(ListAlertsCmd cmd) { Filter searchFilter = new Filter(AlertVO.class, "lastSent", false, cmd.getStartIndex(), cmd.getPageSizeVal()); diff --git a/server/src/com/cloud/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java index 3d55b9fd3a8..ad67618302c 100755 --- a/server/src/com/cloud/user/AccountManager.java +++ b/server/src/com/cloud/user/AccountManager.java @@ -49,7 +49,7 @@ public interface AccountManager extends AccountService { 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); diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index b58c417743d..7d36d5432f9 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -759,7 +759,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @DB @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, - Map details, String accountUUID, String userUUID, Long regionId) { + Map details, String accountUUID, String userUUID, Integer regionId) { if (accountName == null) { accountName = userName; @@ -849,7 +849,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @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 if (domainId == null) { @@ -1629,7 +1629,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @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 Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { @@ -1709,7 +1709,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } //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()) { 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) { 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); + } } diff --git a/server/src/com/cloud/user/DomainManager.java b/server/src/com/cloud/user/DomainManager.java index 36f7e6cf91e..aea653e6f4c 100644 --- a/server/src/com/cloud/user/DomainManager.java +++ b/server/src/com/cloud/user/DomainManager.java @@ -25,16 +25,7 @@ import com.cloud.domain.DomainVO; public interface DomainManager extends DomainService { Set getDomainChildrenIds(String parentDomainPath); - Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Long 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); + Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Integer regionId); Set getDomainParentIds(long domainId); diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 53dca932b7f..8ec68bb7ff9 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -28,6 +28,7 @@ import org.apache.log4j.Logger; import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainsCmd; +import com.cloud.api.commands.UpdateDomainCmd; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.domain.Domain; @@ -131,7 +132,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager @Override @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(); if (parentId == null) { @@ -155,7 +156,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager @Override @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 if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { @@ -483,4 +484,97 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager 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 sc = _domainDao.createSearchCriteria(); + sc.addAnd("name", SearchCriteria.Op.EQ, domainName); + List 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 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); + } + } + } diff --git a/server/src/com/cloud/user/dao/AccountDaoImpl.java b/server/src/com/cloud/user/dao/AccountDaoImpl.java index ab3fd23776c..f7ad679c856 100755 --- a/server/src/com/cloud/user/dao/AccountDaoImpl.java +++ b/server/src/com/cloud/user/dao/AccountDaoImpl.java @@ -32,7 +32,6 @@ import com.cloud.user.User; import com.cloud.user.UserVO; import com.cloud.utils.Pair; import com.cloud.utils.crypt.DBEncryptionUtil; -import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; diff --git a/server/src/com/cloud/user/dao/UserAccountDaoImpl.java b/server/src/com/cloud/user/dao/UserAccountDaoImpl.java index 663e58fba4f..fc4166d1375 100644 --- a/server/src/com/cloud/user/dao/UserAccountDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserAccountDaoImpl.java @@ -62,4 +62,5 @@ public class UserAccountDaoImpl extends GenericDaoBase impl sc.setParameters("apiKey",apiKey); return findOneBy(sc); } + } diff --git a/server/src/com/cloud/user/dao/UserDaoImpl.java b/server/src/com/cloud/user/dao/UserDaoImpl.java index 9bcee2fdbbb..19ef69155ad 100644 --- a/server/src/com/cloud/user/dao/UserDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserDaoImpl.java @@ -20,7 +20,9 @@ import java.util.List; import javax.ejb.Local; +import com.cloud.region.RegionManager; import com.cloud.user.UserVO; +import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; @@ -35,7 +37,6 @@ public class UserDaoImpl extends GenericDaoBase implements UserDao protected SearchBuilder AccountIdSearch; protected SearchBuilder SecretKeySearch; protected SearchBuilder RegistrationTokenSearch; - private final long _regionId = 1; protected UserDaoImpl () { UsernameSearch = createSearchBuilder(); @@ -125,10 +126,4 @@ public class UserDaoImpl extends GenericDaoBase implements UserDao return listBy(sc); } - @Override - @DB - public UserVO persist(UserVO user) { - user.setRegionId(_regionId); - return super.persist(user); - } } diff --git a/server/test/com/cloud/async/TestAsyncJobManager.java b/server/test/com/cloud/async/TestAsyncJobManager.java index 8ce51fa3849..9b154ff4222 100644 --- a/server/test/com/cloud/async/TestAsyncJobManager.java +++ b/server/test/com/cloud/async/TestAsyncJobManager.java @@ -228,25 +228,25 @@ public class TestAsyncJobManager extends ComponentTestCase { getRandomMilliseconds(1, 100); DomainDao domainDao = new DomainDaoImpl(); - DomainVO domain1 = new DomainVO("d1", 2L, 1L, null); + DomainVO domain1 = new DomainVO("d1", 2L, 1L, null, 1); domainDao.create(domain1); - DomainVO domain2 = new DomainVO("d2", 2L, 1L, null); + DomainVO domain2 = new DomainVO("d2", 2L, 1L, null, 1); domainDao.create(domain2); - DomainVO domain3 = new DomainVO("d3", 2L, 1L, null); + DomainVO domain3 = new DomainVO("d3", 2L, 1L, null, 1); 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.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.remove(domain3.getId()); - DomainVO domain4 = new DomainVO("d4", 2L, 1L, null); + DomainVO domain4 = new DomainVO("d4", 2L, 1L, null, 1); domainDao.create(domain4); } } diff --git a/server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java b/server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java new file mode 100755 index 00000000000..9c71c621dda --- /dev/null +++ b/server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java @@ -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 { + + @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 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 searchForSecurityGroupRules( + ListSecurityGroupsCmd cmd) throws PermissionDeniedException, + InvalidParameterValueException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List authorizeSecurityGroupIngress( + AuthorizeSecurityGroupIngressCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List 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 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> newGroupStates) { + // TODO Auto-generated method stub + + } + + @Override + public String getSecurityGroupsNamesForVm(long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List 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; + } + } diff --git a/server/test/com/cloud/storage/MockStorageManagerImpl.java b/server/test/com/cloud/storage/MockStorageManagerImpl.java new file mode 100755 index 00000000000..6273489ae35 --- /dev/null +++ b/server/test/com/cloud/storage/MockStorageManagerImpl.java @@ -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 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 nodeList, + long selfNodeId) { + // TODO Auto-generated method stub + + } + + @Override + public void onManagementNodeLeft(List nodeList, + long selfNodeId) { + // TODO Auto-generated method stub + + } + + @Override + public void onManagementNodeIsolated() { + // TODO Auto-generated method stub + + } + + @Override + public boolean configure(String name, Map 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 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 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 sendToPool(StoragePool pool, + long[] hostIdsToTryFirst, List hostIdsToAvoid, Commands cmds) + throws StorageUnavailableException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Pair sendToPool(StoragePool pool, + long[] hostIdsToTryFirst, List 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 DiskProfile allocateRawVolume(Type type, + String name, DiskOfferingVO offering, Long size, T vm, Account owner) { + // TODO Auto-generated method stub + return null; + } + + @Override + public 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 vm, + DeployDestination dest) throws StorageUnavailableException, + InsufficientStorageCapacityException, ConcurrentOperationException { + // TODO Auto-generated method stub + + } + + @Override + public void release(VirtualMachineProfile profile) { + // TODO Auto-generated method stub + + } + + @Override + public void cleanupVolumes(long vmId) throws ConcurrentOperationException { + // TODO Auto-generated method stub + + } + + @Override + public void prepareForMigration( + VirtualMachineProfile 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 getSecondaryStorageHosts(long zoneId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List ListByDataCenterHypervisor(long datacenterId, + HypervisorType type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List 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 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 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 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, + StoragePool pool) { + // TODO Auto-generated method stub + return false; + } +} diff --git a/server/test/com/cloud/user/MockAccountManagerImpl.java b/server/test/com/cloud/user/MockAccountManagerImpl.java index 0d15cd7de0a..c4c2e6b5394 100644 --- a/server/test/com/cloud/user/MockAccountManagerImpl.java +++ b/server/test/com/cloud/user/MockAccountManagerImpl.java @@ -206,12 +206,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS 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 public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId) { // TODO Auto-generated method stub @@ -280,23 +274,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS 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 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 public List searchForAccounts(ListAccountsCmd cmd) { // TODO Auto-generated method stub @@ -343,4 +320,42 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS 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 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; + } + } diff --git a/server/test/com/cloud/user/MockDomainManagerImpl.java b/server/test/com/cloud/user/MockDomainManagerImpl.java index e99e4d94265..2927526d51c 100644 --- a/server/test/com/cloud/user/MockDomainManagerImpl.java +++ b/server/test/com/cloud/user/MockDomainManagerImpl.java @@ -25,6 +25,7 @@ import javax.naming.ConfigurationException; import com.cloud.api.commands.ListDomainChildrenCmd; import com.cloud.api.commands.ListDomainsCmd; +import com.cloud.api.commands.UpdateDomainCmd; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.exception.PermissionDeniedException; @@ -33,12 +34,6 @@ import com.cloud.utils.component.Manager; @Local(value = { DomainManager.class }) public class MockDomainManagerImpl implements Manager, DomainManager { - @Override - public Domain createDomain(String name, Long parentId, String networkDomain) { - // TODO Auto-generated method stub - return null; - } - @Override public Domain getDomain(long id) { // TODO Auto-generated method stub @@ -77,13 +72,6 @@ public class MockDomainManagerImpl implements Manager, DomainManager { return null; } - @Override - public Domain createDomain(String name, Long parentId, Long ownerId, - String networkDomain) { - // TODO Auto-generated method stub - return null; - } - @Override public DomainVO findDomainByPath(String domainPath) { // TODO Auto-generated method stub @@ -138,4 +126,24 @@ public class MockDomainManagerImpl implements Manager, DomainManager { 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; + } + } diff --git a/server/test/com/cloud/vm/MockUserVmManagerImpl.java b/server/test/com/cloud/vm/MockUserVmManagerImpl.java index efc6916ab40..1baf34a0320 100644 --- a/server/test/com/cloud/vm/MockUserVmManagerImpl.java +++ b/server/test/com/cloud/vm/MockUserVmManagerImpl.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.vm; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -194,7 +195,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana @Override public List searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { // TODO Auto-generated method stub - return null; + return new ArrayList(); } @Override diff --git a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java index 2a2588629b6..6fa31231157 100644 --- a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java +++ b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java @@ -321,8 +321,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi */ @Override public Long getDefaultPageSize() { - // TODO Auto-generated method stub - return null; + return 500L; } /* (non-Javadoc) diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index bdaecb05396..695dc44a2f3 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -891,7 +891,7 @@ CREATE TABLE `cloud`.`user` ( `timezone` varchar(30) default NULL, `registration_token` varchar(255) default NULL, `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, PRIMARY KEY (`id`), 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', `network_domain` varchar(255), `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`), UNIQUE (parent, name, removed), INDEX `i_domain__path`(`path`), @@ -1260,7 +1260,7 @@ CREATE TABLE `cloud`.`account` ( `cleanup_needed` tinyint(1) NOT NULL default '0', `network_domain` varchar(255), `default_zone_id` bigint unsigned, - `region_id` bigint unsigned, + `region_id` int unsigned, PRIMARY KEY (`id`), 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, @@ -2214,10 +2214,11 @@ CREATE TABLE `cloud`.`netscaler_pod_ref` ( CREATE TABLE `cloud`.`region` ( - `id` bigint unsigned NOT NULL UNIQUE, - `name` varchar(255), - `end_point` varchar(255), - `status` varchar(32) NOT NULL, + `id` int unsigned NOT NULL UNIQUE, + `name` varchar(255) NOT NULL, + `end_point` varchar(255) NOT NULL, + `api_key` varchar(255), + `secret_key` varchar(255), `removed` datetime COMMENT 'date removed if not null', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/utils/conf/db.properties b/utils/conf/db.properties index 6bdb6d61667..caf90037282 100644 --- a/utils/conf/db.properties +++ b/utils/conf/db.properties @@ -20,6 +20,7 @@ # in which the management server(Tomcat) is running cluster.node.IP=127.0.0.1 cluster.servlet.port=9090 +region.id=1 # CloudStack database settings db.cloud.username=cloud diff --git a/utils/src/com/cloud/utils/db/GenericDao.java b/utils/src/com/cloud/utils/db/GenericDao.java index 3ab319ea830..ca4c21ac129 100755 --- a/utils/src/com/cloud/utils/db/GenericDao.java +++ b/utils/src/com/cloud/utils/db/GenericDao.java @@ -260,4 +260,6 @@ public interface GenericDao { * @return */ Class getEntityBeanType(); + + public int getRegionId(); } diff --git a/utils/src/com/cloud/utils/db/GenericDaoBase.java b/utils/src/com/cloud/utils/db/GenericDaoBase.java index 3df83747f31..271cec56796 100755 --- a/utils/src/com/cloud/utils/db/GenericDaoBase.java +++ b/utils/src/com/cloud/utils/db/GenericDaoBase.java @@ -1769,4 +1769,9 @@ public abstract class GenericDaoBase implements Gene factory.setCallback(0, sc); return sc; } + + @Override + public int getRegionId(){ + return Transaction.s_region_id; + } } diff --git a/utils/src/com/cloud/utils/db/Transaction.java b/utils/src/com/cloud/utils/db/Transaction.java index bcf7ae1257a..f05d263b41c 100755 --- a/utils/src/com/cloud/utils/db/Transaction.java +++ b/utils/src/com/cloud/utils/db/Transaction.java @@ -82,6 +82,7 @@ public class Transaction { public static final short AWSAPI_DB = 2; public static final short SIMULATOR_DB = 3; public static final short CONNECTED_DB = -1; + public static int s_region_id; private static AtomicLong s_id = new AtomicLong(); 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")); } + 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, cloudMaxWait, cloudMaxIdle, cloudTestOnBorrow, false, cloudTimeBtwEvictionRunsMillis, 1, cloudMinEvcitableIdleTimeMillis, cloudTestWhileIdle); final ConnectionFactory cloudConnectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://"+cloudHost + ":" + cloudPort + "/" + cloudDbName +