From ccf15cb5f6b50821af53e1a58ae499d983a4ac64 Mon Sep 17 00:00:00 2001 From: kishan Date: Tue, 3 Jul 2012 12:59:28 -0700 Subject: [PATCH 01/24] Add Region APIs --- .../com/cloud/api/commands/AddRegionCmd.java | 89 ++++++++++++++++++ .../cloud/api/commands/ListRegionsCmd.java | 85 +++++++++++++++++ .../cloud/api/commands/RemoveRegionCmd.java | 78 ++++++++++++++++ .../cloud/api/commands/UpdateRegionCmd.java | 93 +++++++++++++++++++ .../cloud/api/response/RegionResponse.java | 57 ++++++++++++ 5 files changed, 402 insertions(+) create mode 100644 api/src/com/cloud/api/commands/AddRegionCmd.java create mode 100644 api/src/com/cloud/api/commands/ListRegionsCmd.java create mode 100644 api/src/com/cloud/api/commands/RemoveRegionCmd.java create mode 100644 api/src/com/cloud/api/commands/UpdateRegionCmd.java create mode 100644 api/src/com/cloud/api/response/RegionResponse.java diff --git a/api/src/com/cloud/api/commands/AddRegionCmd.java b/api/src/com/cloud/api/commands/AddRegionCmd.java new file mode 100644 index 00000000000..0338b915c03 --- /dev/null +++ b/api/src/com/cloud/api/commands/AddRegionCmd.java @@ -0,0 +1,89 @@ +// 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.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.RegionResponse; +import com.cloud.region.Region; +import com.cloud.user.Account; + +@Implementation(description="Adds a Region", responseObject=RegionResponse.class) +public class AddRegionCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(AddRegionCmd.class.getName()); + + private static final String s_name = "addregionresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Region") + private Long 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; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public String getRegionName() { + return regionName; + } + + public String getEndPoint() { + return endPoint; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + Region region = _regionService.addRegion(getId(), getRegionName(), getEndPoint()); + if (region != null) { + RegionResponse response = _responseGenerator.createRegionResponse(region); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Region"); + } + } +} diff --git a/api/src/com/cloud/api/commands/ListRegionsCmd.java b/api/src/com/cloud/api/commands/ListRegionsCmd.java new file mode 100644 index 00000000000..38f24d42701 --- /dev/null +++ b/api/src/com/cloud/api/commands/ListRegionsCmd.java @@ -0,0 +1,85 @@ +// 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 java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +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) +public class ListRegionsCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); + + private static final String s_name = "listregionsresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List domain by domain ID.") + private Long id; + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List domain by domain name.") + private String domainName; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public String getRegionName() { + return domainName; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public void execute(){ + List result = _regionService.listRegions(this); + ListResponse response = new ListResponse(); + List regionResponses = new ArrayList(); + for (Region region : result) { + RegionResponse regionResponse = _responseGenerator.createRegionResponse(region); + regionResponse.setObjectName("region"); + regionResponses.add(regionResponse); + } + + response.setResponses(regionResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } +} diff --git a/api/src/com/cloud/api/commands/RemoveRegionCmd.java b/api/src/com/cloud/api/commands/RemoveRegionCmd.java new file mode 100644 index 00000000000..2facc1010a1 --- /dev/null +++ b/api/src/com/cloud/api/commands/RemoveRegionCmd.java @@ -0,0 +1,78 @@ +// 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.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 { + public static final Logger s_logger = Logger.getLogger(RemoveRegionCmd.class.getName()); + private static final String s_name = "updateregionresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the region to delete") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + boolean result = _regionService.removeRegion(id); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove region"); + } + } +} diff --git a/api/src/com/cloud/api/commands/UpdateRegionCmd.java b/api/src/com/cloud/api/commands/UpdateRegionCmd.java new file mode 100644 index 00000000000..bbdb3b03a92 --- /dev/null +++ b/api/src/com/cloud/api/commands/UpdateRegionCmd.java @@ -0,0 +1,93 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package 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.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) +public class UpdateRegionCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(UpdateRegionCmd.class.getName()); + private static final String s_name = "updateregionresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of region to update") + private Long id; + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates region with this name") + private String regionName; + + @Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, description="updates region with this end point") + private String endPoint; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public String getRegionName() { + return regionName; + } + + public String getEndPoint() { + return endPoint; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + Region region = _regionService.updateRegion(getId(), getRegionName(), getEndPoint()); + if (region != null) { + RegionResponse response = _responseGenerator.createRegionResponse(region); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update Region"); + } + } +} diff --git a/api/src/com/cloud/api/response/RegionResponse.java b/api/src/com/cloud/api/response/RegionResponse.java new file mode 100644 index 00000000000..c507621cb5d --- /dev/null +++ b/api/src/com/cloud/api/response/RegionResponse.java @@ -0,0 +1,57 @@ +// 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.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class RegionResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) @Param(description="the ID of the region") + private Long id; + + @SerializedName(ApiConstants.NAME) @Param(description="the name of the region") + private String name; + + @SerializedName(ApiConstants.END_POINT) @Param(description="the end point of the region") + private String endPoint; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEndPoint() { + return endPoint; + } + + public void setEndPoint(String endPoint) { + this.endPoint = endPoint; + } + + } From 6a1b0f3ecf02b3d3c730089ad18b458f216d9784 Mon Sep 17 00:00:00 2001 From: kishan Date: Tue, 3 Jul 2012 13:05:19 -0700 Subject: [PATCH 02/24] Add Region APIs --- api/src/com/cloud/api/ApiConstants.java | 1 + api/src/com/cloud/api/BaseCmd.java | 5 ++++- api/src/com/cloud/api/ResponseGenerator.java | 4 ++++ client/tomcatconf/commands.properties.in | 6 ++++++ core/src/com/cloud/user/AccountVO.java | 12 +++++++++++- core/src/com/cloud/user/UserVO.java | 11 +++++++++++ server/src/com/cloud/api/ApiResponseHelper.java | 12 ++++++++++++ .../configuration/DefaultComponentLibrary.java | 4 ++++ server/src/com/cloud/domain/DomainVO.java | 11 +++++++++++ .../src/com/cloud/domain/dao/DomainDaoImpl.java | 9 +++++++++ server/src/com/cloud/user/AccountManagerImpl.java | 6 ++++-- server/src/com/cloud/user/dao/AccountDaoImpl.java | 9 +++++++++ server/src/com/cloud/user/dao/UserDaoImpl.java | 9 +++++++++ setup/db/create-schema.sql | 15 +++++++++++++++ 14 files changed, 110 insertions(+), 4 deletions(-) diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index f7acd5168be..69e7939c82c 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -357,6 +357,7 @@ public class ApiConstants { public static final String VSM_CONFIG_STATE = "vsmconfigstate"; public static final String VSM_DEVICE_STATE = "vsmdevicestate"; public static final String ADD_VSM_FLAG = "addvsmflag"; + public static final String END_POINT = "endpoint"; public enum HostDetails { all, capacity, events, stats, min; diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/com/cloud/api/BaseCmd.java index a9b6f6074b8..afebf2b7363 100755 --- a/api/src/com/cloud/api/BaseCmd.java +++ b/api/src/com/cloud/api/BaseCmd.java @@ -47,6 +47,7 @@ import com.cloud.network.security.SecurityGroupService; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.projects.Project; import com.cloud.projects.ProjectService; +import com.cloud.region.RegionService; import com.cloud.resource.ResourceService; import com.cloud.server.ManagementService; import com.cloud.storage.StorageService; @@ -128,7 +129,8 @@ public abstract class BaseCmd { public static ResourceLimitService _resourceLimitService; public static IdentityService _identityService; public static StorageNetworkService _storageNetworkService; - + public static RegionService _regionService; + static void setComponents(ResponseGenerator generator) { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); _mgr = (ManagementService) ComponentLocator.getComponent(ManagementService.Name); @@ -155,6 +157,7 @@ public abstract class BaseCmd { _resourceLimitService = locator.getManager(ResourceLimitService.class); _identityService = locator.getManager(IdentityService.class); _storageNetworkService = locator.getManager(StorageNetworkService.class); + _regionService = locator.getManager(RegionService.class); } public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException; diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java index 5f55705981c..42da0fd2cdf 100755 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/com/cloud/api/ResponseGenerator.java @@ -53,6 +53,7 @@ import com.cloud.api.response.ProjectAccountResponse; import com.cloud.api.response.ProjectInvitationResponse; import com.cloud.api.response.ProjectResponse; import com.cloud.api.response.ProviderResponse; +import com.cloud.api.response.RegionResponse; import com.cloud.api.response.RemoteAccessVpnResponse; import com.cloud.api.response.ResourceCountResponse; import com.cloud.api.response.ResourceLimitResponse; @@ -83,6 +84,7 @@ import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; +import com.cloud.region.Region; import com.cloud.dc.StorageNetworkIpRange; import com.cloud.dc.Vlan; import com.cloud.domain.Domain; @@ -273,6 +275,8 @@ public interface ResponseGenerator { LDAPConfigResponse createLDAPConfigResponse(String hostname, Integer port, Boolean useSSL, String queryFilter, String baseSearch, String dn); StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result); + + RegionResponse createRegionResponse(Region region); /** * @param tableName TODO diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index a939eb7751a..6ef0961d5c3 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -332,3 +332,9 @@ updateStorageNetworkIpRange=com.cloud.api.commands.UpdateStorageNetworkIpRangeCm addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 + +#### Region commands +addRegion=com.cloud.api.commands.AddRegionCmd;1 +updateRegion=com.cloud.api.commands.UpdateRegionCmd;1 +removeRegion=com.cloud.api.commands.RemoveRegionCmd;1 +listRegions=com.cloud.api.commands.ListRegionsCmd;7 \ No newline at end of file diff --git a/core/src/com/cloud/user/AccountVO.java b/core/src/com/cloud/user/AccountVO.java index b8f3940c370..a9bb51a9fba 100644 --- a/core/src/com/cloud/user/AccountVO.java +++ b/core/src/com/cloud/user/AccountVO.java @@ -63,6 +63,9 @@ public class AccountVO implements Account, Identity { @Column(name="default_zone_id") private Long defaultZoneId = null; + @Column(name="region_id") + private long regionId; + public AccountVO() { this.uuid = UUID.randomUUID().toString(); } @@ -78,7 +81,6 @@ public class AccountVO implements Account, Identity { this.networkDomain = networkDomain; this.type = type; this.state = State.enabled; - this.uuid = UUID.randomUUID().toString(); } public void setNeedsCleanup(boolean value) { @@ -171,4 +173,12 @@ public class AccountVO implements Account, Identity { public void setUuid(String uuid) { this.uuid = uuid; } + + public long getRegionId() { + return regionId; + } + + public void setRegionId(long regionId) { + this.regionId = regionId; + } } diff --git a/core/src/com/cloud/user/UserVO.java b/core/src/com/cloud/user/UserVO.java index f866f15eccd..efb0583f5a0 100644 --- a/core/src/com/cloud/user/UserVO.java +++ b/core/src/com/cloud/user/UserVO.java @@ -89,6 +89,9 @@ public class UserVO implements User, Identity { @Column(name="uuid") private String uuid; + @Column(name="region_id") + private long regionId; + public UserVO() { this.uuid = UUID.randomUUID().toString(); } @@ -257,4 +260,12 @@ public class UserVO implements User, Identity { public void setUuid(String uuid) { this.uuid = uuid; } + + public long getRegionId() { + return regionId; + } + + public void setRegionId(long regionId) { + this.regionId = regionId; + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index eb64d98512c..accdbabb547 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -67,6 +67,7 @@ import com.cloud.api.response.ProjectAccountResponse; import com.cloud.api.response.ProjectInvitationResponse; import com.cloud.api.response.ProjectResponse; import com.cloud.api.response.ProviderResponse; +import com.cloud.api.response.RegionResponse; import com.cloud.api.response.RemoteAccessVpnResponse; import com.cloud.api.response.ResourceCountResponse; import com.cloud.api.response.ResourceLimitResponse; @@ -150,6 +151,7 @@ import com.cloud.org.Cluster; import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; +import com.cloud.region.Region; import com.cloud.server.Criteria; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOS; @@ -3399,4 +3401,14 @@ public class ApiResponseHelper implements ResponseGenerator { return ApiDispatcher.getIdentiyId(tableName, token); } + @Override + public RegionResponse createRegionResponse(Region region) { + RegionResponse response = new RegionResponse(); + response.setId(region.getId()); + response.setName(region.getName()); + response.setEndPoint(region.getEndPoint()); + response.setObjectName("region"); + return response; + } + } diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 150d7af89b6..a27ae17ae1e 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -129,6 +129,8 @@ import com.cloud.projects.ProjectManagerImpl; import com.cloud.projects.dao.ProjectAccountDaoImpl; import com.cloud.projects.dao.ProjectDaoImpl; import com.cloud.projects.dao.ProjectInvitationDaoImpl; +import com.cloud.region.RegionManagerImpl; +import com.cloud.region.dao.RegionDaoImpl; import com.cloud.resource.ResourceManagerImpl; import com.cloud.resourcelimit.ResourceLimitManagerImpl; import com.cloud.service.dao.ServiceOfferingDaoImpl; @@ -329,6 +331,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("NetworkServiceMapDao", NetworkServiceMapDaoImpl.class); addDao("StorageNetworkIpAddressDao", StorageNetworkIpAddressDaoImpl.class); addDao("StorageNetworkIpRangeDao", StorageNetworkIpRangeDaoImpl.class); + addDao("RegionDao", RegionDaoImpl.class); } @Override @@ -385,6 +388,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addManager("StorageNetworkManager", StorageNetworkManagerImpl.class); addManager("ExternalLoadBalancerUsageManager", ExternalLoadBalancerUsageManagerImpl.class); addManager("HA Manager", HighAvailabilityManagerImpl.class); + addManager("Region Manager", RegionManagerImpl.class); } @Override diff --git a/server/src/com/cloud/domain/DomainVO.java b/server/src/com/cloud/domain/DomainVO.java index 53ed0753244..a5cfe1bb8ff 100644 --- a/server/src/com/cloud/domain/DomainVO.java +++ b/server/src/com/cloud/domain/DomainVO.java @@ -69,6 +69,9 @@ public class DomainVO implements Domain, Identity { @Column(name="uuid") private String uuid; + + @Column(name="region_id") + private long regionId; public DomainVO() {} @@ -200,5 +203,13 @@ public class DomainVO implements Domain, Identity { public void setUuid(String uuid) { this.uuid = uuid; } + + public long getRegionId() { + return regionId; + } + + public void setRegionId(long 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 c5709693b0f..b653d7bb33f 100644 --- a/server/src/com/cloud/domain/dao/DomainDaoImpl.java +++ b/server/src/com/cloud/domain/dao/DomainDaoImpl.java @@ -25,6 +25,7 @@ import org.apache.log4j.Logger; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; +import com.cloud.user.UserVO; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GlobalLock; @@ -42,6 +43,7 @@ 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(); @@ -266,4 +268,11 @@ 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/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 35fbfe01077..cd63b4dd3cc 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -199,7 +199,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag private ProjectAccountDao _projectAccountDao; @Inject private IPAddressDao _ipAddressDao; - + //@Inject + //private RegionManager _regionMgr; + private Adapters _userAuthenticators; private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("AccountChecker")); @@ -1575,7 +1577,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Create default security group _networkGroupMgr.createDefaultSecurityGroup(accountId); - + //_regionMgr.propogateAddResource(); txn.commit(); return account; diff --git a/server/src/com/cloud/user/dao/AccountDaoImpl.java b/server/src/com/cloud/user/dao/AccountDaoImpl.java index c820e2204a4..be14ec3e899 100755 --- a/server/src/com/cloud/user/dao/AccountDaoImpl.java +++ b/server/src/com/cloud/user/dao/AccountDaoImpl.java @@ -28,6 +28,7 @@ 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; @@ -48,6 +49,7 @@ public class AccountDaoImpl extends GenericDaoBase implements A protected final SearchBuilder CleanupForRemovedAccountsSearch; protected final SearchBuilder CleanupForDisabledAccountsSearch; protected final SearchBuilder NonProjectAccountSearch; + private final long _regionId = 1; protected AccountDaoImpl() { AllFieldsSearch = createSearchBuilder(); @@ -257,4 +259,11 @@ public class AccountDaoImpl extends GenericDaoBase implements A } } } + + @Override + @DB + public AccountVO persist(AccountVO account) { + account.setRegionId(_regionId); + return super.persist(account); + } } diff --git a/server/src/com/cloud/user/dao/UserDaoImpl.java b/server/src/com/cloud/user/dao/UserDaoImpl.java index 2c244618767..17a7b5c0b8e 100644 --- a/server/src/com/cloud/user/dao/UserDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserDaoImpl.java @@ -17,6 +17,7 @@ import java.util.List; import javax.ejb.Local; import com.cloud.user.UserVO; +import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -35,6 +36,7 @@ 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(); @@ -123,4 +125,11 @@ public class UserDaoImpl extends GenericDaoBase implements UserDao sc.setParameters("username", username); return listBy(sc); } + + @Override + @DB + public UserVO persist(UserVO user) { + user.setRegionId(_regionId); + return super.persist(user); + } } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 488fb06e9cd..ff092ebd1e2 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -137,6 +137,7 @@ DROP TABLE IF EXISTS `cloud`.`op_dc_storage_network_ip_address`; DROP TABLE IF EXISTS `cloud`.`cluster_vsm_map`; DROP TABLE IF EXISTS `cloud`.`virtual_supervisor_module`; DROP TABLE IF EXISTS `cloud`.`port_profile`; +DROP TABLE IF EXISTS `cloud`.`region`; CREATE TABLE `cloud`.`version` ( `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', @@ -874,6 +875,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, PRIMARY KEY (`id`), INDEX `i_user__removed`(`removed`), INDEX `i_user__secret_key_removed`(`secret_key`, `removed`), @@ -1219,6 +1221,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, PRIMARY KEY (`id`), UNIQUE (parent, name, removed), INDEX `i_domain__path`(`path`), @@ -1237,6 +1240,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, 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, @@ -2132,4 +2136,15 @@ CREATE TABLE `cloud`.`netscaler_pod_ref` ( CONSTRAINT `fk_ns_pod_ref__device_id` FOREIGN KEY (`external_load_balancer_device_id`) REFERENCES `external_load_balancer_devices`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`region` ( + `id` bigint unsigned NOT NULL UNIQUE, + `name` varchar(255), + `end_point` varchar(255), + `status` varchar(32) NOT NULL, + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + SET foreign_key_checks = 1; From b5563e832e8a7ece7129c5af0c3f9dd1e96301d2 Mon Sep 17 00:00:00 2001 From: kishan Date: Tue, 3 Jul 2012 13:06:21 -0700 Subject: [PATCH 03/24] Add Region APIs --- api/src/com/cloud/region/Region.java | 40 +++++ api/src/com/cloud/region/RegionService.java | 30 ++++ .../src/com/cloud/region/RegionManager.java | 30 ++++ .../com/cloud/region/RegionManagerImpl.java | 149 ++++++++++++++++++ server/src/com/cloud/region/RegionVO.java | 95 +++++++++++ .../src/com/cloud/region/dao/RegionDao.java | 19 +++ .../com/cloud/region/dao/RegionDaoImpl.java | 33 ++++ 7 files changed, 396 insertions(+) create mode 100644 api/src/com/cloud/region/Region.java create mode 100644 api/src/com/cloud/region/RegionService.java create mode 100644 server/src/com/cloud/region/RegionManager.java create mode 100755 server/src/com/cloud/region/RegionManagerImpl.java create mode 100644 server/src/com/cloud/region/RegionVO.java create mode 100644 server/src/com/cloud/region/dao/RegionDao.java create mode 100644 server/src/com/cloud/region/dao/RegionDaoImpl.java diff --git a/api/src/com/cloud/region/Region.java b/api/src/com/cloud/region/Region.java new file mode 100644 index 00000000000..5fb8d327d1e --- /dev/null +++ b/api/src/com/cloud/region/Region.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.region; + +import java.util.Date; + +/** + * + */ +public interface Region { + public static enum State { + Up, Down + }; + + public long getId(); + + public String getName(); + + public void setName(String name); + + public Region.State getStatus(); + + public Date getRemoved(); + + public String getEndPoint(); +} diff --git a/api/src/com/cloud/region/RegionService.java b/api/src/com/cloud/region/RegionService.java new file mode 100644 index 00000000000..e149776ad54 --- /dev/null +++ b/api/src/com/cloud/region/RegionService.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.region; + +import java.util.List; + +import com.cloud.api.commands.ListRegionsCmd; +import com.cloud.user.Account; + + +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 List listRegions(ListRegionsCmd cmd); +} diff --git a/server/src/com/cloud/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java new file mode 100644 index 00000000000..4b61bed5e54 --- /dev/null +++ b/server/src/com/cloud/region/RegionManager.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.region; + + +public interface RegionManager { + public boolean propogateAddResource(); + public boolean propogateUpdateResource(); + public boolean propogateDeleteResource(); + public boolean addResource(); + public boolean updateResource(); + public boolean deleteResource(); + + public long getId(); + public void setId(long id); +} diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java new file mode 100755 index 00000000000..a44087196f5 --- /dev/null +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -0,0 +1,149 @@ +// 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.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.api.commands.ListRegionsCmd; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.region.dao.RegionDao; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.Manager; + +@Local(value = { RegionManager.class, RegionService.class }) +public class RegionManagerImpl implements RegionManager, RegionService, Manager{ + public static final Logger s_logger = Logger.getLogger(RegionManagerImpl.class); + + @Inject + private RegionDao _regionDao; + + private String _name; + private long _id = 1; //ToDo, get this from config + + @Override + public boolean configure(final String name, final Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean propogateAddResource() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean propogateUpdateResource() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean propogateDeleteResource() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean addResource() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean updateResource() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deleteResource() { + // TODO Auto-generated method stub + return false; + } + + @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); + } + + if(endPoint != null){ + region.setEndPoint(endPoint); + } + + return region; + } + + @Override + public boolean removeRegion(long id) { + RegionVO region = _regionDao.findById(id); + if(region != null){ + return _regionDao.remove(id); + } else { + throw new InvalidParameterValueException("Failed to delete Region: " + id + ", Region not found"); + } + } + + public long getId() { + return _id; + } + + public void setId(long _id) { + this._id = _id; + } + + @Override + public List listRegions(ListRegionsCmd cmd) { + if(cmd.getId() != null){ + List regions = new ArrayList(); + regions.add(_regionDao.findById(cmd.getId())); + return regions; + } + return _regionDao.listAll(); + } + +} diff --git a/server/src/com/cloud/region/RegionVO.java b/server/src/com/cloud/region/RegionVO.java new file mode 100644 index 00000000000..3a3efd5219f --- /dev/null +++ b/server/src/com/cloud/region/RegionVO.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.region; + +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 +@Table(name="region") +public class RegionVO implements Region{ + + @Id + @Column(name="id") + long id; + + @Column(name="name") + String name; + + @Column(name="end_point") + String endPoint; + + @Column(name="status") + @Enumerated(value=EnumType.STRING) + Region.State status; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + public RegionVO() { + } + + public RegionVO(long id, String name, String endPoint) { + this.id = id; + this.name = name; + this.endPoint = endPoint; + this.status = Region.State.Down; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Region.State getStatus() { + return status; + } + + public void setStatus(Region.State status) { + this.status = status; + } + + public Date getRemoved() { + return removed; + } + + public String getEndPoint() { + return endPoint; + } + + public void setEndPoint(String endPoint) { + this.endPoint = endPoint; + } + + +} diff --git a/server/src/com/cloud/region/dao/RegionDao.java b/server/src/com/cloud/region/dao/RegionDao.java new file mode 100644 index 00000000000..a5efc16dab3 --- /dev/null +++ b/server/src/com/cloud/region/dao/RegionDao.java @@ -0,0 +1,19 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +// Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. Citrix Systems, Inc. +// reserves all rights not expressly granted by 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. +// +// Automatically generated by addcopyright.py at 04/03/2012 +package com.cloud.region.dao; + +import com.cloud.region.RegionVO; +import com.cloud.utils.db.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 new file mode 100644 index 00000000000..79d6d92592c --- /dev/null +++ b/server/src/com/cloud/region/dao/RegionDaoImpl.java @@ -0,0 +1,33 @@ +// 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.dao; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.region.RegionVO; +import com.cloud.utils.db.GenericDaoBase; + +@Local(value={RegionDao.class}) +public class RegionDaoImpl extends GenericDaoBase implements RegionDao { + private static final Logger s_logger = Logger.getLogger(RegionDaoImpl.class); + + public RegionDaoImpl(){ + + } +} From 470cd120d14a60cf34513179e265ab07e881b187 Mon Sep 17 00:00:00 2001 From: kishan Date: Thu, 5 Jul 2012 12:28:15 -0700 Subject: [PATCH 04/24] Added ASF license --- .../src/com/cloud/region/dao/RegionDao.java | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/server/src/com/cloud/region/dao/RegionDao.java b/server/src/com/cloud/region/dao/RegionDao.java index a5efc16dab3..829b8a6b467 100644 --- a/server/src/com/cloud/region/dao/RegionDao.java +++ b/server/src/com/cloud/region/dao/RegionDao.java @@ -1,15 +1,19 @@ -// Copyright 2012 Citrix Systems, Inc. Licensed under the -// Apache License, Version 2.0 (the "License"); you may not use this -// file except in compliance with the License. Citrix Systems, Inc. -// reserves all rights not expressly granted by 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. -// -// Automatically generated by addcopyright.py at 04/03/2012 +// 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.dao; import com.cloud.region.RegionVO; From 4ea36b82e9bb88e75f98982f8c302719f7520f2d Mon Sep 17 00:00:00 2001 From: kishan Date: Fri, 24 Aug 2012 15:59:59 +0530 Subject: [PATCH 05/24] propogate account changes to other Regions --- api/src/com/cloud/api/ApiConstants.java | 5 +- .../cloud/api/commands/CreateAccountCmd.java | 41 +++- .../cloud/api/commands/DeleteAccountCmd.java | 18 +- .../cloud/api/commands/DisableAccountCmd.java | 24 ++- .../cloud/api/commands/EnableAccountCmd.java | 16 +- .../cloud/api/commands/UpdateAccountCmd.java | 16 +- api/src/com/cloud/region/RegionService.java | 6 + api/src/com/cloud/user/Account.java | 4 + api/src/com/cloud/user/AccountService.java | 2 +- core/src/com/cloud/user/AccountVO.java | 4 +- core/src/com/cloud/user/UserVO.java | 7 +- .../cloud/projects/ProjectManagerImpl.java | 2 +- .../src/com/cloud/region/RegionManager.java | 7 +- .../com/cloud/region/RegionManagerImpl.java | 198 ++++++++++++++++-- server/src/com/cloud/region/RegionVO.java | 8 +- server/src/com/cloud/user/AccountManager.java | 2 +- .../com/cloud/user/AccountManagerImpl.java | 83 ++++++-- .../com/cloud/user/dao/AccountDaoImpl.java | 7 - 18 files changed, 380 insertions(+), 70 deletions(-) diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index 69e7939c82c..b5e60026086 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -358,7 +358,10 @@ public class ApiConstants { public static final String VSM_DEVICE_STATE = "vsmdevicestate"; public static final String ADD_VSM_FLAG = "addvsmflag"; public static final String END_POINT = "endpoint"; - + //public static final String REGION_DETAILS = "regiondetails"; + public static final String REGION_ID = "regionid"; + public static final String IS_PROPAGATE = "ispropagate"; + public enum HostDetails { all, capacity, events, stats, min; } diff --git a/api/src/com/cloud/api/commands/CreateAccountCmd.java b/api/src/com/cloud/api/commands/CreateAccountCmd.java index 00e87761c5d..9fc7d2d560c 100755 --- a/api/src/com/cloud/api/commands/CreateAccountCmd.java +++ b/api/src/com/cloud/api/commands/CreateAccountCmd.java @@ -76,6 +76,20 @@ public class CreateAccountCmd extends BaseCmd { @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; + + //@Parameter(name = ApiConstants.REGION_DETAILS, type = CommandType.MAP, description = "details for account used to store region specific parameters") + //private Map regionDetails; + + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.STRING, description="Account UUID, required for adding account from another Region") + private String accountUUID; + + @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; + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -130,11 +144,31 @@ public class CreateAccountCmd extends BaseCmd { return params; } + /*public Map getRegionDetails() { + if (regionDetails == null || regionDetails.isEmpty()) { + return null; + } + + return regionDetails; + }*/ + + public String getAccountUUID() { + return accountUUID; + } + + public String getUserUUID() { + return userUUID; + } + + public Long getRegionId() { + return regionId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } @@ -144,10 +178,11 @@ public class CreateAccountCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override + @Override public void execute(){ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); - UserAccount userAccount = _accountService.createUserAccount(getUsername(), getPassword(), getFirstName(), getLastName(), getEmail(), getTimeZone(), getAccountName(), getAccountType(), getDomainId(), getNetworkDomain(), getDetails()); + UserAccount userAccount = _accountService.createUserAccount(getUsername(), getPassword(), getFirstName(), getLastName(), getEmail(), getTimeZone(), getAccountName(), getAccountType(), getDomainId(), getNetworkDomain(), getDetails(), + getAccountUUID(), getUserUUID(), getRegionId()); if (userAccount != null) { AccountResponse response = _responseGenerator.createUserAccountResponse(userAccount); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/DeleteAccountCmd.java b/api/src/com/cloud/api/commands/DeleteAccountCmd.java index a7bfca78359..9b40e6bb1d7 100755 --- a/api/src/com/cloud/api/commands/DeleteAccountCmd.java +++ b/api/src/com/cloud/api/commands/DeleteAccountCmd.java @@ -46,15 +46,21 @@ public class DeleteAccountCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Account id") private Long id; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { + + public Long getId() { return id; } - + + public Boolean getIsPropagate() { + return isPropagate; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -93,7 +99,13 @@ public class DeleteAccountCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Account Id: "+getId()); - boolean result = _accountService.deleteUserAccount(getId()); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + boolean result = false; + if(isPopagate){ + result = _accountService.deleteUserAccount(getId()); + } else { + result = _regionService.deleteUserAccount(getId()); + } if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/DisableAccountCmd.java b/api/src/com/cloud/api/commands/DisableAccountCmd.java index 7c5e5e38331..ba22166f2dc 100644 --- a/api/src/com/cloud/api/commands/DisableAccountCmd.java +++ b/api/src/com/cloud/api/commands/DisableAccountCmd.java @@ -25,6 +25,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.AccountResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; @@ -55,6 +56,9 @@ public class DisableAccountCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.LOCK, type=CommandType.BOOLEAN, required=true, description="If true, only lock the account; else disable the account") private Boolean lockRequested; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -71,6 +75,10 @@ public class DisableAccountCmd extends BaseAsyncCmd { return domainId; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -109,10 +117,18 @@ public class DisableAccountCmd extends BaseAsyncCmd { public void execute() throws ConcurrentOperationException, ResourceUnavailableException{ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); Account result = null; - if(lockRequested) - result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); - else - result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + if(isPopagate){ + if(lockRequested) + result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); + else + result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); + } else { + if(lockRequested) + result = _regionService.lockAccount(getAccountName(), getDomainId(), getId()); + else + result = _regionService.disableAccount(getAccountName(), getDomainId(), getId()); + } if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/EnableAccountCmd.java b/api/src/com/cloud/api/commands/EnableAccountCmd.java index 576f9354892..536358e21cc 100644 --- a/api/src/com/cloud/api/commands/EnableAccountCmd.java +++ b/api/src/com/cloud/api/commands/EnableAccountCmd.java @@ -24,6 +24,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.AccountResponse; import com.cloud.user.Account; @@ -46,6 +47,9 @@ public class EnableAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Enables specified account in this domain.") private Long domainId; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -62,6 +66,10 @@ public class EnableAccountCmd extends BaseCmd { return domainId; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -88,7 +96,13 @@ public class EnableAccountCmd extends BaseCmd { @Override public void execute(){ - Account result = _accountService.enableAccount(getAccountName(), getDomainId(), getId()); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + Account result = null; + if(isPopagate){ + result = _accountService.enableAccount(getAccountName(), getDomainId(), getId()); + } else { + result = _regionService.enableAccount(getAccountName(), getDomainId(), getId()); + } if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/UpdateAccountCmd.java b/api/src/com/cloud/api/commands/UpdateAccountCmd.java index 8e3ef4364b3..377a61b24f0 100755 --- a/api/src/com/cloud/api/commands/UpdateAccountCmd.java +++ b/api/src/com/cloud/api/commands/UpdateAccountCmd.java @@ -27,6 +27,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.AccountResponse; import com.cloud.user.Account; @@ -59,6 +60,9 @@ public class UpdateAccountCmd extends BaseCmd{ @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -93,6 +97,10 @@ public class UpdateAccountCmd extends BaseCmd{ return params; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -118,7 +126,13 @@ public class UpdateAccountCmd extends BaseCmd{ @Override public void execute(){ - Account result = _accountService.updateAccount(this); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + Account result = null; + if(isPopagate){ + result = _accountService.updateAccount(this); + } else { + result = _regionService.updateAccount(this); + } if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/region/RegionService.java b/api/src/com/cloud/region/RegionService.java index e149776ad54..f9cfeba6aca 100644 --- a/api/src/com/cloud/region/RegionService.java +++ b/api/src/com/cloud/region/RegionService.java @@ -19,6 +19,7 @@ package com.cloud.region; import java.util.List; import com.cloud.api.commands.ListRegionsCmd; +import com.cloud.api.commands.UpdateAccountCmd; import com.cloud.user.Account; @@ -27,4 +28,9 @@ public interface RegionService { public Region updateRegion(long id, String name, String endPoint); public boolean removeRegion(long id); public List listRegions(ListRegionsCmd cmd); + boolean deleteUserAccount(long accountId); + Account updateAccount(UpdateAccountCmd cmd); + public Account lockAccount(String accountName, Long domainId, Long id); + public Account disableAccount(String accountName, Long domainId, Long id); + public Account enableAccount(String accountName, Long domainId, Long id); } diff --git a/api/src/com/cloud/user/Account.java b/api/src/com/cloud/user/Account.java index 18f585be75b..6ae93e2b3e4 100755 --- a/api/src/com/cloud/user/Account.java +++ b/api/src/com/cloud/user/Account.java @@ -61,4 +61,8 @@ public interface Account extends ControlledEntity { public String getNetworkDomain(); public Long getDefaultZoneId(); + + public long getRegionId(); + + public String getUuid(); } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 02e9b27f0f5..0cb36d4da3f 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); + Map details, String accountUUID, String userUUID, Long regionId); /** * Deletes a user by userId diff --git a/core/src/com/cloud/user/AccountVO.java b/core/src/com/cloud/user/AccountVO.java index a9bb51a9fba..629869d42bd 100644 --- a/core/src/com/cloud/user/AccountVO.java +++ b/core/src/com/cloud/user/AccountVO.java @@ -75,12 +75,14 @@ public class AccountVO implements Account, Identity { this.uuid = UUID.randomUUID().toString(); } - public AccountVO(String accountName, long domainId, String networkDomain, short type) { + public AccountVO(String accountName, long domainId, String networkDomain, short type, String uuid, long regionId) { this.accountName = accountName; this.domainId = domainId; this.networkDomain = networkDomain; this.type = type; this.state = State.enabled; + this.uuid = uuid; + this.regionId = regionId; } public void setNeedsCleanup(boolean value) { diff --git a/core/src/com/cloud/user/UserVO.java b/core/src/com/cloud/user/UserVO.java index efb0583f5a0..96e4465fee8 100644 --- a/core/src/com/cloud/user/UserVO.java +++ b/core/src/com/cloud/user/UserVO.java @@ -101,7 +101,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) { + public UserVO(long accountId, String username, String password, String firstName, String lastName, String email, String timezone, String uuid, long regionId) { this.accountId = accountId; this.username = username; this.password = password; @@ -110,9 +110,10 @@ public class UserVO implements User, Identity { this.email = email; this.timezone = timezone; this.state = State.enabled; - this.uuid = UUID.randomUUID().toString(); + this.uuid = uuid; + this.regionId = regionId; } - + @Override public long getId() { return id; diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 01fdeda84a9..b37e18302c3 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -199,7 +199,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); + Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, domainId, null, null, "", 0L); Project project = _projectDao.persist(new ProjectVO(name, displayText, owner.getDomainId(), projectAccount.getId())); diff --git a/server/src/com/cloud/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java index 4b61bed5e54..65b5cd64fab 100644 --- a/server/src/com/cloud/region/RegionManager.java +++ b/server/src/com/cloud/region/RegionManager.java @@ -16,11 +16,12 @@ // under the License. package com.cloud.region; +import java.util.Map; + public interface RegionManager { - public boolean propogateAddResource(); - public boolean propogateUpdateResource(); - public boolean propogateDeleteResource(); + 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, long regionId); public boolean addResource(); public boolean updateResource(); public boolean deleteResource(); diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index a44087196f5..804c1468fdd 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.region; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -23,13 +24,23 @@ 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.log4j.Logger; import com.cloud.api.commands.ListRegionsCmd; +import com.cloud.api.commands.UpdateAccountCmd; import com.cloud.exception.InvalidParameterValueException; import com.cloud.region.dao.RegionDao; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.AccountVO; +import com.cloud.user.dao.AccountDao; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; +import com.cloud.utils.exception.CloudRuntimeException; @Local(value = { RegionManager.class, RegionService.class }) public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @@ -37,9 +48,13 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @Inject private RegionDao _regionDao; + @Inject + private AccountDao _accountDao; + @Inject + private AccountManager _accountMgr; private String _name; - private long _id = 1; //ToDo, get this from config + private long _id = 1; //ToDo, get this from config or db.properties @Override public boolean configure(final String name, final Map params) throws ConfigurationException { @@ -63,23 +78,161 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } @Override - public boolean propogateAddResource() { - // TODO Auto-generated method stub - return false; + 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, long regionId) { + List regions = _regionDao.listAll(); + StringBuffer params = new StringBuffer("/api?command=createAccount"); + params.append("&username="+userName); + params.append("&password="+password); + params.append("&firstname="+firstName); + params.append("&lastname="+lastName); + params.append("&email="+email); + if(timezone != null){ + params.append("&timezone="+timezone); + } + if(accountName != null){ + params.append("&account="+accountName); + } + params.append("&accounttype="+accountType); + if(domainId != null){ + params.append("&domainid="+domainId); //use UUID + } + if(networkDomain != null){ + params.append("&networkdomain="+networkDomain); + } + if(details != null){ + params.append("&accountdetails="+details); //ToDo change to Map + } + params.append("&accountid="+accountUUID); + params.append("&userid="+userUUID); + params.append("®ionid="+regionId); + + 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)) { + 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; } @Override - public boolean propogateUpdateResource() { - // TODO Auto-generated method stub - return false; + public boolean deleteUserAccount(long accountId) { + AccountVO account = _accountDao.findById(accountId); + //Check null account + String accountUUID = account.getUuid(); + long regionId = account.getRegionId(); + String params = "/api?command=deleteAccount&id="+accountUUID+"&ispropagate=true"; + if(getId() == regionId){ + if(_accountMgr.deleteUserAccount(accountId)){ + List regions = _regionDao.listAll(); + for (Region region : regions){ + if(region.getId() == getId()){ + continue; + } + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while deleted account :"+accountUUID+" in Region: "+region.getId()); + } + } + return true; + } else { + return false; + } + } else { + //First delete in the Region where account is created + params = "/api?command=deleteAccount&id="+accountUUID; + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); + return true; + } else { + s_logger.error("Error while deleted account :"+accountUUID+" in Region: "+region.getId()); + return false; + } + } } - + @Override - public boolean propogateDeleteResource() { - // TODO Auto-generated method stub - return false; + public Account updateAccount(UpdateAccountCmd cmd) { + Long accountId = cmd.getId(); + Long domainId = cmd.getDomainId(); + String accountName = cmd.getAccountName(); + String newAccountName = cmd.getNewName(); + String networkDomain = cmd.getNetworkDomain(); + Map details = cmd.getDetails(); + + AccountVO account = _accountDao.findById(accountId); + //Check null account + String accountUUID = account.getUuid(); + long regionId = account.getRegionId(); + if(getId() == regionId){ + Account updateAccount = _accountMgr.updateAccount(cmd); + if(updateAccount != null){ + List regions = _regionDao.listAll(); + StringBuffer params = new StringBuffer("/api?command=updateAccount"+"&ispropagate=true"); + for (Region region : regions){ + if(region.getId() == getId()){ + continue; + } + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully updated account :"+accountUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while updated account :"+accountUUID+" in Region: "+region.getId()); + } + } + } + return updateAccount; + } else { + //First update in the Region where account is created + StringBuffer params = new StringBuffer("/api?command=updateAccount"); + //add params + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully updated account :"+accountUUID+" in source Region: "+region.getId()); + //return Account object + return null; + } else { + s_logger.error("Error while updated account :"+accountUUID+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } } + private boolean makeAPICall(String url){ + try { + + 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 boolean addResource() { // TODO Auto-generated method stub @@ -115,7 +268,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ region.setEndPoint(endPoint); } - return region; + _regionDao.update(id, region); + return _regionDao.findById(id); } @Override @@ -145,5 +299,23 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } return _regionDao.listAll(); } - + + @Override + public Account lockAccount(String accountName, Long domainId, Long id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account disableAccount(String accountName, Long domainId, Long id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Account enableAccount(String accountName, Long domainId, Long id) { + // TODO Auto-generated method stub + return null; + } + } diff --git a/server/src/com/cloud/region/RegionVO.java b/server/src/com/cloud/region/RegionVO.java index 3a3efd5219f..483659470f1 100644 --- a/server/src/com/cloud/region/RegionVO.java +++ b/server/src/com/cloud/region/RegionVO.java @@ -34,17 +34,17 @@ public class RegionVO implements Region{ @Id @Column(name="id") - long id; + private long id; @Column(name="name") - String name; + private String name; @Column(name="end_point") - String endPoint; + private String endPoint; @Column(name="status") @Enumerated(value=EnumType.STRING) - Region.State status; + private Region.State status; @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; diff --git a/server/src/com/cloud/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java index a7f5a68c83f..6904da7380d 100755 --- a/server/src/com/cloud/user/AccountManager.java +++ b/server/src/com/cloud/user/AccountManager.java @@ -45,7 +45,7 @@ public interface AccountManager extends AccountService { Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId); - Account createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details); + Account createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details, String uuid, long 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 cd63b4dd3cc..c174e5c6bad 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -85,6 +85,7 @@ import com.cloud.projects.ProjectManager; import com.cloud.projects.ProjectVO; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; +import com.cloud.region.RegionManager; import com.cloud.server.auth.UserAuthenticator; import com.cloud.storage.StorageManager; import com.cloud.storage.VMTemplateVO; @@ -199,8 +200,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag private ProjectAccountDao _projectAccountDao; @Inject private IPAddressDao _ipAddressDao; - //@Inject - //private RegionManager _regionMgr; + @Inject + private RegionManager _regionMgr; private Adapters _userAuthenticators; @@ -678,7 +679,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) { + Map details, String accountUUID, String userUUID, Long regionId) { if (accountName == null) { accountName = userName; @@ -720,25 +721,51 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } - Transaction txn = Transaction.currentTxn(); - txn.start(); + if(regionId == null){ + Transaction txn = Transaction.currentTxn(); + txn.start(); - // create account - Account account = createAccount(accountName, accountType, domainId, networkDomain, details); - long accountId = account.getId(); + // create account + AccountVO account = createAccount(accountName, accountType, domainId, networkDomain, details, UUID.randomUUID().toString(), _regionMgr.getId()); + long accountId = account.getId(); - // create the first user for the account - UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone); + // create the first user for the account + UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone); - if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - // set registration token - byte[] bytes = (domainId + accountName + userName + System.currentTimeMillis()).getBytes(); - String registrationToken = UUID.nameUUIDFromBytes(bytes).toString(); - user.setRegistrationToken(registrationToken); + if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // set registration token + byte[] bytes = (domainId + accountName + userName + System.currentTimeMillis()).getBytes(); + String registrationToken = UUID.nameUUIDFromBytes(bytes).toString(); + user.setRegistrationToken(registrationToken); + } + txn.commit(); + //Propogate Add account to other Regions + _regionMgr.propogateAddAccount(userName, password, firstName, lastName, email, timezone, accountName, accountType, domainId, + networkDomain, details, account.getUuid(), user.getUuid(), _regionMgr.getId()); + //check success + return _userAccountDao.findById(user.getId()); + } else { + // Account is propogated from another Region + + Transaction txn = Transaction.currentTxn(); + txn.start(); + + // create account + AccountVO account = createAccount(accountName, accountType, domainId, networkDomain, details, accountUUID, regionId); + long accountId = account.getId(); + + // create the first user for the account + UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone, userUUID, regionId); + + if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // set registration token + byte[] bytes = (domainId + accountName + userName + System.currentTimeMillis()).getBytes(); + String registrationToken = UUID.nameUUIDFromBytes(bytes).toString(); + user.setRegistrationToken(registrationToken); + } + txn.commit(); + return _userAccountDao.findById(user.getId()); } - - txn.commit(); - return _userAccountDao.findById(user.getId()); } @Override @@ -1061,7 +1088,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("The account id=" + accountId + " manages project(s) with ids " + projectIds + "and can't be removed"); } - return deleteAccount(account, callerUserId, caller); } @@ -1161,7 +1187,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag String newAccountName = cmd.getNewName(); String networkDomain = cmd.getNetworkDomain(); Map details = cmd.getDetails(); - + boolean success = false; Account account = null; if (accountId != null) { @@ -1516,7 +1542,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @DB - public Account createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details) { + public AccountVO createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details, String uuid, long regionId) { // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { @@ -1560,7 +1586,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); - Account account = _accountDao.persist(new AccountVO(accountName, domainId, networkDomain, accountType)); + AccountVO account = _accountDao.persist(new AccountVO(accountName, domainId, networkDomain, accountType, uuid, regionId)); if (account == null) { throw new CloudRuntimeException("Failed to create account name " + accountName + " in domain id=" + domainId); @@ -1589,7 +1615,18 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone); } - UserVO user = _userDao.persist(new UserVO(accountId, userName, password, firstName, lastName, email, timezone)); + + UserVO user = _userDao.persist(new UserVO(accountId, userName, password, firstName, lastName, email, timezone, UUID.randomUUID().toString(), _regionMgr.getId())); + + return user; + } + + //ToDo Add events?? + public UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone, String uuid, long regionId) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone); + } + UserVO user = _userDao.persist(new UserVO(accountId, userName, password, firstName, lastName, email, timezone, uuid, regionId)); return user; } diff --git a/server/src/com/cloud/user/dao/AccountDaoImpl.java b/server/src/com/cloud/user/dao/AccountDaoImpl.java index be14ec3e899..a7c399b8487 100755 --- a/server/src/com/cloud/user/dao/AccountDaoImpl.java +++ b/server/src/com/cloud/user/dao/AccountDaoImpl.java @@ -49,7 +49,6 @@ public class AccountDaoImpl extends GenericDaoBase implements A protected final SearchBuilder CleanupForRemovedAccountsSearch; protected final SearchBuilder CleanupForDisabledAccountsSearch; protected final SearchBuilder NonProjectAccountSearch; - private final long _regionId = 1; protected AccountDaoImpl() { AllFieldsSearch = createSearchBuilder(); @@ -260,10 +259,4 @@ public class AccountDaoImpl extends GenericDaoBase implements A } } - @Override - @DB - public AccountVO persist(AccountVO account) { - account.setRegionId(_regionId); - return super.persist(account); - } } From 39d394a8e807710d92da3995b32bcfa0b41078dd Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Thu, 27 Sep 2012 16:44:12 +0530 Subject: [PATCH 06/24] Propogate Domain and User commands --- .../cloud/api/commands/CreateAccountCmd.java | 8 - .../cloud/api/commands/CreateDomainCmd.java | 19 +- .../com/cloud/api/commands/CreateUserCmd.java | 17 +- .../cloud/api/commands/DeleteDomainCmd.java | 15 +- .../com/cloud/api/commands/DeleteUserCmd.java | 15 +- .../cloud/api/commands/DisableAccountCmd.java | 5 +- .../cloud/api/commands/DisableUserCmd.java | 17 +- .../com/cloud/api/commands/EnableUserCmd.java | 18 +- .../cloud/api/commands/UpdateDomainCmd.java | 18 +- .../com/cloud/api/commands/UpdateUserCmd.java | 17 +- api/src/com/cloud/domain/Domain.java | 2 + api/src/com/cloud/region/RegionService.java | 16 +- api/src/com/cloud/user/AccountService.java | 2 +- api/src/com/cloud/user/DomainService.java | 2 +- server/src/com/cloud/domain/DomainVO.java | 21 +- .../src/com/cloud/region/RegionManager.java | 10 +- .../com/cloud/region/RegionManagerImpl.java | 627 ++++++++++++++++-- .../com/cloud/user/AccountManagerImpl.java | 16 +- server/src/com/cloud/user/DomainManager.java | 2 +- .../src/com/cloud/user/DomainManagerImpl.java | 35 +- 20 files changed, 768 insertions(+), 114 deletions(-) diff --git a/api/src/com/cloud/api/commands/CreateAccountCmd.java b/api/src/com/cloud/api/commands/CreateAccountCmd.java index 9fc7d2d560c..21a51a65c97 100755 --- a/api/src/com/cloud/api/commands/CreateAccountCmd.java +++ b/api/src/com/cloud/api/commands/CreateAccountCmd.java @@ -144,14 +144,6 @@ public class CreateAccountCmd extends BaseCmd { return params; } - /*public Map getRegionDetails() { - if (regionDetails == null || regionDetails.isEmpty()) { - return null; - } - - return regionDetails; - }*/ - public String getAccountUUID() { return accountUUID; } diff --git a/api/src/com/cloud/api/commands/CreateDomainCmd.java b/api/src/com/cloud/api/commands/CreateDomainCmd.java index 92ee7ecefe9..29fd05018f8 100644 --- a/api/src/com/cloud/api/commands/CreateDomainCmd.java +++ b/api/src/com/cloud/api/commands/CreateDomainCmd.java @@ -24,6 +24,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.DomainResponse; import com.cloud.domain.Domain; import com.cloud.user.Account; @@ -49,6 +50,12 @@ public class CreateDomainCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for networks in the domain") private String networkDomain; + @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; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -63,8 +70,16 @@ public class CreateDomainCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; - } + } + public String getDomainUUID() { + return domainUUID; + } + + public Long getRegionId() { + return regionId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -82,7 +97,7 @@ public class CreateDomainCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("Domain Name: "+getDomainName()+((getParentDomainId()!=null)?", Parent DomainId :"+getParentDomainId():"")); - Domain domain = _domainService.createDomain(getDomainName(), getParentDomainId(), getNetworkDomain()); + Domain domain = _domainService.createDomain(getDomainName(), getParentDomainId(), getNetworkDomain(), getDomainUUID(), getRegionId()); if (domain != null) { DomainResponse response = _responseGenerator.createDomainResponse(domain); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/CreateUserCmd.java b/api/src/com/cloud/api/commands/CreateUserCmd.java index fc10437e257..66a27f08f9d 100644 --- a/api/src/com/cloud/api/commands/CreateUserCmd.java +++ b/api/src/com/cloud/api/commands/CreateUserCmd.java @@ -24,6 +24,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; @@ -64,6 +65,12 @@ public class CreateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="Unique username.") private String username; + @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; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -100,6 +107,14 @@ public class CreateUserCmd extends BaseCmd { return username; } + public String getUserUUID() { + return userUUID; + } + + public Long getRegionId() { + return regionId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -131,7 +146,7 @@ public class CreateUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserName: "+getUserName()+", FirstName :"+getFirstName()+", LastName: "+getLastName()); - User user = _accountService.createUser(getUserName(), getPassword(), getFirstName(), getLastName(), getEmail(), getTimezone(), getAccountName(), getDomainId()); + User user = _accountService.createUser(getUserName(), getPassword(), getFirstName(), getLastName(), getEmail(), getTimezone(), getAccountName(), getDomainId(), getUserUUID(), getRegionId()); if (user != null) { UserResponse response = _responseGenerator.createUserResponse(user); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/DeleteDomainCmd.java b/api/src/com/cloud/api/commands/DeleteDomainCmd.java index 3908256a192..5e371f7eb4c 100644 --- a/api/src/com/cloud/api/commands/DeleteDomainCmd.java +++ b/api/src/com/cloud/api/commands/DeleteDomainCmd.java @@ -25,6 +25,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.SuccessResponse; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; @@ -47,6 +48,8 @@ public class DeleteDomainCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.CLEANUP, type=CommandType.BOOLEAN, description="true if all domain resources (child domains, accounts) have to be cleaned up, false otherwise") private Boolean cleanup; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -60,6 +63,10 @@ public class DeleteDomainCmd extends BaseAsyncCmd { return cleanup; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -92,7 +99,13 @@ public class DeleteDomainCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); - boolean result = _domainService.deleteDomain(id, cleanup); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + boolean result = false; + if(isPopagate){ + result = _domainService.deleteDomain(id, cleanup); + } else { + result = _regionService.deleteDomain(id, cleanup); + } if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/DeleteUserCmd.java b/api/src/com/cloud/api/commands/DeleteUserCmd.java index e43649591fc..846e03c88ad 100644 --- a/api/src/com/cloud/api/commands/DeleteUserCmd.java +++ b/api/src/com/cloud/api/commands/DeleteUserCmd.java @@ -43,6 +43,9 @@ public class DeleteUserCmd extends BaseCmd { @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Deletes a user") private Long id; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,6 +54,10 @@ public class DeleteUserCmd extends BaseCmd { return id; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -73,7 +80,13 @@ public class DeleteUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - boolean result = _accountService.deleteUser(this); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + boolean result = false; + if(isPopagate){ + result = _accountService.deleteUser(this); + } else { + result = _regionService.deleteUser(this); + } if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/DisableAccountCmd.java b/api/src/com/cloud/api/commands/DisableAccountCmd.java index ba22166f2dc..572c5095090 100644 --- a/api/src/com/cloud/api/commands/DisableAccountCmd.java +++ b/api/src/com/cloud/api/commands/DisableAccountCmd.java @@ -124,10 +124,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { else result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); } else { - if(lockRequested) - result = _regionService.lockAccount(getAccountName(), getDomainId(), getId()); - else - result = _regionService.disableAccount(getAccountName(), getDomainId(), getId()); + result = _regionService.disableAccount(getAccountName(), getDomainId(), getId(), lockRequested); } if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); diff --git a/api/src/com/cloud/api/commands/DisableUserCmd.java b/api/src/com/cloud/api/commands/DisableUserCmd.java index 407042dfc40..d068a4cffb9 100644 --- a/api/src/com/cloud/api/commands/DisableUserCmd.java +++ b/api/src/com/cloud/api/commands/DisableUserCmd.java @@ -25,6 +25,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.UserResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; @@ -46,6 +47,9 @@ public class DisableUserCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Disables user by user ID.") private Long id; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -54,6 +58,10 @@ public class DisableUserCmd extends BaseAsyncCmd { return id; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -87,7 +95,14 @@ public class DisableUserCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - UserAccount user = _accountService.disableUser(getId()); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + UserAccount user = null; + if(isPopagate){ + user = _accountService.disableUser(getId()); + } else { + user = _regionService.disableUser(getId()); + } + if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/EnableUserCmd.java b/api/src/com/cloud/api/commands/EnableUserCmd.java index 914d59bb4ea..0b8d950bf80 100644 --- a/api/src/com/cloud/api/commands/EnableUserCmd.java +++ b/api/src/com/cloud/api/commands/EnableUserCmd.java @@ -24,6 +24,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; @@ -43,7 +44,9 @@ public class EnableUserCmd extends BaseCmd { @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Enables user by user ID.") private Long id; - + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -52,6 +55,10 @@ public class EnableUserCmd extends BaseCmd { return id; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -74,7 +81,14 @@ public class EnableUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - UserAccount user = _accountService.enableUser(getId()); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + UserAccount user = null; + if(isPopagate){ + user = _accountService.enableUser(getId()); + } else { + user = _regionService.enableUser(getId()); + } + if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/UpdateDomainCmd.java b/api/src/com/cloud/api/commands/UpdateDomainCmd.java index 739ae87ca05..20a0664f5bb 100644 --- a/api/src/com/cloud/api/commands/UpdateDomainCmd.java +++ b/api/src/com/cloud/api/commands/UpdateDomainCmd.java @@ -24,9 +24,11 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.DomainResponse; import com.cloud.domain.Domain; import com.cloud.user.Account; +import com.cloud.user.UserAccount; import com.cloud.user.UserContext; @Implementation(description="Updates a domain with a new name", responseObject=DomainResponse.class) @@ -48,6 +50,9 @@ public class UpdateDomainCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the domain's networks; empty string will update domainName with NULL value") private String networkDomain; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -64,6 +69,10 @@ public class UpdateDomainCmd extends BaseCmd { return networkDomain; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -81,7 +90,14 @@ public class UpdateDomainCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); - Domain domain = _mgr.updateDomain(this); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + Domain domain = null; + if(isPopagate){ + domain = _mgr.updateDomain(this); + } else { + domain = _regionService.updateDomain(this); + } + if (domain != null) { DomainResponse response = _responseGenerator.createDomainResponse(domain); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/UpdateUserCmd.java b/api/src/com/cloud/api/commands/UpdateUserCmd.java index 634b5d6cc14..14d383d4842 100644 --- a/api/src/com/cloud/api/commands/UpdateUserCmd.java +++ b/api/src/com/cloud/api/commands/UpdateUserCmd.java @@ -24,6 +24,7 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; @@ -68,6 +69,9 @@ public class UpdateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, description="Unique username") private String username; + @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") + private Boolean isPropagate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -108,6 +112,10 @@ public class UpdateUserCmd extends BaseCmd { return username; } + public Boolean getIsPropagate() { + return isPropagate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -130,7 +138,14 @@ public class UpdateUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - UserAccount user = _accountService.updateUser(this); + boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; + UserAccount user = null; + if(isPopagate){ + user = _accountService.updateUser(this); + } else { + user = _regionService.updateUser(this); + } + if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/domain/Domain.java b/api/src/com/cloud/domain/Domain.java index a7b4031dce5..59863471b8e 100644 --- a/api/src/com/cloud/domain/Domain.java +++ b/api/src/com/cloud/domain/Domain.java @@ -57,4 +57,6 @@ public interface Domain extends OwnedBy { void setState(State state); String getNetworkDomain(); + + public String getUuid(); } diff --git a/api/src/com/cloud/region/RegionService.java b/api/src/com/cloud/region/RegionService.java index f9cfeba6aca..8fa505821c1 100644 --- a/api/src/com/cloud/region/RegionService.java +++ b/api/src/com/cloud/region/RegionService.java @@ -18,9 +18,16 @@ package com.cloud.region; import java.util.List; +import com.cloud.api.commands.DeleteUserCmd; import com.cloud.api.commands.ListRegionsCmd; import com.cloud.api.commands.UpdateAccountCmd; +import com.cloud.api.commands.UpdateDomainCmd; +import com.cloud.api.commands.UpdateUserCmd; +import com.cloud.domain.Domain; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; +import com.cloud.user.UserAccount; public interface RegionService { @@ -30,7 +37,12 @@ public interface RegionService { public List listRegions(ListRegionsCmd cmd); boolean deleteUserAccount(long accountId); Account updateAccount(UpdateAccountCmd cmd); - public Account lockAccount(String accountName, Long domainId, Long id); - public Account disableAccount(String accountName, Long domainId, Long id); + public Account disableAccount(String accountName, Long domainId, Long id, Boolean lockRequested) throws ConcurrentOperationException, ResourceUnavailableException; public Account enableAccount(String accountName, Long domainId, Long id); + public boolean deleteUser(DeleteUserCmd deleteUserCmd); + public boolean deleteDomain(Long id, Boolean cleanup); + public UserAccount updateUser(UpdateUserCmd updateUserCmd); + public Domain updateDomain(UpdateDomainCmd updateDomainCmd); + public UserAccount disableUser(Long id); + public UserAccount enableUser(Long id); } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 0cb36d4da3f..15a1a5a0186 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -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); + User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Long regionId); boolean deleteUser(DeleteUserCmd deleteUserCmd); diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 362f87ea0be..4de14d1f210 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -25,7 +25,7 @@ import com.cloud.exception.PermissionDeniedException; public interface DomainService { - Domain createDomain(String name, Long parentId, String networkDomain); + Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID, Long regionId); Domain getDomain(long id); diff --git a/server/src/com/cloud/domain/DomainVO.java b/server/src/com/cloud/domain/DomainVO.java index a5cfe1bb8ff..52b10a7253a 100644 --- a/server/src/com/cloud/domain/DomainVO.java +++ b/server/src/com/cloud/domain/DomainVO.java @@ -75,13 +75,7 @@ public class DomainVO implements Domain, Identity { public DomainVO() {} - public DomainVO(long id, String name, long owner, Long parentId, String networkDomain) { - this(name, owner, parentId, networkDomain); - this.id = id; - this.uuid = UUID.randomUUID().toString(); - } - - public DomainVO(String name, long owner, Long parentId, String networkDomain) { + public DomainVO(String name, long owner, Long parentId, String networkDomain, Long regionId) { this.parent = parentId; this.name = name; this.accountId = owner; @@ -90,8 +84,21 @@ public class DomainVO implements Domain, Identity { this.state = Domain.State.Active; this.networkDomain = networkDomain; this.uuid = UUID.randomUUID().toString(); + this.regionId = regionId; } + public DomainVO(String name, long owner, Long parentId, String networkDomain, String uuid, Long regionId) { + this.parent = parentId; + this.name = name; + this.accountId = owner; + this.path =""; + this.level = 0; + this.state = Domain.State.Active; + this.networkDomain = networkDomain; + this.uuid = uuid; + this.regionId = regionId; + } + @Override public long getId() { return id; diff --git a/server/src/com/cloud/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java index 65b5cd64fab..d74633de1d2 100644 --- a/server/src/com/cloud/region/RegionManager.java +++ b/server/src/com/cloud/region/RegionManager.java @@ -21,11 +21,11 @@ import java.util.Map; 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, long regionId); - public boolean addResource(); - public boolean updateResource(); - public boolean deleteResource(); - + Map details, String accountUUID, String userUUID); public long getId(); public void setId(long 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); } diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index 804c1468fdd..96ff28e0d49 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -30,17 +30,30 @@ import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.log4j.Logger; +import com.cloud.api.ApiConstants; +import com.cloud.api.commands.DeleteUserCmd; import com.cloud.api.commands.ListRegionsCmd; import com.cloud.api.commands.UpdateAccountCmd; +import com.cloud.api.commands.UpdateDomainCmd; +import com.cloud.api.commands.UpdateUserCmd; +import com.cloud.domain.Domain; +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +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; +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.UserDao; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; -import com.cloud.utils.exception.CloudRuntimeException; @Local(value = { RegionManager.class, RegionService.class }) public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @@ -52,10 +65,22 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ private AccountDao _accountDao; @Inject private AccountManager _accountMgr; + @Inject + private UserDao _userDao; + @Inject + private DomainDao _domainDao; + @Inject + private ManagementServer _mgmtSrvr; + @Inject + private DomainManager _domainMgr; + private String _name; private long _id = 1; //ToDo, get this from config or db.properties + //ToDo use API constants + //prepare API params in advance + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; @@ -79,33 +104,33 @@ 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, long regionId) { + String accountName, short accountType, Long domainId, String networkDomain, Map details, String accountUUID, String userUUID) { List regions = _regionDao.listAll(); StringBuffer params = new StringBuffer("/api?command=createAccount"); - params.append("&username="+userName); - params.append("&password="+password); - params.append("&firstname="+firstName); - params.append("&lastname="+lastName); - params.append("&email="+email); + 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("&timezone="+timezone); + params.append("&"+ApiConstants.TIMEZONE+"="+timezone); } if(accountName != null){ - params.append("&account="+accountName); + params.append("&"+ApiConstants.ACCOUNT+"="+accountName); } - params.append("&accounttype="+accountType); + params.append("&"+ApiConstants.ACCOUNT_TYPE+"="+accountType); if(domainId != null){ - params.append("&domainid="+domainId); //use UUID + params.append("&"+ApiConstants.DOMAIN_ID+"="+domainId); //use UUID } if(networkDomain != null){ - params.append("&networkdomain="+networkDomain); + params.append("&"+ApiConstants.NETWORK_DOMAIN+"="+networkDomain); } if(details != null){ - params.append("&accountdetails="+details); //ToDo change to Map + params.append("&"+ApiConstants.ACCOUNT_DETAILS+"="+details); //ToDo change to Map } - params.append("&accountid="+accountUUID); - params.append("&userid="+userUUID); - params.append("®ionid="+regionId); + 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()){ @@ -127,10 +152,12 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @Override public boolean deleteUserAccount(long accountId) { AccountVO account = _accountDao.findById(accountId); - //Check null account + if(account == null){ + return false; + } String accountUUID = account.getUuid(); long regionId = account.getRegionId(); - String params = "/api?command=deleteAccount&id="+accountUUID+"&ispropagate=true"; + String params = "/api?command=deleteAccount&"+ApiConstants.ID+"="+accountUUID; if(getId() == regionId){ if(_accountMgr.deleteUserAccount(accountId)){ List regions = _regionDao.listAll(); @@ -138,11 +165,11 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params; + String url = region.getEndPoint() + params+"&"+ApiConstants.IS_PROPAGATE+"=true"; if (makeAPICall(url)) { s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); } else { - s_logger.error("Error while deleted account :"+accountUUID+" in Region: "+region.getId()); + s_logger.error("Error while deleting account :"+accountUUID+" in Region: "+region.getId()); } } return true; @@ -151,14 +178,13 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } else { //First delete in the Region where account is created - params = "/api?command=deleteAccount&id="+accountUUID; Region region = _regionDao.findById(regionId); String url = region.getEndPoint() + params; if (makeAPICall(url)) { s_logger.debug("Successfully deleted account :"+accountUUID+" in Region: "+region.getId()); return true; } else { - s_logger.error("Error while deleted account :"+accountUUID+" in Region: "+region.getId()); + s_logger.error("Error while deleting account :"+accountUUID+" in Region: "+region.getId()); return false; } } @@ -168,45 +194,71 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ public Account updateAccount(UpdateAccountCmd cmd) { Long accountId = cmd.getId(); Long domainId = cmd.getDomainId(); + DomainVO domain = _domainDao.findById(domainId); String accountName = cmd.getAccountName(); String newAccountName = cmd.getNewName(); String networkDomain = cmd.getNetworkDomain(); Map details = cmd.getDetails(); - AccountVO account = _accountDao.findById(accountId); - //Check null account - String accountUUID = account.getUuid(); + Account account = null; + if (accountId != null) { + account = _accountDao.findById(accountId); + } else { + account = _accountDao.findEnabledAccount(accountName, domainId); + } + + // Check if account exists + if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + s_logger.error("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + } + + StringBuffer params = new StringBuffer("/api?command=updateAccount"); + 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(); if(getId() == regionId){ Account updateAccount = _accountMgr.updateAccount(cmd); if(updateAccount != null){ List regions = _regionDao.listAll(); - StringBuffer params = new StringBuffer("/api?command=updateAccount"+"&ispropagate=true"); for (Region region : regions){ if(region.getId() == getId()){ continue; } - String url = region.getEndPoint() + params; + String url = region.getEndPoint() + params+"&"+ApiConstants.IS_PROPAGATE+"=true"; if (makeAPICall(url)) { - s_logger.debug("Successfully updated account :"+accountUUID+" in Region: "+region.getId()); + s_logger.debug("Successfully updated account :"+account.getUuid()+" in Region: "+region.getId()); } else { - s_logger.error("Error while updated account :"+accountUUID+" in Region: "+region.getId()); + s_logger.error("Error while updating account :"+account.getUuid()+" in Region: "+region.getId()); } } } return updateAccount; } else { //First update in the Region where account is created - StringBuffer params = new StringBuffer("/api?command=updateAccount"); - //add params Region region = _regionDao.findById(regionId); String url = region.getEndPoint() + params; if (makeAPICall(url)) { - s_logger.debug("Successfully updated account :"+accountUUID+" in source Region: "+region.getId()); + s_logger.debug("Successfully updated account :"+account.getUuid()+" in source Region: "+region.getId()); //return Account object return null; } else { - s_logger.error("Error while updated account :"+accountUUID+" in source Region: "+region.getId()); + s_logger.error("Error while updating account :"+account.getUuid()+" in source Region: "+region.getId()); //throw exception; return null; } @@ -233,24 +285,6 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } - @Override - public boolean addResource() { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean updateResource() { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean deleteResource() { - // TODO Auto-generated method stub - return false; - } - @Override public Region addRegion(long id, String name, String endPoint) { RegionVO region = new RegionVO(id, name, endPoint); @@ -301,21 +335,494 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } @Override - public Account lockAccount(String accountName, Long domainId, Long id) { - // TODO Auto-generated method stub - return null; + public Account disableAccount(String accountName, Long domainId, Long accountId, Boolean lockRequested) throws ConcurrentOperationException, ResourceUnavailableException { + Account account = null; + if (accountId != null) { + account = _accountDao.findById(accountId); + } else { + account = _accountDao.findActiveAccount(accountName, domainId); + } + + if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + 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); + } + DomainVO domain = _domainDao.findById(domainId); + if(domain != null){ + params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); + } + long regionId = account.getRegionId(); + if(getId() == regionId){ + Account retAccount = null; + if(lockRequested){ + retAccount = _accountMgr.lockAccount(accountName, domainId, accountId); + } else { + retAccount = _accountMgr.disableAccount(accountName, domainId, accountId); + } + if(retAccount != 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)) { + s_logger.debug("Successfully disabled account :"+accountUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while disabling account :"+accountUUID+" in Region: "+region.getId()); + } + } + } + return retAccount; + } else { + //First disable account in the Region where account is created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully disabled account :"+accountUUID+" in source Region: "+region.getId()); + //return Account object + return null; + } else { + s_logger.error("Error while disabling account :"+accountUUID+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } } @Override - public Account disableAccount(String accountName, Long domainId, Long id) { - // TODO Auto-generated method stub - return null; + public Account enableAccount(String accountName, Long domainId, Long accountId) { + // Check if account exists + Account account = null; + if (accountId != null) { + account = _accountDao.findById(accountId); + } else { + account = _accountDao.findActiveAccount(accountName, domainId); + } + + if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + 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); + } + DomainVO domain = _domainDao.findById(domainId); + if(domain != null){ + params.append("&"+ApiConstants.DOMAIN_ID+"="+domain.getUuid()); + } + + long regionId = account.getRegionId(); + if(getId() == regionId){ + Account retAccount = _accountMgr.enableAccount(accountName, domainId, accountId); + if(retAccount != 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)) { + s_logger.debug("Successfully enabled account :"+accountUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while enabling account :"+accountUUID+" in Region: "+region.getId()); + } + } + } + return retAccount; + } else { + //First disable account in the Region where account is created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully enabled account :"+accountUUID+" in source Region: "+region.getId()); + //return Account object + return null; + } else { + s_logger.error("Error while enabling account :"+accountUUID+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } } @Override - public Account enableAccount(String accountName, Long domainId, Long id) { - // TODO Auto-generated method stub - return null; + public boolean deleteUser(DeleteUserCmd cmd) { + long id = cmd.getId(); + + UserVO user = _userDao.findById(id); + + if (user == null) { + throw new InvalidParameterValueException("The specified user doesn't exist in the system"); + } + + String userUUID = user.getUuid(); + long regionId = user.getRegionId(); + String params = "/api?command=deleteUser&id="+userUUID; + if(getId() == regionId){ + if(_accountMgr.deleteUser(cmd)){ + 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)) { + s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while deleting account :"+userUUID+" in Region: "+region.getId()); + } + } + return true; + } else { + return false; + } + } else { + //First delete in the Region where account is created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); + return true; + } else { + s_logger.error("Error while deleting user :"+userUUID+" in Region: "+region.getId()); + return false; + } + } } + @Override + public boolean deleteDomain(Long id, Boolean cleanup) { + + DomainVO domain = _domainDao.findById(id); + if(domain == null){ + 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(); + if(getId() == regionId){ + if(_domainMgr.deleteDomain(id, cleanup)){ + 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)) { + s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while deleting domain :"+domainUUID+" in Region: "+region.getId()); + } + } + return true; + } else { + return false; + } + } else { + //First delete in the Region where domain is created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully deleted domain :"+domainUUID+" in Region: "+region.getId()); + return true; + } else { + s_logger.error("Error while deleting domain :"+domainUUID+" in Region: "+region.getId()); + return false; + } + } + } + + @Override + public UserAccount updateUser(UpdateUserCmd cmd){ + long id = cmd.getId(); + + UserVO user = _userDao.findById(id); + + if (user == null) { + 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(); + if(getId() == regionId){ + UserAccount updateUser = _accountMgr.updateUser(cmd); + if(updateUser != 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)) { + s_logger.debug("Successfully updated user :"+userUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while updating user :"+userUUID+" in Region: "+region.getId()); + } + } + } + return updateUser; + } else { + //First update in the Region where user was created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully updated user :"+userUUID+" in source Region: "+region.getId()); + //return object + return null; + } else { + s_logger.error("Error while updating user :"+userUUID+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } + } + + @Override + public Domain updateDomain(UpdateDomainCmd cmd) { + long id = cmd.getId(); + DomainVO domain = _domainDao.findById(id); + if(domain == null){ + 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(); + if(getId() == regionId){ + Domain updatedDomain = _mgmtSrvr.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)) { + s_logger.debug("Successfully updated updatedDomain :"+domainUUID+" in Region: "+region.getId()); + } else { + s_logger.error("Error while updating updatedDomain :"+domainUUID+" in Region: "+region.getId()); + } + } + } + return updatedDomain; + } else { + //First update in the Region where domain was created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully updated user :"+domainUUID+" in source Region: "+region.getId()); + //return object + return null; + } else { + s_logger.error("Error while updating user :"+domainUUID+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } + } + + @Override + public UserAccount disableUser(Long userId) { + UserVO user = _userDao.findById(userId); + 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()); + if(getId() == regionId){ + UserAccount disabledUser = _accountMgr.disableUser(userId); + if(disabledUser != 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)) { + 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()); + } + } + } + return disabledUser; + } else { + //First disable in the Region where user was created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully disabled user :"+user.getUuid()+" in source Region: "+region.getId()); + //return object + return null; + } else { + s_logger.error("Error while disabling user :"+user.getUuid()+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } + } + + @Override + public UserAccount enableUser(Long userId) { + UserVO user = _userDao.findById(userId); + 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()); + if(getId() == regionId){ + UserAccount enabledUser = _accountMgr.enableUser(userId); + if(enabledUser != 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)) { + 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()); + } + } + } + return enabledUser; + } else { + //First enable in the Region where user was created + Region region = _regionDao.findById(regionId); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + s_logger.debug("Successfully enabled user :"+user.getUuid()+" in source Region: "+region.getId()); + //return object + return null; + } else { + s_logger.error("Error while enabling user :"+user.getUuid()+" in source Region: "+region.getId()); + //throw exception; + return null; + } + } + } + + @Override + public void propogateAddUser(String userName, String password, + 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()); + + List regions = _regionDao.listAll(); + 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)) { + 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; + } + + @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; + if(parentId != null){ + DomainVO domain = _domainDao.findById(parentId); + if(domain != null){ + parentUUID = domain.getUuid(); + params.append("&ApiConstants.PARENT_DOMAIN_ID="+parentUUID); + } + } + if(networkDomain != null){ + params.append("&ApiConstants.NETWORK_DOMAIN="+networkDomain); + } + params.append("&ApiConstants.DOMAIN_ID="+uuid); + params.append("&ApiConstants.REGION_ID="+getId()); + + List regions = _regionDao.listAll(); + for (Region region : regions){ + if(region.getId() == getId()){ + continue; + } + s_logger.debug("Adding domain :"+name+" to Region: "+region.getId()); + String url = region.getEndPoint() + params; + if (makeAPICall(url)) { + 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; + + } + } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index c174e5c6bad..f603ec325cf 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -49,6 +49,7 @@ import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.configuration.dao.ConfigurationDaoImpl; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.DataCenterDao; @@ -741,7 +742,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag txn.commit(); //Propogate Add account to other Regions _regionMgr.propogateAddAccount(userName, password, firstName, lastName, email, timezone, accountName, accountType, domainId, - networkDomain, details, account.getUuid(), user.getUuid(), _regionMgr.getId()); + networkDomain, details, account.getUuid(), user.getUuid()); //check success return _userAccountDao.findById(user.getId()); } else { @@ -769,7 +770,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) { + public UserVO createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Long regionId) { // default domain to ROOT if not specified if (domainId == null) { @@ -793,9 +794,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { throw new CloudRuntimeException("The user " + userName + " already exists in domain " + domainId); } - - UserVO user = createUser(account.getId(), userName, password, firstName, lastName, email, timeZone); - + UserVO user = null; + if(regionId == null){ + user = createUser(account.getId(), userName, password, firstName, lastName, email, timeZone); + //Propogate Add user to other Regions + _regionMgr.propogateAddUser(userName, password, firstName, lastName, email, timeZone, accountName, domain.getUuid(), user.getUuid()); + } else { + user = createUser(account.getId(), userName, password, firstName, lastName, email, timeZone, userUUID, regionId); + } return user; } diff --git a/server/src/com/cloud/user/DomainManager.java b/server/src/com/cloud/user/DomainManager.java index 9d8b75af4bc..5183f8c519d 100644 --- a/server/src/com/cloud/user/DomainManager.java +++ b/server/src/com/cloud/user/DomainManager.java @@ -21,7 +21,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); + Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Long regionId); /** * find the domain by its path diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 3223d8c1c28..84ba3d97795 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -38,6 +38,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.ProjectManager; import com.cloud.projects.ProjectVO; import com.cloud.projects.dao.ProjectDao; +import com.cloud.region.RegionManager; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; @@ -74,7 +75,9 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager private ProjectDao _projectDao; @Inject private ProjectManager _projectMgr; - + @Inject + private RegionManager _regionMgr; + @Override public Domain getDomain(long domainId) { return _domainDao.findById(domainId); @@ -124,7 +127,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) { + public Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID, Long regionId) { Account caller = UserContext.current().getCaller(); if (parentId == null) { @@ -142,13 +145,13 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager _accountMgr.checkAccess(caller, parentDomain); - return createDomain(name, parentId, caller.getId(), networkDomain); + return createDomain(name, parentId, caller.getId(), networkDomain, domainUUID, regionId); } @Override @DB - public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain) { + public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID, Long regionId) { // Verify network domain if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { @@ -167,15 +170,27 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager throw new InvalidParameterValueException("Domain with name " + name + " already exists for the parent id=" + parentId); } - Transaction txn = Transaction.currentTxn(); - txn.start(); + if(regionId == null){ + Transaction txn = Transaction.currentTxn(); + txn.start(); - DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain)); - _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain); + DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, _regionMgr.getId())); + _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain); + _regionMgr.propogateAddDomain(name, parentId, networkDomain, domain.getUuid()); + txn.commit(); + return domain; + } else { + Transaction txn = Transaction.currentTxn(); + txn.start(); - txn.commit(); + DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, domainUUID, regionId)); + _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain); - return domain; + txn.commit(); + return domain; + + } + } @Override From f0f33bf4da7948f2109d0e07a4d80c4e362d86b8 Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Wed, 17 Oct 2012 14:16:36 +0530 Subject: [PATCH 07/24] 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 + From c40aac0add91e4fc9bc7cd2df66e27b750090ebe Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Wed, 17 Oct 2012 17:02:13 +0530 Subject: [PATCH 08/24] Add Mock managers for Regio API server --- server/test/com/cloud/api/RegionTest.java | 42 ++ .../RegionsComponentLibrary.java | 230 +++++++++ .../vpn/MockRemoteAccessVpnManagerImpl.java | 129 +++++ .../server/MockManagementServerImpl.java | 483 ++++++++++++++++++ .../snapshot/MockSnapshotManagerImpl.java | 236 +++++++++ .../template/MockTemplateManagerImpl.java | 211 ++++++++ 6 files changed, 1331 insertions(+) create mode 100644 server/test/com/cloud/api/RegionTest.java create mode 100755 server/test/com/cloud/configuration/RegionsComponentLibrary.java create mode 100755 server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java create mode 100755 server/test/com/cloud/server/MockManagementServerImpl.java create mode 100755 server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java create mode 100755 server/test/com/cloud/template/MockTemplateManagerImpl.java diff --git a/server/test/com/cloud/api/RegionTest.java b/server/test/com/cloud/api/RegionTest.java new file mode 100644 index 00000000000..9ddade33f21 --- /dev/null +++ b/server/test/com/cloud/api/RegionTest.java @@ -0,0 +1,42 @@ +// 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.File; + +import org.apache.log4j.Logger; +import org.apache.log4j.xml.DOMConfigurator; + +import com.cloud.server.ManagementService; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.component.ComponentLocator; + +public class RegionTest { + private static final Logger s_logger = Logger.getLogger(RegionTest.class.getName()); + + public static void main(String args[]){ + System.out.println("Starting"); + File file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); + if (file != null) { + s_logger.info("log4j configuration found at " + file.getAbsolutePath()); + DOMConfigurator.configureAndWatch(file.getAbsolutePath()); + } + final ComponentLocator _locator = ComponentLocator.getLocator(ManagementService.Name, "components-regions.xml", "log4j-cloud"); + MockApiServer.initApiServer(new String[] { "commands.properties" }); + System.out.println("Started"); + } +} \ No newline at end of file diff --git a/server/test/com/cloud/configuration/RegionsComponentLibrary.java b/server/test/com/cloud/configuration/RegionsComponentLibrary.java new file mode 100755 index 00000000000..75ac6b6ace0 --- /dev/null +++ b/server/test/com/cloud/configuration/RegionsComponentLibrary.java @@ -0,0 +1,230 @@ +// 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.configuration; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.cloud.alert.AlertManagerImpl; +import com.cloud.alert.dao.AlertDaoImpl; +import com.cloud.capacity.dao.CapacityDaoImpl; +import com.cloud.configuration.dao.ConfigurationDaoImpl; +import com.cloud.configuration.dao.ResourceCountDaoImpl; +import com.cloud.configuration.dao.ResourceLimitDaoImpl; +import com.cloud.dao.EntityManager; +import com.cloud.dao.EntityManagerImpl; +import com.cloud.dc.dao.AccountVlanMapDaoImpl; +import com.cloud.dc.dao.ClusterDaoImpl; +import com.cloud.dc.dao.DataCenterDaoImpl; +import com.cloud.dc.dao.HostPodDaoImpl; +import com.cloud.dc.dao.VlanDaoImpl; +import com.cloud.domain.dao.DomainDaoImpl; +import com.cloud.host.dao.HostDaoImpl; +import com.cloud.network.MockNetworkManagerImpl; +import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; +import com.cloud.network.dao.IPAddressDaoImpl; +import com.cloud.network.dao.LoadBalancerDaoImpl; +import com.cloud.network.dao.NetworkDaoImpl; +import com.cloud.network.dao.NetworkDomainDaoImpl; +import com.cloud.network.dao.NetworkRuleConfigDaoImpl; +import com.cloud.network.dao.RemoteAccessVpnDaoImpl; +import com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl; +import com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl; +import com.cloud.network.dao.VpnUserDaoImpl; +import com.cloud.network.security.MockSecurityGroupManagerImpl; +import com.cloud.network.security.dao.SecurityGroupDaoImpl; +import com.cloud.network.vpc.dao.VpcDaoImpl; +import com.cloud.network.vpn.MockRemoteAccessVpnManagerImpl; +import com.cloud.offerings.dao.NetworkOfferingDaoImpl; +import com.cloud.projects.MockProjectManagerImpl; +import com.cloud.projects.dao.ProjectAccountDaoImpl; +import com.cloud.projects.dao.ProjectDaoImpl; +import com.cloud.region.RegionManagerImpl; +import com.cloud.region.dao.RegionDaoImpl; +import com.cloud.resourcelimit.ResourceLimitManagerImpl; +import com.cloud.service.dao.ServiceOfferingDaoImpl; +import com.cloud.storage.MockStorageManagerImpl; +import com.cloud.storage.dao.DiskOfferingDaoImpl; +import com.cloud.storage.dao.GuestOSCategoryDaoImpl; +import com.cloud.storage.dao.GuestOSDaoImpl; +import com.cloud.storage.dao.LaunchPermissionDaoImpl; +import com.cloud.storage.dao.SnapshotDaoImpl; +import com.cloud.storage.dao.StoragePoolDaoImpl; +import com.cloud.storage.dao.UploadDaoImpl; +import com.cloud.storage.dao.VMTemplateDaoImpl; +import com.cloud.storage.dao.VMTemplateDetailsDaoImpl; +import com.cloud.storage.dao.VMTemplateHostDaoImpl; +import com.cloud.storage.dao.VMTemplateSwiftDaoImpl; +import com.cloud.storage.dao.VMTemplateZoneDaoImpl; +import com.cloud.storage.dao.VolumeDaoImpl; +import com.cloud.storage.dao.VolumeHostDaoImpl; +import com.cloud.storage.snapshot.MockSnapshotManagerImpl; +import com.cloud.template.MockTemplateManagerImpl; +import com.cloud.user.AccountDetailsDaoImpl; +import com.cloud.user.AccountManagerImpl; +import com.cloud.user.DomainManagerImpl; +import com.cloud.user.dao.AccountDaoImpl; +import com.cloud.user.dao.SSHKeyPairDaoImpl; +import com.cloud.user.dao.UserAccountDaoImpl; +import com.cloud.user.dao.UserDaoImpl; +import com.cloud.user.dao.UserStatisticsDaoImpl; +import com.cloud.utils.component.Adapter; +import com.cloud.utils.component.ComponentLibrary; +import com.cloud.utils.component.ComponentLibraryBase; +import com.cloud.utils.component.ComponentLocator.ComponentInfo; +import com.cloud.utils.component.Manager; +import com.cloud.utils.component.PluggableService; +import com.cloud.utils.db.GenericDao; +import com.cloud.uuididentity.dao.IdentityDaoImpl; +import com.cloud.vm.MockUserVmManagerImpl; +import com.cloud.vm.MockVirtualMachineManagerImpl; +import com.cloud.vm.dao.ConsoleProxyDaoImpl; +import com.cloud.vm.dao.DomainRouterDaoImpl; +import com.cloud.vm.dao.InstanceGroupDaoImpl; +import com.cloud.vm.dao.UserVmDaoImpl; +import com.cloud.vm.dao.UserVmDetailsDaoImpl; +import com.cloud.vm.dao.VMInstanceDaoImpl; +import com.cloud.vpc.MockConfigurationManagerImpl; +import com.cloud.vpc.MockResourceLimitManagerImpl; +import com.cloud.vpc.MockSite2SiteVpnManagerImpl; +import com.cloud.vpc.MockVpcManagerImpl; + + +public class RegionsComponentLibrary extends ComponentLibraryBase implements ComponentLibrary { + protected void populateDaos() { + addDao("DomainDao", DomainDaoImpl.class); + addDao("AccountDao", AccountDaoImpl.class); + addDao("UserDao", UserDaoImpl.class); + addDao("UserAccountDao", UserAccountDaoImpl.class); + addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); + addDao("RegionDao", RegionDaoImpl.class); + addDao("IdentityDao", IdentityDaoImpl.class); + addDao("AccountVlanMapDao", AccountVlanMapDaoImpl.class); + addDao("CapacityDao", CapacityDaoImpl.class); + addDao("ClusterDao", ClusterDaoImpl.class); + addDao("ServiceOfferingDao", ServiceOfferingDaoImpl.class); + addDao("DiskOfferingDao", DiskOfferingDaoImpl.class); + addDao("DomainRouterDao", DomainRouterDaoImpl.class); + addDao("GuestOSDao", GuestOSDaoImpl.class); + addDao("GuestOSCategoryDao", GuestOSCategoryDaoImpl.class); + addDao("HostDao", HostDaoImpl.class); + addDao("IPAddressDao", IPAddressDaoImpl.class); + addDao("LoadBalancerDao", LoadBalancerDaoImpl.class); + addDao("NetworkRuleConfigDao", NetworkRuleConfigDaoImpl.class); + addDao("HostPodDao", HostPodDaoImpl.class); + addDao("SnapshotDao", SnapshotDaoImpl.class); + addDao("StoragePoolDao", StoragePoolDaoImpl.class); + addDao("ConfigurationDao", ConfigurationDaoImpl.class); + addDao("DataCenterDao", DataCenterDaoImpl.class); + addDao("VMTemplateZoneDao", VMTemplateZoneDaoImpl.class); + addDao("VMTemplateDetailsDao", VMTemplateDetailsDaoImpl.class); + addDao("VMTemplateDao", VMTemplateDaoImpl.class); + addDao("VMTemplateHostDao", VMTemplateHostDaoImpl.class); + addDao("VMTemplateSwiftDao", VMTemplateSwiftDaoImpl.class); + addDao("UploadDao", UploadDaoImpl.class); + addDao("UserDao", UserDaoImpl.class); + addDao("UserStatisticsDao", UserStatisticsDaoImpl.class); + addDao("UserVmDao", UserVmDaoImpl.class); + addDao("VlanDao", VlanDaoImpl.class); + addDao("VolumeDao", VolumeDaoImpl.class); + addDao("Site2SiteVpnGatewayDao", Site2SiteVpnGatewayDaoImpl.class); + addDao("Site2SiteCustomerGatewayDao", Site2SiteCustomerGatewayDaoImpl.class); + addDao("VolumeHostDao", VolumeHostDaoImpl.class); + addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); + addDao("NetworkConfigurationDao", NetworkDaoImpl.class); + addDao("ConsoleProxyDao", ConsoleProxyDaoImpl.class); + addDao("FirewallRulesCidrsDao", FirewallRulesCidrsDaoImpl.class); + addDao("VMInstanceDao", VMInstanceDaoImpl.class); + addDao("AccountDetailsDao", AccountDetailsDaoImpl.class); + addDao("NetworkDomainDao", NetworkDomainDaoImpl.class); + addDao("SSHKeyPairDao", SSHKeyPairDaoImpl.class); + addDao("UserVmDetailsDao", UserVmDetailsDaoImpl.class); + addDao("ResourceCountDao", ResourceCountDaoImpl.class); + addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); + addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); + addDao("VpnUserDao", VpnUserDaoImpl.class); + addDao("ProjectDao", ProjectDaoImpl.class); + addDao("ProjectAccountDao", ProjectAccountDaoImpl.class); + addDao("LaunchPermissionDao", LaunchPermissionDaoImpl.class); + } + + @Override + public synchronized Map>> getDaos() { + if (_daos.size() == 0) { + populateDaos(); + } + return _daos; + } + + protected void populateManagers() { + addManager("configuration manager", MockConfigurationManagerImpl.class); + addManager("account manager", AccountManagerImpl.class); + addManager("domain manager", DomainManagerImpl.class); + addManager("Region Manager", RegionManagerImpl.class); + addManager("ResourceLimit Manager", MockResourceLimitManagerImpl.class); + addManager("Network Manager", MockNetworkManagerImpl.class); + addManager("UserVm Manager", MockUserVmManagerImpl.class); + addManager("Vm Manager", MockVirtualMachineManagerImpl.class); + addManager("Project Manager", MockProjectManagerImpl.class); + addManager("Vpc Manager", MockVpcManagerImpl.class); + addManager("Site2SiteVpn Manager", MockSite2SiteVpnManagerImpl.class); + addManager("SecurityGroup Manager", MockSecurityGroupManagerImpl.class); + addManager("Snapshot Manager", MockSnapshotManagerImpl.class); + addManager("Template Manager", MockTemplateManagerImpl.class); + addManager("Storage Manager", MockStorageManagerImpl.class); + addManager("RemoteAccessVpn Manager", MockRemoteAccessVpnManagerImpl.class); + addManager("Entity Manager", EntityManagerImpl.class); + } + + @Override + public synchronized Map> getManagers() { + if (_managers.size() == 0) { + populateManagers(); + } + return _managers; + } + + protected void populateAdapters() { + } + + @Override + public synchronized Map>> getAdapters() { + if (_adapters.size() == 0) { + populateAdapters(); + } + return _adapters; + } + + @Override + public synchronized Map, Class> getFactories() { + HashMap, Class> factories = new HashMap, Class>(); + factories.put(EntityManager.class, EntityManagerImpl.class); + return factories; + } + + protected void populateServices() { + } + + @Override + public synchronized Map> getPluggableServices() { + if (_pluggableServices.size() == 0) { + populateServices(); + } + return _pluggableServices; + } +} diff --git a/server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java b/server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java new file mode 100755 index 00000000000..efda5c65ccb --- /dev/null +++ b/server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java @@ -0,0 +1,129 @@ +// 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.vpn; + +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.api.commands.ListRemoteAccessVpnsCmd; +import com.cloud.api.commands.ListVpnUsersCmd; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.RemoteAccessVpn; +import com.cloud.network.VpnUser; +import com.cloud.utils.component.Manager; + +@Local(value = RemoteAccessVpnService.class) +public class MockRemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manager { + + @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 RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, + String ipRange, boolean openFirewall, long networkId) + throws NetworkRuleConflictException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void destroyRemoteAccessVpn(long vpnServerAddressId) + throws ResourceUnavailableException { + // TODO Auto-generated method stub + + } + + @Override + public RemoteAccessVpn startRemoteAccessVpn(long vpnServerAddressId, + boolean openFirewall) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return null; + } + + @Override + public VpnUser addVpnUser(long vpnOwnerId, String userName, String password) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean removeVpnUser(long vpnOwnerId, String userName) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List listVpnUsers(long vpnOwnerId, String userName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean applyVpnUsers(long vpnOwnerId, String userName) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List searchForRemoteAccessVpns( + ListRemoteAccessVpnsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForVpnUsers(ListVpnUsersCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listRemoteAccessVpns(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public RemoteAccessVpn getRemoteAccessVpn(long vpnId) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/server/test/com/cloud/server/MockManagementServerImpl.java b/server/test/com/cloud/server/MockManagementServerImpl.java new file mode 100755 index 00000000000..d505ff47bab --- /dev/null +++ b/server/test/com/cloud/server/MockManagementServerImpl.java @@ -0,0 +1,483 @@ +// 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.server; + +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.cloud.alert.Alert; +import com.cloud.api.commands.CreateSSHKeyPairCmd; +import com.cloud.api.commands.DeleteSSHKeyPairCmd; +import com.cloud.api.commands.DestroySystemVmCmd; +import com.cloud.api.commands.ExtractVolumeCmd; +import com.cloud.api.commands.GetVMPasswordCmd; +import com.cloud.api.commands.ListAlertsCmd; +import com.cloud.api.commands.ListAsyncJobsCmd; +import com.cloud.api.commands.ListCapabilitiesCmd; +import com.cloud.api.commands.ListCapacityCmd; +import com.cloud.api.commands.ListCfgsByCmd; +import com.cloud.api.commands.ListClustersCmd; +import com.cloud.api.commands.ListDiskOfferingsCmd; +import com.cloud.api.commands.ListEventsCmd; +import com.cloud.api.commands.ListGuestOsCategoriesCmd; +import com.cloud.api.commands.ListGuestOsCmd; +import com.cloud.api.commands.ListHostsCmd; +import com.cloud.api.commands.ListIsosCmd; +import com.cloud.api.commands.ListPodsByCmd; +import com.cloud.api.commands.ListPublicIpAddressesCmd; +import com.cloud.api.commands.ListRoutersCmd; +import com.cloud.api.commands.ListSSHKeyPairsCmd; +import com.cloud.api.commands.ListServiceOfferingsCmd; +import com.cloud.api.commands.ListStoragePoolsCmd; +import com.cloud.api.commands.ListSystemVMsCmd; +import com.cloud.api.commands.ListTemplatesCmd; +import com.cloud.api.commands.ListVMGroupsCmd; +import com.cloud.api.commands.ListVlanIpRangesCmd; +import com.cloud.api.commands.ListZonesByCmd; +import com.cloud.api.commands.RebootSystemVmCmd; +import com.cloud.api.commands.RegisterSSHKeyPairCmd; +import com.cloud.api.commands.StopSystemVmCmd; +import com.cloud.api.commands.UpdateHostPasswordCmd; +import com.cloud.api.commands.UpdateIsoCmd; +import com.cloud.api.commands.UpdateTemplateCmd; +import com.cloud.api.commands.UpdateVMGroupCmd; +import com.cloud.api.commands.UpgradeSystemVMCmd; +import com.cloud.api.commands.UploadCustomCertificateCmd; +import com.cloud.async.AsyncJob; +import com.cloud.capacity.Capacity; +import com.cloud.configuration.Configuration; +import com.cloud.dc.DataCenter; +import com.cloud.dc.Pod; +import com.cloud.dc.Vlan; +import com.cloud.event.Event; +import com.cloud.event.EventVO; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.hypervisor.HypervisorCapabilities; +import com.cloud.info.ConsoleProxyInfo; +import com.cloud.network.IpAddress; +import com.cloud.network.router.VirtualRouter; +import com.cloud.offering.DiskOffering; +import com.cloud.offering.ServiceOffering; +import com.cloud.org.Cluster; +import com.cloud.storage.GuestOS; +import com.cloud.storage.GuestOSVO; +import com.cloud.storage.GuestOsCategory; +import com.cloud.storage.StoragePool; +import com.cloud.storage.StoragePoolVO; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.user.SSHKeyPair; +import com.cloud.utils.Pair; +import com.cloud.vm.InstanceGroup; +import com.cloud.vm.VirtualMachine; + +public class MockManagementServerImpl implements ManagementServer { + + @Override + public List listDataCenters(ListZonesByCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForConfigurations(ListCfgsByCmd c) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForServiceOfferings( + ListServiceOfferingsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForClusters(ListClustersCmd c) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForClusters(long zoneId, + Long startIndex, Long pageSizeVal, String hypervisorType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForPods(ListPodsByCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForServers(ListHostsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachineTemplate updateTemplate(UpdateIsoCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForEvents(ListEventsCmd c) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForRouters(ListRoutersCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForIPAddresses( + ListPublicIpAddressesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listGuestOSByCriteria(ListGuestOsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listGuestOSCategoriesByCriteria( + ListGuestOsCategoriesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachine stopSystemVM(StopSystemVmCmd cmd) + throws ResourceUnavailableException, ConcurrentOperationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachine startSystemVM(long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachine rebootSystemVM(RebootSystemVmCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachine destroySystemVM(DestroySystemVmCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForAlerts(ListAlertsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listCapacities(ListCapacityCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set> listIsos(ListIsosCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set> listTemplates(ListTemplatesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForDiskOfferings( + ListDiskOfferingsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForStoragePools( + ListStoragePoolsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForSystemVm(ListSystemVMsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ArrayList getCloudIdentifierResponse(long userId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean updateHostPassword(UpdateHostPasswordCmd cmd) { + // TODO Auto-generated method stub + return false; + } + + @Override + public InstanceGroup updateVmGroup(UpdateVMGroupCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForVmGroups(ListVMGroupsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map listCapabilities(ListCapabilitiesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getHypervisors(Long zoneId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String uploadCertificate(UploadCustomCertificateCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForVlans(ListVlanIpRangesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForAsyncJobs(ListAsyncJobsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String generateRandomPassword() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long saveStartedEvent(Long userId, Long accountId, String type, + String description, long startEventId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long saveCompletedEvent(Long userId, Long accountId, String level, + String type, String description, long startEventId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listSSHKeyPairs(ListSSHKeyPairsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public SSHKeyPair registerSSHKeyPair(RegisterSSHKeyPairCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deleteSSHKeyPair(DeleteSSHKeyPairCmd cmd) { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getVMPassword(GetVMPasswordCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public com.cloud.vm.VirtualMachine.Type findSystemVMTypeById(long instanceId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Pair, List> listHostsForMigrationOfVM( + Long vmId, Long startIndex, Long pageSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String[] listEventTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listHypervisorCapabilities( + Long id, HypervisorType hypervisorType, String keyword, + Long startIndex, Long pageSizeVal) { + // TODO Auto-generated method stub + return null; + } + + @Override + public HypervisorCapabilities updateHypervisorCapabilities(Long id, + Long maxGuestsLimit, Boolean securityGroupEnabled) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listTopConsumedResources(ListCapacityCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getId() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getVersion() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String[] getApiConfig() { + // TODO Auto-generated method stub + return null; + } + + @Override + public HostVO getHostBy(long hostId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getEvents(long userId, long accountId, Long domainId, + String type, String level, Date startDate, Date endDate) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ConsoleProxyInfo getConsoleProxyForVm(long dataCenterId, + long userVmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getConsoleAccessUrlRoot(long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public GuestOSVO getGuestOs(Long guestOsId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Pair getVncPort(VirtualMachine vm) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getMemoryOrCpuCapacityByHost(Long hostId, short capacityType) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public List searchForStoragePools(Criteria c) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getHashKey() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java b/server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java new file mode 100755 index 00000000000..c79966bd533 --- /dev/null +++ b/server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java @@ -0,0 +1,236 @@ +// 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.snapshot; + +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.api.commands.CreateSnapshotPolicyCmd; +import com.cloud.api.commands.DeleteSnapshotPoliciesCmd; +import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; +import com.cloud.api.commands.ListSnapshotPoliciesCmd; +import com.cloud.api.commands.ListSnapshotsCmd; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.host.HostVO; +import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotPolicyVO; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.VolumeVO; +import com.cloud.user.Account; +import com.cloud.utils.component.Manager; +import com.cloud.utils.db.Filter; + +@Local(value = { SnapshotManager.class, SnapshotService.class }) +public class MockSnapshotManagerImpl implements SnapshotManager, SnapshotService, Manager { + + @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 List listSnapshots(ListSnapshotsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deleteSnapshot(long snapshotId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SnapshotPolicy createPolicy(CreateSnapshotPolicyCmd cmd, + Account policyOwner) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List findRecurringSnapshotSchedule( + ListRecurringSnapshotScheduleCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listPoliciesforVolume( + ListSnapshotPoliciesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deleteSnapshotPolicies(DeleteSnapshotPoliciesCmd cmd) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Snapshot allocSnapshot(Long volumeId, Long policyId) + throws ResourceAllocationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Snapshot createSnapshot(Long volumeId, Long policyId, + Long snapshotId, Account snapshotOwner) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean backupSnapshotToSecondaryStorage(SnapshotVO snapshot) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void postCreateSnapshot(Long volumeId, Long snapshotId, + Long policyId, boolean backedUp) { + // TODO Auto-generated method stub + + } + + @Override + public boolean destroySnapshot(long userId, long snapshotId, long policyId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deletePolicy(long userId, Long policyId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List listPoliciesforVolume(long volumeId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listSnapsforVolume(long volumeId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void deletePoliciesForVolume(Long volumeId) { + // TODO Auto-generated method stub + + } + + @Override + public boolean deleteSnapshotDirsForAccount(long accountId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SnapshotPolicyVO getPolicyForVolume(long volumeId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean destroySnapshotBackUp(long snapshotId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public SnapshotVO createSnapshotOnPrimary(VolumeVO volume, Long polocyId, + Long snapshotId) throws ResourceAllocationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listPoliciesforSnapshot(long snapshotId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listSnapsforPolicy(long policyId, Filter filter) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void downloadSnapshotsFromSwift(SnapshotVO ss) { + // TODO Auto-generated method stub + + } + + @Override + public HostVO getSecondaryStorageHost(SnapshotVO snapshot) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getSecondaryStorageURL(SnapshotVO snapshot) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void deleteSnapshotsForVolume(String secondaryStoragePoolUrl, + Long dcId, Long accountId, Long volumeId) { + // TODO Auto-generated method stub + + } + + @Override + public void deleteSnapshotsDirForVolume(String secondaryStoragePoolUrl, + Long dcId, Long accountId, Long volumeId) { + // TODO Auto-generated method stub + + } + + @Override + public boolean canOperateOnVolume(VolumeVO volume) { + // TODO Auto-generated method stub + return false; + } +} diff --git a/server/test/com/cloud/template/MockTemplateManagerImpl.java b/server/test/com/cloud/template/MockTemplateManagerImpl.java new file mode 100755 index 00000000000..19cd8d1430f --- /dev/null +++ b/server/test/com/cloud/template/MockTemplateManagerImpl.java @@ -0,0 +1,211 @@ +// 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.template; + +import java.net.URISyntaxException; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.api.commands.CopyTemplateCmd; +import com.cloud.api.commands.DeleteIsoCmd; +import com.cloud.api.commands.DeleteTemplateCmd; +import com.cloud.api.commands.ExtractIsoCmd; +import com.cloud.api.commands.ExtractTemplateCmd; +import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; +import com.cloud.api.commands.RegisterIsoCmd; +import com.cloud.api.commands.RegisterTemplateCmd; +import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd; +import com.cloud.dc.DataCenterVO; +import com.cloud.exception.InternalErrorException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.StorageUnavailableException; +import com.cloud.host.HostVO; +import com.cloud.storage.StoragePool; +import com.cloud.storage.StoragePoolVO; +import com.cloud.storage.VMTemplateHostVO; +import com.cloud.storage.VMTemplateStoragePoolVO; +import com.cloud.storage.VMTemplateVO; +import com.cloud.utils.component.Manager; + + +@Local(value={TemplateManager.class, TemplateService.class}) +public class MockTemplateManagerImpl implements TemplateManager, Manager, TemplateService { + + @Override + public VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) + throws URISyntaxException, ResourceAllocationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) + throws IllegalArgumentException, ResourceAllocationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) + throws StorageUnavailableException, ResourceAllocationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachineTemplate prepareTemplate(long templateId, long zoneId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean detachIso(long vmId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean attachIso(long isoId, long vmId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deleteTemplate(DeleteTemplateCmd cmd) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deleteIso(DeleteIsoCmd cmd) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Long extract(ExtractIsoCmd cmd) throws InternalErrorException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long extract(ExtractTemplateCmd cmd) throws InternalErrorException { + // TODO Auto-generated method stub + return null; + } + + @Override + public VirtualMachineTemplate getTemplate(long templateId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listTemplatePermissions( + ListTemplateOrIsoPermissionsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean updateTemplateOrIsoPermissions( + UpdateTemplateOrIsoPermissionsCmd cmd) { + // 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 VMTemplateStoragePoolVO prepareTemplateForCreate( + VMTemplateVO template, StoragePool pool) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean resetTemplateDownloadStateOnPool( + long templateStoragePoolRefId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean copy(long userId, VMTemplateVO template, HostVO srcSecHost, + DataCenterVO srcZone, DataCenterVO dstZone) + throws StorageUnavailableException, ResourceAllocationException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean delete(long userId, long templateId, Long zoneId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List getUnusedTemplatesInPool( + StoragePoolVO pool) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void evictTemplateFromStoragePool( + VMTemplateStoragePoolVO templatePoolVO) { + // TODO Auto-generated method stub + + } + + @Override + public boolean templateIsDeleteable(VMTemplateHostVO templateHostRef) { + // TODO Auto-generated method stub + return false; + } + + @Override + public VMTemplateHostVO prepareISOForCreate(VMTemplateVO template, + StoragePool pool) { + // TODO Auto-generated method stub + return null; + } +} From f365426b99b5e395b6ffe3fc19b81ec5a63afa43 Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Thu, 8 Nov 2012 23:37:30 +0530 Subject: [PATCH 09/24] temp changes --- server/src/com/cloud/region/RegionManagerImpl.java | 5 +++-- server/src/com/cloud/user/AccountManagerImpl.java | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index 0311780125e..3797ea1d292 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -289,6 +289,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ @Override public boolean removeRegion(int id) { + //Remove complete row, instead of soft delete RegionVO region = _regionDao.findById(id); if(region != null){ return _regionDao.remove(id); @@ -469,10 +470,10 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ //First delete in the Region where account is created Region region = _regionDao.findById(regionId); if (RegionsApiUtil.makeAPICall(region, command, params)) { - s_logger.debug("Successfully deleted user :"+userUUID+" in Region: "+region.getId()); + s_logger.debug("Successfully deleted user :"+userUUID+" in source Region: "+region.getId()); return true; } else { - s_logger.error("Error while deleting user :"+userUUID+" in Region: "+region.getId()); + s_logger.error("Error while deleting user :"+userUUID+" in source Region: "+region.getId()); return false; } } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 7d36d5432f9..b72a8ac03cc 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -1937,6 +1937,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @DB public String[] createApiKeyAndSecretKey(RegisterCmd cmd) { + //Send keys to other Regions Long userId = cmd.getId(); if (getUserIncludingRemoved(userId) == null) { @@ -2381,6 +2382,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public User findUser(String username, Long domainId) { UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId); + if(userAccount == null){ + throw new InvalidParameterValueException("Unable to find user account by name: "+username); + } User user = _userDao.findById(userAccount.getId()); if(user == null){ throw new InvalidParameterValueException("Unable to find user by name: "+username); From de20cb6c1a2e80a417c5fb7c66ab51ed6fe84faf Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Fri, 25 Jan 2013 18:45:01 +0530 Subject: [PATCH 10/24] Apply API refactoring changes. Make changes to Regions API to work with new code --- api/src/com/cloud/region/RegionService.java | 11 +- api/src/com/cloud/user/DomainService.java | 2 + .../cloudstack/api/ResponseGenerator.java | 13 +- .../admin/account}/FindAccountCmd.java | 19 +- .../command/admin/domain}/FindDomainCmd.java | 19 +- .../command/admin/region}/AddRegionCmd.java | 19 +- .../admin/region}/RemoveRegionCmd.java | 19 +- .../admin/region}/UpdateRegionCmd.java | 19 +- .../api/command/admin/user}/FindUserCmd.java | 19 +- .../command/user/region}/ListRegionsCmd.java | 16 +- .../api/response/FindAccountResponse.java | 57 +- .../api/response/FindDomainResponse.java | 74 +- .../api/response/FindUserResponse.java | 28 +- .../api/response/RegionResponse.java | 6 +- .../src/com/cloud/api/ApiResponseHelper.java | 119 +- server/src/com/cloud/api/ApiServer.java | 4 +- server/src/com/cloud/api/MockApiServer.java | 1101 +++++++++-------- .../src/com/cloud/region/RegionManager.java | 4 +- .../com/cloud/region/RegionManagerImpl.java | 12 +- 19 files changed, 749 insertions(+), 812 deletions(-) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/admin/account}/FindAccountCmd.java (79%) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/admin/domain}/FindDomainCmd.java (81%) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/admin/region}/AddRegionCmd.java (84%) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/admin/region}/RemoveRegionCmd.java (78%) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/admin/region}/UpdateRegionCmd.java (84%) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/admin/user}/FindUserCmd.java (80%) rename api/src/{com/cloud/api/commands => org/apache/cloudstack/api/command/user/region}/ListRegionsCmd.java (86%) rename api/src/{com/cloud => org/apache/cloudstack}/api/response/FindAccountResponse.java (78%) rename api/src/{com/cloud => org/apache/cloudstack}/api/response/FindDomainResponse.java (75%) rename api/src/{com/cloud => org/apache/cloudstack}/api/response/FindUserResponse.java (89%) rename api/src/{com/cloud => org/apache/cloudstack}/api/response/RegionResponse.java (92%) diff --git a/api/src/com/cloud/region/RegionService.java b/api/src/com/cloud/region/RegionService.java index a10bcfac3d8..ef4b5cb1a13 100644 --- a/api/src/com/cloud/region/RegionService.java +++ b/api/src/com/cloud/region/RegionService.java @@ -18,11 +18,12 @@ package com.cloud.region; import java.util.List; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListRegionsCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateDomainCmd; -import com.cloud.api.commands.UpdateUserCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.api.command.user.region.ListRegionsCmd; + import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 1d207e7d0f8..9fca09de1e6 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -20,6 +20,8 @@ import java.util.List; import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; + import com.cloud.domain.Domain; import com.cloud.exception.PermissionDeniedException; import com.cloud.utils.Pair; diff --git a/api/src/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java index d0be69c90a2..e380642a937 100644 --- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -39,6 +39,9 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.FindAccountResponse; +import org.apache.cloudstack.api.response.FindDomainResponse; +import org.apache.cloudstack.api.response.FindUserResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.GuestOSResponse; @@ -60,10 +63,12 @@ import org.apache.cloudstack.api.response.ProjectAccountResponse; import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.RegionResponse; import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; import org.apache.cloudstack.api.response.ResourceCountResponse; import org.apache.cloudstack.api.response.ResourceLimitResponse; import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.S3Response; import org.apache.cloudstack.api.response.SecurityGroupResponse; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.ServiceResponse; @@ -92,12 +97,6 @@ import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.cloudstack.api.response.S3Response; - -import com.cloud.api.response.FindAccountResponse; -import com.cloud.api.response.FindDomainResponse; -import com.cloud.api.response.FindUserResponse; -import com.cloud.api.response.RegionResponse; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.configuration.Configuration; @@ -105,7 +104,6 @@ import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; -import com.cloud.region.Region; import com.cloud.dc.StorageNetworkIpRange; import com.cloud.dc.Vlan; import com.cloud.domain.Domain; @@ -148,6 +146,7 @@ import com.cloud.org.Cluster; import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; +import com.cloud.region.Region; import com.cloud.server.ResourceTag; import com.cloud.storage.GuestOS; import com.cloud.storage.S3; diff --git a/api/src/com/cloud/api/commands/FindAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/FindAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java index 3c8610a71d9..9cfe548d5ff 100644 --- a/api/src/com/cloud/api/commands/FindAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FindAccountResponse; 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) +@APICommand(name = "findAccount", description="Find account by ID", responseObject=FindAccountResponse.class) public class FindAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(FindAccountCmd.class.getName()); @@ -37,8 +37,7 @@ public class FindAccountCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required=true, description = "Id of the account") + @Parameter(name = ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, required=true, description = "Id of the account") private Long id; ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/FindDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/FindDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java index cb299d12399..ff9bdc1005d 100644 --- a/api/src/com/cloud/api/commands/FindDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.FindDomainResponse; 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) +@APICommand(name = "findDomain", description="Find account by ID", responseObject=FindDomainResponse.class) public class FindDomainCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(FindDomainCmd.class.getName()); @@ -37,8 +37,7 @@ public class FindDomainCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "Id of the domain") + @Parameter(name = ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, description = "Id of the domain") private Long id; @Parameter(name = ApiConstants.DOMAIN, type = CommandType.STRING, description = "Path of the domain") diff --git a/api/src/com/cloud/api/commands/AddRegionCmd.java b/api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/AddRegionCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java index f2fd91f0221..73453a68fab 100644 --- a/api/src/com/cloud/api/commands/AddRegionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.region; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.RegionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.RegionResponse; import com.cloud.region.Region; import com.cloud.user.Account; -@Implementation(description="Adds a Region", responseObject=RegionResponse.class) +@APICommand(name = "addRegion", description="Adds a Region", responseObject=RegionResponse.class) public class AddRegionCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddRegionCmd.class.getName()); @@ -97,7 +98,7 @@ public class AddRegionCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Region"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Region"); } } } diff --git a/api/src/com/cloud/api/commands/RemoveRegionCmd.java b/api/src/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/RemoveRegionCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java index a42ce4b36e9..bb74c17fbbd 100644 --- a/api/src/com/cloud/api/commands/RemoveRegionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java @@ -14,19 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.region; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Removes specified region", responseObject=SuccessResponse.class) +@APICommand(name = "removeRegion", description="Removes specified region", responseObject=SuccessResponse.class) public class RemoveRegionCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RemoveRegionCmd.class.getName()); private static final String s_name = "updateregionresponse"; @@ -67,7 +68,7 @@ public class RemoveRegionCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove region"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to remove region"); } } } diff --git a/api/src/com/cloud/api/commands/UpdateRegionCmd.java b/api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/UpdateRegionCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java index f1f1dbad50d..626fb337aba 100644 --- a/api/src/com/cloud/api/commands/UpdateRegionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.region; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.RegionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.RegionResponse; import com.cloud.region.Region; import com.cloud.user.Account; -@Implementation(description="Updates a region", responseObject=RegionResponse.class) +@APICommand(name = "updateRegion", 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"; @@ -96,7 +97,7 @@ public class UpdateRegionCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update Region"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update Region"); } } } diff --git a/api/src/com/cloud/api/commands/FindUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/FindUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java index cd46ffd7f6d..ffd548765cb 100644 --- a/api/src/com/cloud/api/commands/FindUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.FindUserResponse; 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) +@APICommand(name = "findUser", 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()); @@ -40,8 +40,7 @@ public class FindUserCmd extends BaseCmd { @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") + @Parameter(name = ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, required=true, description = "Domain the user belongs to") private Long domainId; ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListRegionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/ListRegionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java index 53b7a6e307e..beddc3f4f33 100644 --- a/api/src/com/cloud/api/commands/ListRegionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.region; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.RegionResponse; import org.apache.log4j.Logger; -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.ListResponse; -import com.cloud.api.response.RegionResponse; import com.cloud.region.Region; -@Implementation(description="Lists Regions", responseObject=RegionResponse.class) +@APICommand(name = "listRegions", description="Lists Regions", responseObject=RegionResponse.class) public class ListRegionsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListRegionsCmd.class.getName()); diff --git a/api/src/com/cloud/api/response/FindAccountResponse.java b/api/src/org/apache/cloudstack/api/response/FindAccountResponse.java similarity index 78% rename from api/src/com/cloud/api/response/FindAccountResponse.java rename to api/src/org/apache/cloudstack/api/response/FindAccountResponse.java index bf79abdaf2c..6cff618057c 100755 --- a/api/src/com/cloud/api/response/FindAccountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FindAccountResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import java.util.List; import java.util.Map; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; +import com.cloud.user.Account; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value = Account.class) public class FindAccountResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the account") - private IdentityProxy id = new IdentityProxy("account"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the account") private String name; @@ -36,10 +39,10 @@ public class FindAccountResponse extends BaseResponse { private Short accountType; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="id of the Domain the account belongs too") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DEFAULT_ZONE_ID) @Param(description="the default zone of the account") - private IdentityProxy defaultZoneId = new IdentityProxy("data_center"); + private String defaultZoneId; @SerializedName(ApiConstants.STATE) @Param(description="the state of the account") private String state; @@ -53,10 +56,6 @@ public class FindAccountResponse extends BaseResponse { @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; } @@ -65,10 +64,6 @@ public class FindAccountResponse extends BaseResponse { this.accountType = accountType; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } - public void setState(String state) { this.state = state; } @@ -81,15 +76,31 @@ public class FindAccountResponse extends BaseResponse { 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; } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDomainId() { + return domainId; + } + + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public String getDefaultZoneId() { + return defaultZoneId; + } + + public void setDefaultZoneId(String defaultZoneId) { + this.defaultZoneId = defaultZoneId; + } } diff --git a/api/src/com/cloud/api/response/FindDomainResponse.java b/api/src/org/apache/cloudstack/api/response/FindDomainResponse.java similarity index 75% rename from api/src/com/cloud/api/response/FindDomainResponse.java rename to api/src/org/apache/cloudstack/api/response/FindDomainResponse.java index befb6329052..055e4a2b78c 100644 --- a/api/src/com/cloud/api/response/FindDomainResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FindDomainResponse.java @@ -14,16 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.domain.Domain; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@EntityReference(value = Domain.class) public class FindDomainResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the domain") - private IdentityProxy id = new IdentityProxy("domain"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the domain") private String domainName; @@ -32,7 +36,7 @@ public class FindDomainResponse extends BaseResponse { private Integer level; @SerializedName("parentdomainid") @Param(description="the domain ID of the parent domain") - private IdentityProxy parent = new IdentityProxy("domain"); + private String parent; @SerializedName("haschild") @Param(description="whether the domain has one or more sub-domains") private boolean hasChild; @@ -49,42 +53,14 @@ public class FindDomainResponse extends BaseResponse { @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; } @@ -93,19 +69,35 @@ public class FindDomainResponse extends BaseResponse { 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; } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } } diff --git a/api/src/com/cloud/api/response/FindUserResponse.java b/api/src/org/apache/cloudstack/api/response/FindUserResponse.java similarity index 89% rename from api/src/com/cloud/api/response/FindUserResponse.java rename to api/src/org/apache/cloudstack/api/response/FindUserResponse.java index 3532f2c472c..c60caabd596 100644 --- a/api/src/com/cloud/api/response/FindUserResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FindUserResponse.java @@ -14,17 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; +import com.cloud.user.User; import com.google.gson.annotations.SerializedName; +@EntityReference(value = User.class) public class FindUserResponse extends BaseResponse { @SerializedName("id") @Param(description="the user ID") - private IdentityProxy id = new IdentityProxy("user"); + private String id ; @SerializedName("username") @Param(description="the user name") private String username; @@ -39,7 +43,7 @@ public class FindUserResponse extends BaseResponse { private String lastname; @SerializedName("accountId") @Param(description="the account ID of the user") - private IdentityProxy accountId = new IdentityProxy("account"); + private String accountId; @SerializedName("email") @Param(description="the user email address") private String email; @@ -68,12 +72,12 @@ public class FindUserResponse extends BaseResponse { @SerializedName("regionId") @Param(description="source region id of the user") private int regionId; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getUsername() { @@ -147,12 +151,12 @@ public class FindUserResponse extends BaseResponse { public void setSecretKey(String secretKey) { this.secretKey = secretKey; } - public Long getAccountId() { - return accountId.getValue(); + public String getAccountId() { + return accountId; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; } public String getPassword() { diff --git a/api/src/com/cloud/api/response/RegionResponse.java b/api/src/org/apache/cloudstack/api/response/RegionResponse.java similarity index 92% rename from api/src/com/cloud/api/response/RegionResponse.java rename to api/src/org/apache/cloudstack/api/response/RegionResponse.java index 92f97c728da..cbd14b6fb5a 100644 --- a/api/src/com/cloud/api/response/RegionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RegionResponse.java @@ -14,9 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; -import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index cae27bdb686..3706d4fc9a7 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -60,80 +60,6 @@ import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.api.query.vo.VolumeJoinVO; import com.cloud.api.response.ApiResponseSerializer; -<<<<<<< HEAD -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.CapabilityResponse; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.ControlledEntityResponse; -import com.cloud.api.response.CreateCmdResponse; -import com.cloud.api.response.DiskOfferingResponse; -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; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.LBStickinessPolicyResponse; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.NetworkACLResponse; -import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.api.response.NetworkResponse; -import com.cloud.api.response.NicResponse; -import com.cloud.api.response.PhysicalNetworkResponse; -import com.cloud.api.response.PodResponse; -import com.cloud.api.response.PrivateGatewayResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.RegionResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; -import com.cloud.api.response.ResourceCountResponse; -import com.cloud.api.response.ResourceLimitResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SecurityGroupResultObject; -import com.cloud.api.response.SecurityGroupRuleResponse; -import com.cloud.api.response.SecurityGroupRuleResultObject; -import com.cloud.api.response.ServiceOfferingResponse; -import com.cloud.api.response.ServiceResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; -import com.cloud.api.response.SnapshotPolicyResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StaticRouteResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.SwiftResponse; -import com.cloud.api.response.SystemVmInstanceResponse; -import com.cloud.api.response.SystemVmResponse; -import com.cloud.api.response.TemplatePermissionsResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.TrafficTypeResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; -import com.cloud.api.response.VlanIpRangeResponse; -import com.cloud.api.response.VolumeResponse; -import com.cloud.api.response.VpcOfferingResponse; -import com.cloud.api.response.VpcResponse; -import com.cloud.api.response.VpnUsersResponse; -import com.cloud.api.response.ZoneResponse; -======= import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; @@ -151,6 +77,9 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.FindAccountResponse; +import org.apache.cloudstack.api.response.FindDomainResponse; +import org.apache.cloudstack.api.response.FindUserResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.GuestOSResponse; @@ -174,6 +103,7 @@ import org.apache.cloudstack.api.response.ProjectAccountResponse; import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.RegionResponse; import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; import org.apache.cloudstack.api.response.ResourceCountResponse; import org.apache.cloudstack.api.response.ResourceLimitResponse; @@ -208,7 +138,6 @@ import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.api.response.S3Response; ->>>>>>> master import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; @@ -2828,12 +2757,6 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("storagenetworkiprange"); return response; } -<<<<<<< HEAD - - @Override - public Long getIdentiyId(String tableName, String token) { - return ApiDispatcher.getIdentiyId(tableName, token); - } @Override public RegionResponse createRegionResponse(Region region) { @@ -2844,8 +2767,6 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("region"); return response; } -======= ->>>>>>> master @Override public ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag, boolean keyValueOnly) { @@ -3225,17 +3146,19 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("vpnconnection"); return response; } -<<<<<<< HEAD @Override public FindUserResponse createFindUserResponse(User user) { FindUserResponse userResponse = new FindUserResponse(); - userResponse.setId(user.getId()); + userResponse.setId(user.getUuid()); userResponse.setUsername(user.getUsername()); userResponse.setPassword(user.getPassword()); userResponse.setFirstname(user.getFirstname()); userResponse.setLastname(user.getLastname()); - userResponse.setAccountId(user.getAccountId()); + Account account = ApiDBUtils.findAccountById(user.getAccountId()); + if(account != null){ + userResponse.setAccountId(account.getUuid()); + } userResponse.setEmail(user.getEmail()); userResponse.setState(user.getState().toString()); userResponse.setApiKey(user.getApiKey()); @@ -3253,11 +3176,17 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public FindAccountResponse createFindAccountResponse(Account account) { FindAccountResponse accountResponse = new FindAccountResponse(); - accountResponse.setId(account.getId()); + accountResponse.setId(account.getUuid()); accountResponse.setName(account.getAccountName()); accountResponse.setAccountType(account.getType()); - accountResponse.setDefaultZone(account.getDefaultZoneId()); - accountResponse.setDomainId(account.getDomainId()); + DataCenterVO zone = ApiDBUtils.findZoneById(account.getDefaultZoneId()); + if(zone != null){ + accountResponse.setDefaultZoneId(zone.getUuid()); + } + Domain domain = ApiDBUtils.findDomainById(account.getDomainId()); + if(domain != null){ + accountResponse.setDomainId(domain.getUuid()); + } accountResponse.setRegionId(account.getRegionId()); accountResponse.setState(account.getState().toString()); accountResponse.setObjectName("account"); @@ -3268,18 +3197,18 @@ public class ApiResponseHelper implements ResponseGenerator { public FindDomainResponse createFindDomainResponse(Domain domain) { FindDomainResponse domainResponse = new FindDomainResponse(); domainResponse.setDomainName(domain.getName()); - domainResponse.setId(domain.getId()); + domainResponse.setId(domain.getUuid()); domainResponse.setLevel(domain.getLevel()); domainResponse.setNetworkDomain(domain.getNetworkDomain()); - domainResponse.setParent(domain.getParent()); + Domain parentDomain = ApiDBUtils.findDomainById(domain.getParent()); + if (parentDomain != null) { + domainResponse.setParent(parentDomain.getUuid()); + } domainResponse.setPath(domain.getPath()); domainResponse.setObjectName("domain"); domainResponse.setRegionId(domain.getRegionId()); return domainResponse; } -======= - - @Override public GuestOSResponse createGuestOSResponse(GuestOS guestOS) { @@ -3319,6 +3248,4 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - ->>>>>>> master } diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 93089a1541e..07b89c3b808 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -162,7 +162,7 @@ public class ApiServer implements HttpRequestHandler { private Account _systemAccount = null; private User _systemUser = null; - private RegionManager _regionMgr = null; + @Inject private RegionManager _regionMgr = null; private static int _workerCount = 0; private static ApiServer s_instance = null; @@ -197,8 +197,6 @@ public class ApiServer implements HttpRequestHandler { _systemAccount = _accountMgr.getSystemAccount(); _systemUser = _accountMgr.getSystemUser(); _dispatcher = ApiDispatcher.getInstance(); - _domainMgr = ComponentLocator.inject(DomainManager.class); - _regionMgr = ComponentLocator.inject(RegionManager.class); Integer apiPort = null; // api port, null by default ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); diff --git a/server/src/com/cloud/api/MockApiServer.java b/server/src/com/cloud/api/MockApiServer.java index 23b78a4c808..52d6b57cdee 100755 --- a/server/src/com/cloud/api/MockApiServer.java +++ b/server/src/com/cloud/api/MockApiServer.java @@ -40,6 +40,12 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ExceptionResponse; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; @@ -68,571 +74,566 @@ 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; - } - +public abstract 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(ApiErrorCode.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(ApiErrorCode.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(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString); +// } +// } +// } +// } catch (Exception ex) { +// if (ex instanceof InvalidParameterValueException) { +// InvalidParameterValueException ref = (InvalidParameterValueException)ex; +// ServerApiException e = new ServerApiException(ApiErrorCode.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(ApiErrorCode.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(ApiErrorCode.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 == ApiErrorCode.UNSUPPORTED_ACTION_ERROR.ordinal() || 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/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java index 20e24bacec0..453a9779411 100644 --- a/server/src/com/cloud/region/RegionManager.java +++ b/server/src/com/cloud/region/RegionManager.java @@ -18,7 +18,7 @@ package com.cloud.region; import java.util.Map; -import com.cloud.domain.DomainVO; +import com.cloud.domain.Domain; import com.cloud.user.UserAccount; @@ -32,5 +32,5 @@ public interface RegionManager { 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); + Domain findDomainByPath(String domainPath); } diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index 3797ea1d292..193c16ab2a2 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -23,15 +23,15 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.api.command.user.region.ListRegionsCmd; import org.apache.commons.httpclient.NameValuePair; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListRegionsCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateDomainCmd; -import com.cloud.api.commands.UpdateUserCmd; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; From cd9e4e999e4d2aa29297cd3d483529bbb8bf746f Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Fri, 25 Jan 2013 19:32:13 +0530 Subject: [PATCH 11/24] added missing bracket --- ui/scripts/system.js | 1 + 1 file changed, 1 insertion(+) diff --git a/ui/scripts/system.js b/ui/scripts/system.js index 761900be218..def6d443026 100644 --- a/ui/scripts/system.js +++ b/ui/scripts/system.js @@ -1328,6 +1328,7 @@ if(serviceObjArray == "DefaultSharedNetworkOfferingWithSGService"){ continue; } + } //comment out the following 12 lines because of CS-16718 /* From def9fd1f2e42892ff7cd8c7da4d2af17ab819a9c Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Mon, 28 Jan 2013 17:04:25 +0530 Subject: [PATCH 12/24] remove finduser, findaccount, finddomain APIs --- api/src/com/cloud/region/Region.java | 4 - api/src/com/cloud/user/AccountService.java | 3 - .../cloudstack/api/ResponseGenerator.java | 8 - .../command/admin/account/FindAccountCmd.java | 76 ----- .../command/admin/domain/FindDomainCmd.java | 89 ------ .../api/command/admin/user/FindUserCmd.java | 83 ------ .../api/response/FindAccountResponse.java | 106 ------- .../api/response/FindDomainResponse.java | 103 ------- .../api/response/FindUserResponse.java | 193 ------------ .../server/auth/MD5UserAuthenticator.java | 8 +- .../src/com/cloud/api/ApiResponseHelper.java | 66 ----- server/src/com/cloud/api/ApiServer.java | 2 +- .../src/com/cloud/region/RegionManager.java | 6 - .../com/cloud/region/RegionManagerImpl.java | 277 +++++------------- server/src/com/cloud/region/RegionVO.java | 10 - .../com/cloud/user/AccountManagerImpl.java | 18 -- .../cloud/user/MockAccountManagerImpl.java | 14 - setup/db/create-schema.sql | 1 - 18 files changed, 71 insertions(+), 996 deletions(-) delete mode 100644 api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java delete mode 100644 api/src/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java delete mode 100644 api/src/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java delete mode 100755 api/src/org/apache/cloudstack/api/response/FindAccountResponse.java delete mode 100644 api/src/org/apache/cloudstack/api/response/FindDomainResponse.java delete mode 100644 api/src/org/apache/cloudstack/api/response/FindUserResponse.java diff --git a/api/src/com/cloud/region/Region.java b/api/src/com/cloud/region/Region.java index 3096af59317..96d7dff5e10 100644 --- a/api/src/com/cloud/region/Region.java +++ b/api/src/com/cloud/region/Region.java @@ -16,8 +16,6 @@ // under the License. package com.cloud.region; -import java.util.Date; - /** * */ @@ -29,8 +27,6 @@ public interface Region { public void setName(String name); - public Date getRemoved(); - public String getEndPoint(); public String getApiKey(); diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 288d845f1ed..553c84ae100 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -200,7 +200,4 @@ 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/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java index e380642a937..d6780fd66a0 100644 --- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -39,9 +39,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.ExtractResponse; -import org.apache.cloudstack.api.response.FindAccountResponse; -import org.apache.cloudstack.api.response.FindDomainResponse; -import org.apache.cloudstack.api.response.FindUserResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.GuestOSResponse; @@ -365,11 +362,6 @@ public interface ResponseGenerator { Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result); - FindUserResponse createFindUserResponse(User user); - - FindAccountResponse createFindAccountResponse(Account account); - - FindDomainResponse createFindDomainResponse(Domain domain); CounterResponse createCounterResponse(Counter ctr); ConditionResponse createConditionResponse(Condition cndn); diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java deleted file mode 100644 index 9cfe548d5ff..00000000000 --- a/api/src/org/apache/cloudstack/api/command/admin/account/FindAccountCmd.java +++ /dev/null @@ -1,76 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.api.command.admin.account; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.AccountResponse; -import org.apache.cloudstack.api.response.FindAccountResponse; -import org.apache.log4j.Logger; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.user.Account; - -@APICommand(name = "findAccount", 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 ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, 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/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java deleted file mode 100644 index ff9bdc1005d..00000000000 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/FindDomainCmd.java +++ /dev/null @@ -1,89 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.api.command.admin.domain; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.cloudstack.api.response.FindDomainResponse; -import org.apache.log4j.Logger; - -import com.cloud.domain.Domain; -import com.cloud.exception.InvalidParameterValueException; - -@APICommand(name = "findDomain", 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 ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, 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/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java deleted file mode 100644 index ffd548765cb..00000000000 --- a/api/src/org/apache/cloudstack/api/command/admin/user/FindUserCmd.java +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.api.command.admin.user; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.cloudstack.api.response.FindUserResponse; -import org.apache.log4j.Logger; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.user.User; - -@APICommand(name = "findUser", 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; - - @Parameter(name = ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, 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/org/apache/cloudstack/api/response/FindAccountResponse.java b/api/src/org/apache/cloudstack/api/response/FindAccountResponse.java deleted file mode 100755 index 6cff618057c..00000000000 --- a/api/src/org/apache/cloudstack/api/response/FindAccountResponse.java +++ /dev/null @@ -1,106 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.api.response; - -import java.util.Map; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.serializer.Param; -import com.cloud.user.Account; -import com.google.gson.annotations.SerializedName; - -@SuppressWarnings("unused") -@EntityReference(value = Account.class) -public class FindAccountResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) @Param(description="the id of the account") - private String id; - - @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 String domainId; - - @SerializedName(ApiConstants.DEFAULT_ZONE_ID) @Param(description="the default zone of the account") - private String defaultZoneId; - - @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 setName(String name) { - this.name = name; - } - - public void setAccountType(Short accountType) { - this.accountType = accountType; - } - - 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 setRegionId(int regionId) { - this.regionId = regionId; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getDomainId() { - return domainId; - } - - public void setDomainId(String domainId) { - this.domainId = domainId; - } - - public String getDefaultZoneId() { - return defaultZoneId; - } - - public void setDefaultZoneId(String defaultZoneId) { - this.defaultZoneId = defaultZoneId; - } -} diff --git a/api/src/org/apache/cloudstack/api/response/FindDomainResponse.java b/api/src/org/apache/cloudstack/api/response/FindDomainResponse.java deleted file mode 100644 index 055e4a2b78c..00000000000 --- a/api/src/org/apache/cloudstack/api/response/FindDomainResponse.java +++ /dev/null @@ -1,103 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.api.response; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.domain.Domain; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; - -@EntityReference(value = Domain.class) -public class FindDomainResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) @Param(description="the ID of the domain") - private String id; - - @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 String parent; - - @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 void setDomainName(String domainName) { - this.domainName = domainName; - } - - public void setLevel(Integer level) { - this.level = level; - } - - public void setHasChild(boolean hasChild) { - this.hasChild = hasChild; - } - - public void setNetworkDomain(String networkDomain) { - this.networkDomain = networkDomain; - } - - public void setPath(String path) { - this.path = path; - } - - public void setRegionId(int regionId) { - this.regionId = regionId; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getParent() { - return parent; - } - - public void setParent(String parent) { - this.parent = parent; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } -} diff --git a/api/src/org/apache/cloudstack/api/response/FindUserResponse.java b/api/src/org/apache/cloudstack/api/response/FindUserResponse.java deleted file mode 100644 index c60caabd596..00000000000 --- a/api/src/org/apache/cloudstack/api/response/FindUserResponse.java +++ /dev/null @@ -1,193 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.api.response; - -import java.util.Date; - -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.serializer.Param; -import com.cloud.user.User; -import com.google.gson.annotations.SerializedName; - -@EntityReference(value = User.class) -public class FindUserResponse extends BaseResponse { - @SerializedName("id") @Param(description="the user ID") - private String id ; - - @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 String accountId; - - @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 String getId() { - return id; - } - - public void setId(String id) { - this.id = 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 String getAccountId() { - return accountId; - } - - public void setAccountId(String accountId) { - this.accountId = 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/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java index 4417a97590c..b0cf0b03cd6 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 @@ -25,9 +25,9 @@ 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.exception.CloudRuntimeException; @@ -40,14 +40,14 @@ import com.cloud.utils.exception.CloudRuntimeException; public class MD5UserAuthenticator extends DefaultUserAuthenticator { public static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class); - private RegionManager _regionMgr; + private UserAccountDao _userAccountDao; @Override public boolean authenticate(String username, String password, Long domainId, Map requestParameters ) { if (s_logger.isDebugEnabled()) { s_logger.debug("Retrieving user: " + username); } - UserAccount user = _regionMgr.getUserAccount(username, domainId); + UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { s_logger.debug("Unable to find user with " + username + " in domain " + domainId); return false; @@ -64,7 +64,7 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator { throws ConfigurationException { super.configure(name, params); ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - _regionMgr = locator.getManager(RegionManager.class); + _userAccountDao = locator.getDao(UserAccountDao.class); return true; } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index cef780d121b..86f0ea3a7c1 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -78,9 +78,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.ExtractResponse; -import org.apache.cloudstack.api.response.FindAccountResponse; -import org.apache.cloudstack.api.response.FindDomainResponse; -import org.apache.cloudstack.api.response.FindUserResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.GuestOSResponse; @@ -3113,69 +3110,6 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - @Override - public FindUserResponse createFindUserResponse(User user) { - FindUserResponse userResponse = new FindUserResponse(); - userResponse.setId(user.getUuid()); - userResponse.setUsername(user.getUsername()); - userResponse.setPassword(user.getPassword()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setLastname(user.getLastname()); - Account account = ApiDBUtils.findAccountById(user.getAccountId()); - if(account != null){ - userResponse.setAccountId(account.getUuid()); - } - 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.getUuid()); - accountResponse.setName(account.getAccountName()); - accountResponse.setAccountType(account.getType()); - DataCenterVO zone = ApiDBUtils.findZoneById(account.getDefaultZoneId()); - if(zone != null){ - accountResponse.setDefaultZoneId(zone.getUuid()); - } - Domain domain = ApiDBUtils.findDomainById(account.getDomainId()); - if(domain != null){ - accountResponse.setDomainId(domain.getUuid()); - } - 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.getUuid()); - domainResponse.setLevel(domain.getLevel()); - domainResponse.setNetworkDomain(domain.getNetworkDomain()); - Domain parentDomain = ApiDBUtils.findDomainById(domain.getParent()); - if (parentDomain != null) { - domainResponse.setParent(parentDomain.getUuid()); - } - domainResponse.setPath(domain.getPath()); - domainResponse.setObjectName("domain"); - domainResponse.setRegionId(domain.getRegionId()); - return domainResponse; - } - @Override public GuestOSResponse createGuestOSResponse(GuestOS guestOS) { GuestOSResponse response = new GuestOSResponse(); diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 0b160f1018e..d2d07125acb 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -754,7 +754,7 @@ public class ApiServer implements HttpRequestHandler { if (domainPath == null || domainPath.trim().length() == 0) { domainId = DomainVO.ROOT_DOMAIN; } else { - Domain domainObj = _regionMgr.findDomainByPath(domainPath); + Domain domainObj = _domainMgr.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/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java index 453a9779411..437e02d334d 100644 --- a/server/src/com/cloud/region/RegionManager.java +++ b/server/src/com/cloud/region/RegionManager.java @@ -18,10 +18,6 @@ package com.cloud.region; import java.util.Map; -import com.cloud.domain.Domain; -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); @@ -31,6 +27,4 @@ public interface RegionManager { 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); - Domain findDomainByPath(String domainPath); } diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index 193c16ab2a2..a2a79e444c7 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -99,6 +99,72 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ return _name; } + @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"); + } + } + + @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"); + } + + if(name != null){ + region.setName(name); + } + + if(endPoint != null){ + 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(int id) { + RegionVO region = _regionDao.findById(id); + if(region != null){ + return _regionDao.remove(id); + } else { + throw new InvalidParameterValueException("Failed to delete Region: " + id + ", Region not found"); + } + } + + @Override + public List listRegions(ListRegionsCmd cmd) { + if(cmd.getId() != null){ + List regions = new ArrayList(); + regions.add(_regionDao.findById(cmd.getId())); + return regions; + } + return _regionDao.listAll(); + } + + public int getId() { + return _id; + } + + public void setId(int _id) { + this._id = _id; + } + @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) { @@ -249,73 +315,6 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } - @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"); - } - } - - @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"); - } - - if(name != null){ - region.setName(name); - } - - if(endPoint != null){ - 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(int id) { - //Remove complete row, instead of soft delete - RegionVO region = _regionDao.findById(id); - if(region != null){ - return _regionDao.remove(id); - } else { - throw new InvalidParameterValueException("Failed to delete Region: " + id + ", Region not found"); - } - } - - public int getId() { - return _id; - } - - public void setId(int _id) { - this._id = _id; - } - - @Override - public List listRegions(ListRegionsCmd cmd) { - if(cmd.getId() != null){ - List regions = new ArrayList(); - regions.add(_regionDao.findById(cmd.getId())); - return regions; - } - return _regionDao.listAll(); - } - @Override public Account disableAccount(String accountName, Long domainId, Long accountId, Boolean lockRequested) throws ConcurrentOperationException, ResourceUnavailableException { Account account = null; @@ -774,149 +773,5 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } 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/RegionVO.java b/server/src/com/cloud/region/RegionVO.java index c54dea23154..a168f395aa6 100644 --- a/server/src/com/cloud/region/RegionVO.java +++ b/server/src/com/cloud/region/RegionVO.java @@ -16,14 +16,11 @@ // under the License. package com.cloud.region; -import java.util.Date; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.utils.db.GenericDao; @Entity @Table(name="region") @@ -45,9 +42,6 @@ public class RegionVO implements Region{ @Column(name="secret_key") private String secretKey; - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - public RegionVO() { } @@ -71,10 +65,6 @@ public class RegionVO implements Region{ this.name = name; } - public Date getRemoved() { - return removed; - } - public String getEndPoint() { return endPoint; } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index dcd6da30e72..c5c53e898dc 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -2240,24 +2240,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } - @Override - public User findUser(String username, Long domainId) { - UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId); - if(userAccount == null){ - throw new InvalidParameterValueException("Unable to find user account by name: "+username); - } - 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); - } - @Override public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { diff --git a/server/test/com/cloud/user/MockAccountManagerImpl.java b/server/test/com/cloud/user/MockAccountManagerImpl.java index 7e204916d71..2b22e7bc98a 100644 --- a/server/test/com/cloud/user/MockAccountManagerImpl.java +++ b/server/test/com/cloud/user/MockAccountManagerImpl.java @@ -28,11 +28,9 @@ import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.api.query.vo.ControlledViewEntity; import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; -import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; -import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; @@ -342,18 +340,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS 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, diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 62b95af7ec7..31f6d781557 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -2262,7 +2262,6 @@ CREATE TABLE `cloud`.`region` ( `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; From ea660cd06de9350f5fffaaeb53e49e8bc91c4c1e Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Mon, 28 Jan 2013 17:50:38 +0530 Subject: [PATCH 13/24] removed MockAPI server --- client/tomcatconf/components-regions.xml.in | 52 -- server/src/com/cloud/api/MockApiServer.java | 639 ---------------- server/test/com/cloud/api/RegionTest.java | 42 -- .../RegionsComponentLibrary.java | 230 ------ .../MockSecurityGroupManagerImpl.java | 198 ----- .../vpn/MockRemoteAccessVpnManagerImpl.java | 129 ---- .../server/MockManagementServerImpl.java | 483 ------------- .../cloud/storage/MockStorageManagerImpl.java | 679 ------------------ .../snapshot/MockSnapshotManagerImpl.java | 236 ------ .../template/MockTemplateManagerImpl.java | 211 ------ .../com/cloud/vm/MockUserVmManagerImpl.java | 4 +- 11 files changed, 1 insertion(+), 2902 deletions(-) delete mode 100755 client/tomcatconf/components-regions.xml.in delete mode 100755 server/src/com/cloud/api/MockApiServer.java delete mode 100644 server/test/com/cloud/api/RegionTest.java delete mode 100755 server/test/com/cloud/configuration/RegionsComponentLibrary.java delete mode 100755 server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java delete mode 100755 server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java delete mode 100755 server/test/com/cloud/server/MockManagementServerImpl.java delete mode 100755 server/test/com/cloud/storage/MockStorageManagerImpl.java delete mode 100755 server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java delete mode 100755 server/test/com/cloud/template/MockTemplateManagerImpl.java diff --git a/client/tomcatconf/components-regions.xml.in b/client/tomcatconf/components-regions.xml.in deleted file mode 100755 index 60a2d00d542..00000000000 --- a/client/tomcatconf/components-regions.xml.in +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - true - - - - - - diff --git a/server/src/com/cloud/api/MockApiServer.java b/server/src/com/cloud/api/MockApiServer.java deleted file mode 100755 index 52d6b57cdee..00000000000 --- a/server/src/com/cloud/api/MockApiServer.java +++ /dev/null @@ -1,639 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api; - -import java.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.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.ResponseObject; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ExceptionResponse; -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.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.server.ManagementService; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.User; -import com.cloud.user.UserContext; -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 abstract 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(ApiErrorCode.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(ApiErrorCode.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(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString); -// } -// } -// } -// } catch (Exception ex) { -// if (ex instanceof InvalidParameterValueException) { -// InvalidParameterValueException ref = (InvalidParameterValueException)ex; -// ServerApiException e = new ServerApiException(ApiErrorCode.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(ApiErrorCode.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(ApiErrorCode.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 == ApiErrorCode.UNSUPPORTED_ACTION_ERROR.ordinal() || 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/test/com/cloud/api/RegionTest.java b/server/test/com/cloud/api/RegionTest.java deleted file mode 100644 index 9ddade33f21..00000000000 --- a/server/test/com/cloud/api/RegionTest.java +++ /dev/null @@ -1,42 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api; - -import java.io.File; - -import org.apache.log4j.Logger; -import org.apache.log4j.xml.DOMConfigurator; - -import com.cloud.server.ManagementService; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.ComponentLocator; - -public class RegionTest { - private static final Logger s_logger = Logger.getLogger(RegionTest.class.getName()); - - public static void main(String args[]){ - System.out.println("Starting"); - File file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); - if (file != null) { - s_logger.info("log4j configuration found at " + file.getAbsolutePath()); - DOMConfigurator.configureAndWatch(file.getAbsolutePath()); - } - final ComponentLocator _locator = ComponentLocator.getLocator(ManagementService.Name, "components-regions.xml", "log4j-cloud"); - MockApiServer.initApiServer(new String[] { "commands.properties" }); - System.out.println("Started"); - } -} \ No newline at end of file diff --git a/server/test/com/cloud/configuration/RegionsComponentLibrary.java b/server/test/com/cloud/configuration/RegionsComponentLibrary.java deleted file mode 100755 index 75ac6b6ace0..00000000000 --- a/server/test/com/cloud/configuration/RegionsComponentLibrary.java +++ /dev/null @@ -1,230 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.configuration; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.cloud.alert.AlertManagerImpl; -import com.cloud.alert.dao.AlertDaoImpl; -import com.cloud.capacity.dao.CapacityDaoImpl; -import com.cloud.configuration.dao.ConfigurationDaoImpl; -import com.cloud.configuration.dao.ResourceCountDaoImpl; -import com.cloud.configuration.dao.ResourceLimitDaoImpl; -import com.cloud.dao.EntityManager; -import com.cloud.dao.EntityManagerImpl; -import com.cloud.dc.dao.AccountVlanMapDaoImpl; -import com.cloud.dc.dao.ClusterDaoImpl; -import com.cloud.dc.dao.DataCenterDaoImpl; -import com.cloud.dc.dao.HostPodDaoImpl; -import com.cloud.dc.dao.VlanDaoImpl; -import com.cloud.domain.dao.DomainDaoImpl; -import com.cloud.host.dao.HostDaoImpl; -import com.cloud.network.MockNetworkManagerImpl; -import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; -import com.cloud.network.dao.IPAddressDaoImpl; -import com.cloud.network.dao.LoadBalancerDaoImpl; -import com.cloud.network.dao.NetworkDaoImpl; -import com.cloud.network.dao.NetworkDomainDaoImpl; -import com.cloud.network.dao.NetworkRuleConfigDaoImpl; -import com.cloud.network.dao.RemoteAccessVpnDaoImpl; -import com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl; -import com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl; -import com.cloud.network.dao.VpnUserDaoImpl; -import com.cloud.network.security.MockSecurityGroupManagerImpl; -import com.cloud.network.security.dao.SecurityGroupDaoImpl; -import com.cloud.network.vpc.dao.VpcDaoImpl; -import com.cloud.network.vpn.MockRemoteAccessVpnManagerImpl; -import com.cloud.offerings.dao.NetworkOfferingDaoImpl; -import com.cloud.projects.MockProjectManagerImpl; -import com.cloud.projects.dao.ProjectAccountDaoImpl; -import com.cloud.projects.dao.ProjectDaoImpl; -import com.cloud.region.RegionManagerImpl; -import com.cloud.region.dao.RegionDaoImpl; -import com.cloud.resourcelimit.ResourceLimitManagerImpl; -import com.cloud.service.dao.ServiceOfferingDaoImpl; -import com.cloud.storage.MockStorageManagerImpl; -import com.cloud.storage.dao.DiskOfferingDaoImpl; -import com.cloud.storage.dao.GuestOSCategoryDaoImpl; -import com.cloud.storage.dao.GuestOSDaoImpl; -import com.cloud.storage.dao.LaunchPermissionDaoImpl; -import com.cloud.storage.dao.SnapshotDaoImpl; -import com.cloud.storage.dao.StoragePoolDaoImpl; -import com.cloud.storage.dao.UploadDaoImpl; -import com.cloud.storage.dao.VMTemplateDaoImpl; -import com.cloud.storage.dao.VMTemplateDetailsDaoImpl; -import com.cloud.storage.dao.VMTemplateHostDaoImpl; -import com.cloud.storage.dao.VMTemplateSwiftDaoImpl; -import com.cloud.storage.dao.VMTemplateZoneDaoImpl; -import com.cloud.storage.dao.VolumeDaoImpl; -import com.cloud.storage.dao.VolumeHostDaoImpl; -import com.cloud.storage.snapshot.MockSnapshotManagerImpl; -import com.cloud.template.MockTemplateManagerImpl; -import com.cloud.user.AccountDetailsDaoImpl; -import com.cloud.user.AccountManagerImpl; -import com.cloud.user.DomainManagerImpl; -import com.cloud.user.dao.AccountDaoImpl; -import com.cloud.user.dao.SSHKeyPairDaoImpl; -import com.cloud.user.dao.UserAccountDaoImpl; -import com.cloud.user.dao.UserDaoImpl; -import com.cloud.user.dao.UserStatisticsDaoImpl; -import com.cloud.utils.component.Adapter; -import com.cloud.utils.component.ComponentLibrary; -import com.cloud.utils.component.ComponentLibraryBase; -import com.cloud.utils.component.ComponentLocator.ComponentInfo; -import com.cloud.utils.component.Manager; -import com.cloud.utils.component.PluggableService; -import com.cloud.utils.db.GenericDao; -import com.cloud.uuididentity.dao.IdentityDaoImpl; -import com.cloud.vm.MockUserVmManagerImpl; -import com.cloud.vm.MockVirtualMachineManagerImpl; -import com.cloud.vm.dao.ConsoleProxyDaoImpl; -import com.cloud.vm.dao.DomainRouterDaoImpl; -import com.cloud.vm.dao.InstanceGroupDaoImpl; -import com.cloud.vm.dao.UserVmDaoImpl; -import com.cloud.vm.dao.UserVmDetailsDaoImpl; -import com.cloud.vm.dao.VMInstanceDaoImpl; -import com.cloud.vpc.MockConfigurationManagerImpl; -import com.cloud.vpc.MockResourceLimitManagerImpl; -import com.cloud.vpc.MockSite2SiteVpnManagerImpl; -import com.cloud.vpc.MockVpcManagerImpl; - - -public class RegionsComponentLibrary extends ComponentLibraryBase implements ComponentLibrary { - protected void populateDaos() { - addDao("DomainDao", DomainDaoImpl.class); - addDao("AccountDao", AccountDaoImpl.class); - addDao("UserDao", UserDaoImpl.class); - addDao("UserAccountDao", UserAccountDaoImpl.class); - addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); - addDao("RegionDao", RegionDaoImpl.class); - addDao("IdentityDao", IdentityDaoImpl.class); - addDao("AccountVlanMapDao", AccountVlanMapDaoImpl.class); - addDao("CapacityDao", CapacityDaoImpl.class); - addDao("ClusterDao", ClusterDaoImpl.class); - addDao("ServiceOfferingDao", ServiceOfferingDaoImpl.class); - addDao("DiskOfferingDao", DiskOfferingDaoImpl.class); - addDao("DomainRouterDao", DomainRouterDaoImpl.class); - addDao("GuestOSDao", GuestOSDaoImpl.class); - addDao("GuestOSCategoryDao", GuestOSCategoryDaoImpl.class); - addDao("HostDao", HostDaoImpl.class); - addDao("IPAddressDao", IPAddressDaoImpl.class); - addDao("LoadBalancerDao", LoadBalancerDaoImpl.class); - addDao("NetworkRuleConfigDao", NetworkRuleConfigDaoImpl.class); - addDao("HostPodDao", HostPodDaoImpl.class); - addDao("SnapshotDao", SnapshotDaoImpl.class); - addDao("StoragePoolDao", StoragePoolDaoImpl.class); - addDao("ConfigurationDao", ConfigurationDaoImpl.class); - addDao("DataCenterDao", DataCenterDaoImpl.class); - addDao("VMTemplateZoneDao", VMTemplateZoneDaoImpl.class); - addDao("VMTemplateDetailsDao", VMTemplateDetailsDaoImpl.class); - addDao("VMTemplateDao", VMTemplateDaoImpl.class); - addDao("VMTemplateHostDao", VMTemplateHostDaoImpl.class); - addDao("VMTemplateSwiftDao", VMTemplateSwiftDaoImpl.class); - addDao("UploadDao", UploadDaoImpl.class); - addDao("UserDao", UserDaoImpl.class); - addDao("UserStatisticsDao", UserStatisticsDaoImpl.class); - addDao("UserVmDao", UserVmDaoImpl.class); - addDao("VlanDao", VlanDaoImpl.class); - addDao("VolumeDao", VolumeDaoImpl.class); - addDao("Site2SiteVpnGatewayDao", Site2SiteVpnGatewayDaoImpl.class); - addDao("Site2SiteCustomerGatewayDao", Site2SiteCustomerGatewayDaoImpl.class); - addDao("VolumeHostDao", VolumeHostDaoImpl.class); - addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); - addDao("NetworkConfigurationDao", NetworkDaoImpl.class); - addDao("ConsoleProxyDao", ConsoleProxyDaoImpl.class); - addDao("FirewallRulesCidrsDao", FirewallRulesCidrsDaoImpl.class); - addDao("VMInstanceDao", VMInstanceDaoImpl.class); - addDao("AccountDetailsDao", AccountDetailsDaoImpl.class); - addDao("NetworkDomainDao", NetworkDomainDaoImpl.class); - addDao("SSHKeyPairDao", SSHKeyPairDaoImpl.class); - addDao("UserVmDetailsDao", UserVmDetailsDaoImpl.class); - addDao("ResourceCountDao", ResourceCountDaoImpl.class); - addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); - addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); - addDao("VpnUserDao", VpnUserDaoImpl.class); - addDao("ProjectDao", ProjectDaoImpl.class); - addDao("ProjectAccountDao", ProjectAccountDaoImpl.class); - addDao("LaunchPermissionDao", LaunchPermissionDaoImpl.class); - } - - @Override - public synchronized Map>> getDaos() { - if (_daos.size() == 0) { - populateDaos(); - } - return _daos; - } - - protected void populateManagers() { - addManager("configuration manager", MockConfigurationManagerImpl.class); - addManager("account manager", AccountManagerImpl.class); - addManager("domain manager", DomainManagerImpl.class); - addManager("Region Manager", RegionManagerImpl.class); - addManager("ResourceLimit Manager", MockResourceLimitManagerImpl.class); - addManager("Network Manager", MockNetworkManagerImpl.class); - addManager("UserVm Manager", MockUserVmManagerImpl.class); - addManager("Vm Manager", MockVirtualMachineManagerImpl.class); - addManager("Project Manager", MockProjectManagerImpl.class); - addManager("Vpc Manager", MockVpcManagerImpl.class); - addManager("Site2SiteVpn Manager", MockSite2SiteVpnManagerImpl.class); - addManager("SecurityGroup Manager", MockSecurityGroupManagerImpl.class); - addManager("Snapshot Manager", MockSnapshotManagerImpl.class); - addManager("Template Manager", MockTemplateManagerImpl.class); - addManager("Storage Manager", MockStorageManagerImpl.class); - addManager("RemoteAccessVpn Manager", MockRemoteAccessVpnManagerImpl.class); - addManager("Entity Manager", EntityManagerImpl.class); - } - - @Override - public synchronized Map> getManagers() { - if (_managers.size() == 0) { - populateManagers(); - } - return _managers; - } - - protected void populateAdapters() { - } - - @Override - public synchronized Map>> getAdapters() { - if (_adapters.size() == 0) { - populateAdapters(); - } - return _adapters; - } - - @Override - public synchronized Map, Class> getFactories() { - HashMap, Class> factories = new HashMap, Class>(); - factories.put(EntityManager.class, EntityManagerImpl.class); - return factories; - } - - protected void populateServices() { - } - - @Override - public synchronized Map> getPluggableServices() { - if (_pluggableServices.size() == 0) { - populateServices(); - } - return _pluggableServices; - } -} diff --git a/server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java b/server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java deleted file mode 100755 index 9c71c621dda..00000000000 --- a/server/test/com/cloud/network/security/MockSecurityGroupManagerImpl.java +++ /dev/null @@ -1,198 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.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/network/vpn/MockRemoteAccessVpnManagerImpl.java b/server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java deleted file mode 100755 index efda5c65ccb..00000000000 --- a/server/test/com/cloud/network/vpn/MockRemoteAccessVpnManagerImpl.java +++ /dev/null @@ -1,129 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.vpn; - -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.api.commands.ListRemoteAccessVpnsCmd; -import com.cloud.api.commands.ListVpnUsersCmd; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.RemoteAccessVpn; -import com.cloud.network.VpnUser; -import com.cloud.utils.component.Manager; - -@Local(value = RemoteAccessVpnService.class) -public class MockRemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manager { - - @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 RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, - String ipRange, boolean openFirewall, long networkId) - throws NetworkRuleConflictException { - // TODO Auto-generated method stub - return null; - } - - @Override - public void destroyRemoteAccessVpn(long vpnServerAddressId) - throws ResourceUnavailableException { - // TODO Auto-generated method stub - - } - - @Override - public RemoteAccessVpn startRemoteAccessVpn(long vpnServerAddressId, - boolean openFirewall) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return null; - } - - @Override - public VpnUser addVpnUser(long vpnOwnerId, String userName, String password) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean removeVpnUser(long vpnOwnerId, String userName) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List listVpnUsers(long vpnOwnerId, String userName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean applyVpnUsers(long vpnOwnerId, String userName) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List searchForRemoteAccessVpns( - ListRemoteAccessVpnsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForVpnUsers(ListVpnUsersCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listRemoteAccessVpns(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public RemoteAccessVpn getRemoteAccessVpn(long vpnId) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/server/test/com/cloud/server/MockManagementServerImpl.java b/server/test/com/cloud/server/MockManagementServerImpl.java deleted file mode 100755 index d505ff47bab..00000000000 --- a/server/test/com/cloud/server/MockManagementServerImpl.java +++ /dev/null @@ -1,483 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.server; - -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.cloud.alert.Alert; -import com.cloud.api.commands.CreateSSHKeyPairCmd; -import com.cloud.api.commands.DeleteSSHKeyPairCmd; -import com.cloud.api.commands.DestroySystemVmCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.commands.GetVMPasswordCmd; -import com.cloud.api.commands.ListAlertsCmd; -import com.cloud.api.commands.ListAsyncJobsCmd; -import com.cloud.api.commands.ListCapabilitiesCmd; -import com.cloud.api.commands.ListCapacityCmd; -import com.cloud.api.commands.ListCfgsByCmd; -import com.cloud.api.commands.ListClustersCmd; -import com.cloud.api.commands.ListDiskOfferingsCmd; -import com.cloud.api.commands.ListEventsCmd; -import com.cloud.api.commands.ListGuestOsCategoriesCmd; -import com.cloud.api.commands.ListGuestOsCmd; -import com.cloud.api.commands.ListHostsCmd; -import com.cloud.api.commands.ListIsosCmd; -import com.cloud.api.commands.ListPodsByCmd; -import com.cloud.api.commands.ListPublicIpAddressesCmd; -import com.cloud.api.commands.ListRoutersCmd; -import com.cloud.api.commands.ListSSHKeyPairsCmd; -import com.cloud.api.commands.ListServiceOfferingsCmd; -import com.cloud.api.commands.ListStoragePoolsCmd; -import com.cloud.api.commands.ListSystemVMsCmd; -import com.cloud.api.commands.ListTemplatesCmd; -import com.cloud.api.commands.ListVMGroupsCmd; -import com.cloud.api.commands.ListVlanIpRangesCmd; -import com.cloud.api.commands.ListZonesByCmd; -import com.cloud.api.commands.RebootSystemVmCmd; -import com.cloud.api.commands.RegisterSSHKeyPairCmd; -import com.cloud.api.commands.StopSystemVmCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; -import com.cloud.api.commands.UpdateIsoCmd; -import com.cloud.api.commands.UpdateTemplateCmd; -import com.cloud.api.commands.UpdateVMGroupCmd; -import com.cloud.api.commands.UpgradeSystemVMCmd; -import com.cloud.api.commands.UploadCustomCertificateCmd; -import com.cloud.async.AsyncJob; -import com.cloud.capacity.Capacity; -import com.cloud.configuration.Configuration; -import com.cloud.dc.DataCenter; -import com.cloud.dc.Pod; -import com.cloud.dc.Vlan; -import com.cloud.event.Event; -import com.cloud.event.EventVO; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.HypervisorCapabilities; -import com.cloud.info.ConsoleProxyInfo; -import com.cloud.network.IpAddress; -import com.cloud.network.router.VirtualRouter; -import com.cloud.offering.DiskOffering; -import com.cloud.offering.ServiceOffering; -import com.cloud.org.Cluster; -import com.cloud.storage.GuestOS; -import com.cloud.storage.GuestOSVO; -import com.cloud.storage.GuestOsCategory; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolVO; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.SSHKeyPair; -import com.cloud.utils.Pair; -import com.cloud.vm.InstanceGroup; -import com.cloud.vm.VirtualMachine; - -public class MockManagementServerImpl implements ManagementServer { - - @Override - public List listDataCenters(ListZonesByCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForConfigurations(ListCfgsByCmd c) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForServiceOfferings( - ListServiceOfferingsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForClusters(ListClustersCmd c) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForClusters(long zoneId, - Long startIndex, Long pageSizeVal, String hypervisorType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForPods(ListPodsByCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForServers(ListHostsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachineTemplate updateTemplate(UpdateIsoCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForEvents(ListEventsCmd c) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForRouters(ListRoutersCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForIPAddresses( - ListPublicIpAddressesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listGuestOSByCriteria(ListGuestOsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listGuestOSCategoriesByCriteria( - ListGuestOsCategoriesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachine stopSystemVM(StopSystemVmCmd cmd) - throws ResourceUnavailableException, ConcurrentOperationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachine startSystemVM(long vmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachine rebootSystemVM(RebootSystemVmCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachine destroySystemVM(DestroySystemVmCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForAlerts(ListAlertsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listCapacities(ListCapacityCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set> listIsos(ListIsosCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set> listTemplates(ListTemplatesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForDiskOfferings( - ListDiskOfferingsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForStoragePools( - ListStoragePoolsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForSystemVm(ListSystemVMsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ArrayList getCloudIdentifierResponse(long userId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean updateHostPassword(UpdateHostPasswordCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public InstanceGroup updateVmGroup(UpdateVMGroupCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForVmGroups(ListVMGroupsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map listCapabilities(ListCapabilitiesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getHypervisors(Long zoneId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String uploadCertificate(UploadCustomCertificateCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForVlans(ListVlanIpRangesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForAsyncJobs(ListAsyncJobsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String generateRandomPassword() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long saveStartedEvent(Long userId, Long accountId, String type, - String description, long startEventId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long saveCompletedEvent(Long userId, Long accountId, String level, - String type, String description, long startEventId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listSSHKeyPairs(ListSSHKeyPairsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public SSHKeyPair registerSSHKeyPair(RegisterSSHKeyPairCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deleteSSHKeyPair(DeleteSSHKeyPairCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public String getVMPassword(GetVMPasswordCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public com.cloud.vm.VirtualMachine.Type findSystemVMTypeById(long instanceId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Pair, List> listHostsForMigrationOfVM( - Long vmId, Long startIndex, Long pageSize) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String[] listEventTypes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listHypervisorCapabilities( - Long id, HypervisorType hypervisorType, String keyword, - Long startIndex, Long pageSizeVal) { - // TODO Auto-generated method stub - return null; - } - - @Override - public HypervisorCapabilities updateHypervisorCapabilities(Long id, - Long maxGuestsLimit, Boolean securityGroupEnabled) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listTopConsumedResources(ListCapacityCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getVersion() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String[] getApiConfig() { - // TODO Auto-generated method stub - return null; - } - - @Override - public HostVO getHostBy(long hostId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getEvents(long userId, long accountId, Long domainId, - String type, String level, Date startDate, Date endDate) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ConsoleProxyInfo getConsoleProxyForVm(long dataCenterId, - long userVmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getConsoleAccessUrlRoot(long vmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public GuestOSVO getGuestOs(Long guestOsId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Pair getVncPort(VirtualMachine vm) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getMemoryOrCpuCapacityByHost(Long hostId, short capacityType) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public List searchForStoragePools(Criteria c) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getHashKey() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/server/test/com/cloud/storage/MockStorageManagerImpl.java b/server/test/com/cloud/storage/MockStorageManagerImpl.java deleted file mode 100755 index 6273489ae35..00000000000 --- a/server/test/com/cloud/storage/MockStorageManagerImpl.java +++ /dev/null @@ -1,679 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.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/storage/snapshot/MockSnapshotManagerImpl.java b/server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java deleted file mode 100755 index c79966bd533..00000000000 --- a/server/test/com/cloud/storage/snapshot/MockSnapshotManagerImpl.java +++ /dev/null @@ -1,236 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.storage.snapshot; - -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.api.commands.CreateSnapshotPolicyCmd; -import com.cloud.api.commands.DeleteSnapshotPoliciesCmd; -import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; -import com.cloud.api.commands.ListSnapshotPoliciesCmd; -import com.cloud.api.commands.ListSnapshotsCmd; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.host.HostVO; -import com.cloud.storage.Snapshot; -import com.cloud.storage.SnapshotPolicyVO; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.VolumeVO; -import com.cloud.user.Account; -import com.cloud.utils.component.Manager; -import com.cloud.utils.db.Filter; - -@Local(value = { SnapshotManager.class, SnapshotService.class }) -public class MockSnapshotManagerImpl implements SnapshotManager, SnapshotService, Manager { - - @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 List listSnapshots(ListSnapshotsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deleteSnapshot(long snapshotId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SnapshotPolicy createPolicy(CreateSnapshotPolicyCmd cmd, - Account policyOwner) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List findRecurringSnapshotSchedule( - ListRecurringSnapshotScheduleCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listPoliciesforVolume( - ListSnapshotPoliciesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deleteSnapshotPolicies(DeleteSnapshotPoliciesCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Snapshot allocSnapshot(Long volumeId, Long policyId) - throws ResourceAllocationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Snapshot createSnapshot(Long volumeId, Long policyId, - Long snapshotId, Account snapshotOwner) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean backupSnapshotToSecondaryStorage(SnapshotVO snapshot) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void postCreateSnapshot(Long volumeId, Long snapshotId, - Long policyId, boolean backedUp) { - // TODO Auto-generated method stub - - } - - @Override - public boolean destroySnapshot(long userId, long snapshotId, long policyId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean deletePolicy(long userId, Long policyId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List listPoliciesforVolume(long volumeId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listSnapsforVolume(long volumeId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void deletePoliciesForVolume(Long volumeId) { - // TODO Auto-generated method stub - - } - - @Override - public boolean deleteSnapshotDirsForAccount(long accountId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SnapshotPolicyVO getPolicyForVolume(long volumeId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean destroySnapshotBackUp(long snapshotId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public SnapshotVO createSnapshotOnPrimary(VolumeVO volume, Long polocyId, - Long snapshotId) throws ResourceAllocationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listPoliciesforSnapshot(long snapshotId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listSnapsforPolicy(long policyId, Filter filter) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void downloadSnapshotsFromSwift(SnapshotVO ss) { - // TODO Auto-generated method stub - - } - - @Override - public HostVO getSecondaryStorageHost(SnapshotVO snapshot) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getSecondaryStorageURL(SnapshotVO snapshot) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void deleteSnapshotsForVolume(String secondaryStoragePoolUrl, - Long dcId, Long accountId, Long volumeId) { - // TODO Auto-generated method stub - - } - - @Override - public void deleteSnapshotsDirForVolume(String secondaryStoragePoolUrl, - Long dcId, Long accountId, Long volumeId) { - // TODO Auto-generated method stub - - } - - @Override - public boolean canOperateOnVolume(VolumeVO volume) { - // TODO Auto-generated method stub - return false; - } -} diff --git a/server/test/com/cloud/template/MockTemplateManagerImpl.java b/server/test/com/cloud/template/MockTemplateManagerImpl.java deleted file mode 100755 index 19cd8d1430f..00000000000 --- a/server/test/com/cloud/template/MockTemplateManagerImpl.java +++ /dev/null @@ -1,211 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.template; - -import java.net.URISyntaxException; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.api.commands.CopyTemplateCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ExtractIsoCmd; -import com.cloud.api.commands.ExtractTemplateCmd; -import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; -import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd; -import com.cloud.dc.DataCenterVO; -import com.cloud.exception.InternalErrorException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.StorageUnavailableException; -import com.cloud.host.HostVO; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolVO; -import com.cloud.storage.VMTemplateHostVO; -import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.storage.VMTemplateVO; -import com.cloud.utils.component.Manager; - - -@Local(value={TemplateManager.class, TemplateService.class}) -public class MockTemplateManagerImpl implements TemplateManager, Manager, TemplateService { - - @Override - public VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) - throws URISyntaxException, ResourceAllocationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) - throws IllegalArgumentException, ResourceAllocationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) - throws StorageUnavailableException, ResourceAllocationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachineTemplate prepareTemplate(long templateId, long zoneId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean detachIso(long vmId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean attachIso(long isoId, long vmId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean deleteTemplate(DeleteTemplateCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean deleteIso(DeleteIsoCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Long extract(ExtractIsoCmd cmd) throws InternalErrorException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long extract(ExtractTemplateCmd cmd) throws InternalErrorException { - // TODO Auto-generated method stub - return null; - } - - @Override - public VirtualMachineTemplate getTemplate(long templateId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listTemplatePermissions( - ListTemplateOrIsoPermissionsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean updateTemplateOrIsoPermissions( - UpdateTemplateOrIsoPermissionsCmd cmd) { - // 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 VMTemplateStoragePoolVO prepareTemplateForCreate( - VMTemplateVO template, StoragePool pool) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean resetTemplateDownloadStateOnPool( - long templateStoragePoolRefId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean copy(long userId, VMTemplateVO template, HostVO srcSecHost, - DataCenterVO srcZone, DataCenterVO dstZone) - throws StorageUnavailableException, ResourceAllocationException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean delete(long userId, long templateId, Long zoneId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List getUnusedTemplatesInPool( - StoragePoolVO pool) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void evictTemplateFromStoragePool( - VMTemplateStoragePoolVO templatePoolVO) { - // TODO Auto-generated method stub - - } - - @Override - public boolean templateIsDeleteable(VMTemplateHostVO templateHostRef) { - // TODO Auto-generated method stub - return false; - } - - @Override - public VMTemplateHostVO prepareISOForCreate(VMTemplateVO template, - StoragePool pool) { - // 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 e397b82d321..b6f30c48023 100644 --- a/server/test/com/cloud/vm/MockUserVmManagerImpl.java +++ b/server/test/com/cloud/vm/MockUserVmManagerImpl.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.vm; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -40,7 +39,6 @@ import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; -import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; @@ -197,7 +195,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana @Override public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { // TODO Auto-generated method stub - return new ArrayList(); + return null; } @Override From 158ee8b2fa0d7984229c7e647a15a003ea084017 Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Tue, 29 Jan 2013 11:49:23 +0530 Subject: [PATCH 14/24] Add sync entry to region_sunc table on region api failure --- .../DefaultComponentLibrary.java | 2 + .../com/cloud/region/FindDomainResponse.java | 36 ------------------ .../com/cloud/region/FindUserResponse.java | 34 ----------------- .../com/cloud/region/RegionManagerImpl.java | 14 +++++++ .../src/com/cloud/region/RegionsApiUtil.java | 37 ++----------------- setup/db/create-schema.sql | 9 +++++ 6 files changed, 29 insertions(+), 103 deletions(-) delete mode 100644 server/src/com/cloud/region/FindDomainResponse.java delete mode 100644 server/src/com/cloud/region/FindUserResponse.java diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index ee70b55825b..9fcfb814e7e 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -160,6 +160,7 @@ import com.cloud.projects.dao.ProjectDaoImpl; import com.cloud.projects.dao.ProjectInvitationDaoImpl; import com.cloud.region.RegionManagerImpl; import com.cloud.region.dao.RegionDaoImpl; +import com.cloud.region.dao.RegionSyncDaoImpl; import com.cloud.resource.ResourceManagerImpl; import com.cloud.resourcelimit.ResourceLimitManagerImpl; import com.cloud.service.dao.ServiceOfferingDaoImpl; @@ -401,6 +402,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("DiskOfferingJoinDao", DiskOfferingJoinDaoImpl.class); addDao("ServiceOfferingJoinDao", ServiceOfferingJoinDaoImpl.class); addDao("DataCenterJoinDao", DataCenterJoinDaoImpl.class); + addDao("RegionSyncDao", RegionSyncDaoImpl.class); } @Override diff --git a/server/src/com/cloud/region/FindDomainResponse.java b/server/src/com/cloud/region/FindDomainResponse.java deleted file mode 100644 index 075bcf220f1..00000000000 --- a/server/src/com/cloud/region/FindDomainResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.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 deleted file mode 100644 index b6eba46ac2f..00000000000 --- a/server/src/com/cloud/region/FindUserResponse.java +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.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/RegionManagerImpl.java b/server/src/com/cloud/region/RegionManagerImpl.java index a2a79e444c7..988231eddf5 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/com/cloud/region/RegionManagerImpl.java @@ -39,6 +39,7 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.region.dao.RegionDao; +import com.cloud.region.dao.RegionSyncDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -73,6 +74,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ private UserAccountDao _userAccountDao; @Inject private IdentityDao _identityDao; + @Inject + private RegionSyncDao _regionSyncDao; private String _name; private int _id; @@ -195,6 +198,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added account :"+accountName+" to Region: "+region.getId()); } else { + addRegionSyncItem(region.getId(), command, params); s_logger.error("Error while Adding account :"+accountName+" to Region: "+region.getId()); } } @@ -737,6 +741,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added user :"+userName+" to Region: "+region.getId()); } else { + addRegionSyncItem(region.getId(), command, params); s_logger.error("Error while Adding user :"+userName+" to Region: "+region.getId()); } } @@ -768,10 +773,19 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added domain :"+name+" to Region: "+region.getId()); } else { + addRegionSyncItem(region.getId(), command, params); s_logger.error("Error while Adding domain :"+name+" to Region: "+region.getId()); } } return; } + + private void addRegionSyncItem(int regionId, String command, List params){ + String api = RegionsApiUtil.buildParams(command, params); + RegionSyncVO sync = new RegionSyncVO(regionId, api); + if(_regionSyncDao.persist(sync) == null){ + s_logger.error("Failed to add Region Sync Item. RegionId: "+regionId + "API command: "+api); + } + } } diff --git a/server/src/com/cloud/region/RegionsApiUtil.java b/server/src/com/cloud/region/RegionsApiUtil.java index 3e20fd37f21..a7c71379794 100644 --- a/server/src/com/cloud/region/RegionsApiUtil.java +++ b/server/src/com/cloud/region/RegionsApiUtil.java @@ -38,14 +38,10 @@ 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 { @@ -53,7 +49,8 @@ public class RegionsApiUtil { protected static boolean makeAPICall(Region region, String command, List params){ try { - String url = buildUrl(buildParams(command, params), region); + String apiParams = buildParams(command, params); + String url = buildUrl(apiParams, region); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); if( client.executeMethod(method) == 200){ @@ -160,34 +157,7 @@ public class RegionsApiUtil { } } - 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) { + protected static String buildParams(String command, List params) { StringBuffer paramString = new StringBuffer("command="+command); Iterator iter = params.iterator(); try { @@ -282,4 +252,5 @@ public class RegionsApiUtil { return null; } } + } \ No newline at end of file diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 31f6d781557..2a6dc1a1837 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -2551,6 +2551,15 @@ CREATE TABLE `cloud`.`autoscale_vmgroup_policy_map` ( INDEX `i_autoscale_vmgroup_policy_map__vmgroup_id`(`vmgroup_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`region_sync` ( + `id` bigint unsigned NOT NULL auto_increment, + `region_id` int unsigned NOT NULL, + `api` varchar(1024) NOT NULL, + `created` datetime NOT NULL COMMENT 'date created', + `processed` tinyint NOT NULL default '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (1, UUID(), 'snmp','Linux User CPU - percentage', '1.3.6.1.4.1.2021.11.9.0', now()); INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (2, UUID(), 'snmp','Linux System CPU - percentage', '1.3.6.1.4.1.2021.11.10.0', now()); INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (3, UUID(), 'snmp','Linux CPU Idle - percentage', '1.3.6.1.4.1.2021.11.11.0', now()); From 60fd29dacd66c3c0f7a9771e838306e407458ecd Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Wed, 30 Jan 2013 11:11:49 +0530 Subject: [PATCH 15/24] Add sync entry to region_sunc table on region api failure --- server/src/com/cloud/region/RegionSyncVO.java | 93 +++++++++++++++++++ .../com/cloud/region/dao/RegionSyncDao.java | 23 +++++ .../cloud/region/dao/RegionSyncDaoImpl.java | 33 +++++++ 3 files changed, 149 insertions(+) create mode 100644 server/src/com/cloud/region/RegionSyncVO.java create mode 100644 server/src/com/cloud/region/dao/RegionSyncDao.java create mode 100644 server/src/com/cloud/region/dao/RegionSyncDaoImpl.java diff --git a/server/src/com/cloud/region/RegionSyncVO.java b/server/src/com/cloud/region/RegionSyncVO.java new file mode 100644 index 00000000000..fc3f4239672 --- /dev/null +++ b/server/src/com/cloud/region/RegionSyncVO.java @@ -0,0 +1,93 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.region; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + + +@Entity +@Table(name="region_sync") +public class RegionSyncVO implements RegionSync { + + @Id + @Column(name="id") + private long id; + + @Column(name="region_id") + private int regionId; + + @Column(name="api") + private String api; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date createDate; + + @Column(name="processed") + boolean processed; + + public RegionSyncVO() { + } + + public RegionSyncVO(int regionId, String api) { + this.regionId = regionId; + this.api = api; + } + + public int getRegionId() { + return regionId; + } + + public void setRegionId(int regionId) { + this.regionId = regionId; + } + + public String getApi() { + return api; + } + + public void setApi(String api) { + this.api = api; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public boolean isProcessed() { + return processed; + } + + public void setProcessed(boolean processed) { + this.processed = processed; + } + + public long getId() { + return id; + } + +} diff --git a/server/src/com/cloud/region/dao/RegionSyncDao.java b/server/src/com/cloud/region/dao/RegionSyncDao.java new file mode 100644 index 00000000000..5387d2ea0e2 --- /dev/null +++ b/server/src/com/cloud/region/dao/RegionSyncDao.java @@ -0,0 +1,23 @@ +// 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.dao; + +import com.cloud.region.RegionSyncVO; +import com.cloud.utils.db.GenericDao; + +public interface RegionSyncDao extends GenericDao { +} diff --git a/server/src/com/cloud/region/dao/RegionSyncDaoImpl.java b/server/src/com/cloud/region/dao/RegionSyncDaoImpl.java new file mode 100644 index 00000000000..766286e45cb --- /dev/null +++ b/server/src/com/cloud/region/dao/RegionSyncDaoImpl.java @@ -0,0 +1,33 @@ +// 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.dao; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.region.RegionSyncVO; +import com.cloud.utils.db.GenericDaoBase; + +@Local(value={RegionSyncDao.class}) +public class RegionSyncDaoImpl extends GenericDaoBase implements RegionSyncDao { + private static final Logger s_logger = Logger.getLogger(RegionSyncDaoImpl.class); + + public RegionSyncDaoImpl(){ + + } +} From e848a937df6037b151de3e0a3ce70fcd8db49a82 Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Wed, 30 Jan 2013 11:20:30 +0530 Subject: [PATCH 16/24] Add sync entry to region_sunc table on region api failure --- api/src/com/cloud/region/RegionSync.java | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 api/src/com/cloud/region/RegionSync.java diff --git a/api/src/com/cloud/region/RegionSync.java b/api/src/com/cloud/region/RegionSync.java new file mode 100644 index 00000000000..ed485df123b --- /dev/null +++ b/api/src/com/cloud/region/RegionSync.java @@ -0,0 +1,33 @@ +// 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.util.Date; + +/** + * + */ +public interface RegionSync { + + public long getId(); + + public int getRegionId(); + + public String getApi(); + + Date getCreateDate(); +} From 8b1a5b1de2ef4e69e2bde234c56dff120cb666f0 Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Thu, 31 Jan 2013 18:08:20 +0530 Subject: [PATCH 17/24] - Separated RegionServiceImpl and RegionManagerImpl - Added comments - Changed package name to org.apache.cloudstack.region --- api/src/com/cloud/region/RegionService.java | 49 -- api/src/com/cloud/user/AccountService.java | 93 ---- api/src/com/cloud/user/DomainService.java | 11 - .../org/apache/cloudstack/api/BaseCmd.java | 2 +- .../cloudstack/api/ResponseGenerator.java | 2 +- .../admin/account/DeleteAccountCmd.java | 9 +- .../admin/account/DisableAccountCmd.java | 19 +- .../admin/account/EnableAccountCmd.java | 8 +- .../admin/account/UpdateAccountCmd.java | 8 +- .../command/admin/domain/DeleteDomainCmd.java | 7 +- .../command/admin/domain/UpdateDomainCmd.java | 8 +- .../command/admin/region/AddRegionCmd.java | 10 +- .../command/admin/region/UpdateRegionCmd.java | 8 +- .../api/command/admin/user/DeleteUserCmd.java | 8 +- .../command/admin/user/DisableUserCmd.java | 8 +- .../api/command/admin/user/EnableUserCmd.java | 8 +- .../api/command/admin/user/UpdateUserCmd.java | 8 +- .../command/user/region/ListRegionsCmd.java | 9 +- .../api/response/RegionResponse.java | 3 + .../apache/cloudstack}/region/Region.java | 2 +- .../cloudstack/region/RegionService.java | 157 ++++++ .../apache/cloudstack}/region/RegionSync.java | 2 +- client/tomcatconf/components.xml.in | 2 +- .../src/com/cloud/api/ApiResponseHelper.java | 3 +- server/src/com/cloud/api/ApiServer.java | 2 +- .../DefaultComponentLibrary.java | 7 +- .../com/cloud/domain/dao/DomainDaoImpl.java | 1 - .../src/com/cloud/region/RegionManager.java | 30 -- .../com/cloud/region/dao/RegionDaoImpl.java | 33 -- .../cloud/server/ConfigurationServerImpl.java | 5 +- server/src/com/cloud/user/AccountManager.java | 95 +++- .../com/cloud/user/AccountManagerImpl.java | 15 +- server/src/com/cloud/user/DomainManager.java | 14 +- .../src/com/cloud/user/DomainManagerImpl.java | 5 +- .../src/com/cloud/user/dao/UserDaoImpl.java | 3 - .../cloudstack}/region/RegionAccount.java | 2 +- .../cloudstack}/region/RegionDomain.java | 2 +- .../cloudstack/region/RegionManager.java | 216 ++++++++ .../cloudstack}/region/RegionManagerImpl.java | 486 ++++++++++-------- .../cloudstack/region/RegionServiceImpl.java | 299 +++++++++++ .../cloudstack}/region/RegionSyncVO.java | 2 +- .../apache/cloudstack}/region/RegionUser.java | 2 +- .../apache/cloudstack}/region/RegionVO.java | 2 +- .../cloudstack}/region/RegionsApiUtil.java | 52 +- .../cloudstack}/region/dao/RegionDao.java | 11 +- .../cloudstack/region/dao/RegionDaoImpl.java | 62 +++ .../cloudstack}/region/dao/RegionSyncDao.java | 5 +- .../region/dao/RegionSyncDaoImpl.java | 4 +- setup/db/create-schema.sql | 2 +- 49 files changed, 1247 insertions(+), 554 deletions(-) delete mode 100644 api/src/com/cloud/region/RegionService.java rename api/src/{com/cloud => org/apache/cloudstack}/region/Region.java (96%) create mode 100644 api/src/org/apache/cloudstack/region/RegionService.java rename api/src/{com/cloud => org/apache/cloudstack}/region/RegionSync.java (96%) delete mode 100644 server/src/com/cloud/region/RegionManager.java delete mode 100644 server/src/com/cloud/region/dao/RegionDaoImpl.java rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionAccount.java (99%) rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionDomain.java (97%) create mode 100644 server/src/org/apache/cloudstack/region/RegionManager.java rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionManagerImpl.java (91%) create mode 100755 server/src/org/apache/cloudstack/region/RegionServiceImpl.java rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionSyncVO.java (98%) rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionUser.java (97%) rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionVO.java (98%) rename server/src/{com/cloud => org/apache/cloudstack}/region/RegionsApiUtil.java (87%) rename server/src/{com/cloud => org/apache/cloudstack}/region/dao/RegionDao.java (81%) create mode 100644 server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java rename server/src/{com/cloud => org/apache/cloudstack}/region/dao/RegionSyncDao.java (90%) rename server/src/{com/cloud => org/apache/cloudstack}/region/dao/RegionSyncDaoImpl.java (92%) diff --git a/api/src/com/cloud/region/RegionService.java b/api/src/com/cloud/region/RegionService.java deleted file mode 100644 index ef4b5cb1a13..00000000000 --- a/api/src/com/cloud/region/RegionService.java +++ /dev/null @@ -1,49 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.region; - -import java.util.List; - -import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; -import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; -import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; -import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; -import org.apache.cloudstack.api.command.user.region.ListRegionsCmd; - -import com.cloud.domain.Domain; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; -import com.cloud.user.UserAccount; - - -public interface RegionService { - 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); - public Account disableAccount(String accountName, Long domainId, Long id, Boolean lockRequested) throws ConcurrentOperationException, ResourceUnavailableException; - public Account enableAccount(String accountName, Long domainId, Long id); - public boolean deleteUser(DeleteUserCmd deleteUserCmd); - public boolean deleteDomain(Long id, Boolean cleanup); - public UserAccount updateUser(UpdateUserCmd updateUserCmd); - public Domain updateDomain(UpdateDomainCmd updateDomainCmd); - public UserAccount disableUser(Long id); - public UserAccount enableUser(Long id); -} diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 553c84ae100..0c1fc77f71f 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -23,15 +23,10 @@ import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; import org.apache.cloudstack.api.command.admin.user.RegisterCmd; -import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; -import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; import com.cloud.domain.Domain; -import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceUnavailableException; import com.cloud.utils.Pair; public interface AccountService { @@ -65,34 +60,6 @@ public interface AccountService { 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); - /** - * Deletes a user by userId - * - * @param accountId - * - id of the account do delete - * - * @return true if delete was successful, false otherwise - */ - boolean deleteUserAccount(long accountId); - - /** - * Disables a user by userId - * - * @param userId - * - the userId - * @return UserAccount object - */ - UserAccount disableUser(long userId); - - /** - * Enables a user - * - * @param userId - * - the userId - * @return UserAccount object - */ - UserAccount enableUser(long userId); - /** * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses * allocated/etc. @@ -102,72 +69,12 @@ public interface AccountService { */ UserAccount lockUser(long userId); - /** - * Update a user by userId - * - * @param userId - * @return UserAccount object - */ - UserAccount updateUser(UpdateUserCmd cmd); - - /** - * Disables an account by accountName and domainId - * - * @param accountName - * TODO - * @param domainId - * TODO - * @param accountId - * @param disabled - * account if success - * @return true if disable was successful, false otherwise - */ - Account disableAccount(String accountName, Long domainId, Long accountId) throws ConcurrentOperationException, ResourceUnavailableException; - - /** - * Enables an account by accountId - * - * @param accountName - * - the enableAccount command defining the accountId to be deleted. - * @param domainId - * TODO - * @param accountId - * @return account object - */ - Account enableAccount(String accountName, Long domainId, Long accountId); - - /** - * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP - * addresses - * allocated/etc. - * - * @param accountName - * - the LockAccount command defining the accountId to be locked. - * @param domainId - * TODO - * @param accountId - * @return account object - */ - Account lockAccount(String accountName, Long domainId, Long accountId); - - /** - * Updates an account name - * - * @param cmd - * - the parameter containing accountId - * @return updated account object - */ - - Account updateAccount(UpdateAccountCmd cmd); - Account getSystemAccount(); User getSystemUser(); User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, Integer regionId); - boolean deleteUser(DeleteUserCmd deleteUserCmd); - boolean isAdmin(short accountType); Account finalizeOwner(Account caller, String accountName, Long domainId, Long projectId); diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 9fca09de1e6..1a9635499f1 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -20,7 +20,6 @@ import java.util.List; import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; -import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; import com.cloud.domain.Domain; import com.cloud.exception.PermissionDeniedException; @@ -42,21 +41,11 @@ public interface DomainService { */ boolean isChildDomain(Long parentId, Long childId); - boolean deleteDomain(long domainId, Boolean cleanup); - Pair, Integer> searchForDomains(ListDomainsCmd cmd) throws PermissionDeniedException; Pair, Integer> 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 diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index c0d465f6d6e..e2c3e03ac66 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.regex.Pattern; import org.apache.cloudstack.query.QueryService; +import org.apache.cloudstack.region.RegionService; import org.apache.log4j.Logger; import com.cloud.configuration.ConfigurationService; @@ -53,7 +54,6 @@ import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.network.vpn.Site2SiteVpnService; import com.cloud.projects.Project; import com.cloud.projects.ProjectService; -import com.cloud.region.RegionService; import com.cloud.resource.ResourceService; import com.cloud.server.ManagementService; import com.cloud.server.TaggedResourceService; diff --git a/api/src/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java index d6780fd66a0..0b9eb5017b2 100644 --- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -93,6 +93,7 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.region.Region; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; @@ -143,7 +144,6 @@ import com.cloud.org.Cluster; import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; -import com.cloud.region.Region; import com.cloud.server.ResourceTag; import com.cloud.storage.GuestOS; import com.cloud.storage.S3; diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java index c918655e125..22cab8aab40 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java @@ -94,13 +94,8 @@ public class DeleteAccountCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Account Id: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - boolean result = false; - if(isPopagate){ - result = _accountService.deleteUserAccount(getId()); - } else { - result = _regionService.deleteUserAccount(getId()); - } + + boolean result = _regionService.deleteUserAccount(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java index 32bc9d45a3c..e78a09c3084 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java @@ -74,12 +74,16 @@ public class DisableAccountCmd extends BaseAsyncCmd { public Boolean getIsPropagate() { return isPropagate; } - + + public Boolean getLockRequested() { + return lockRequested; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } @@ -112,16 +116,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException{ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); - Account result = null; - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - if(isPopagate){ - if(lockRequested) - result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); - else - result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); - } else { - result = _regionService.disableAccount(getAccountName(), getDomainId(), getId(), lockRequested); - } + Account result = _regionService.disableAccount(this); if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java index 08fe4c50329..09aafea6f9b 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java @@ -97,13 +97,7 @@ public class EnableAccountCmd extends BaseCmd { @Override public void execute(){ - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - Account result = null; - if(isPopagate){ - result = _accountService.enableAccount(getAccountName(), getDomainId(), getId()); - } else { - result = _regionService.enableAccount(getAccountName(), getDomainId(), getId()); - } + Account result = _regionService.enableAccount(this); if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java index ea46ba9e17a..5840647a9f8 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java @@ -127,13 +127,7 @@ public class UpdateAccountCmd extends BaseCmd{ @Override public void execute(){ - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - Account result = null; - if(isPopagate){ - result = _accountService.updateAccount(this); - } else { - result = _regionService.updateAccount(this); - } + Account result = _regionService.updateAccount(this); if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java index 7c33c79ba1f..b0133916041 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java @@ -95,12 +95,7 @@ public class DeleteDomainCmd extends BaseAsyncCmd { public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - boolean result = false; - if(isPopagate){ - result = _domainService.deleteDomain(id, cleanup); - } else { - result = _regionService.deleteDomain(id, cleanup); - } + boolean result = _regionService.deleteDomain(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java index 8de92be3d9d..79e57a6dae2 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java @@ -85,13 +85,7 @@ public class UpdateDomainCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - Domain domain = null; - if(isPopagate){ - domain = _domainService.updateDomain(this); - } else { - domain = _regionService.updateDomain(this); - } + Domain domain = _regionService.updateDomain(this); if (domain != null) { DomainResponse response = _responseGenerator.createDomainResponse(domain); diff --git a/api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java b/api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java index 73453a68fab..f9663b7049c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java @@ -23,9 +23,9 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.RegionResponse; +import org.apache.cloudstack.region.Region; import org.apache.log4j.Logger; -import com.cloud.region.Region; import com.cloud.user.Account; @APICommand(name = "addRegion", description="Adds a Region", responseObject=RegionResponse.class) @@ -40,16 +40,16 @@ public class AddRegionCmd extends BaseCmd { @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") + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the region") private String regionName; - @Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, required=true, description="end_point of the Region") + @Parameter(name=ApiConstants.END_POINT, type=CommandType.STRING, required=true, description="Region service endpoint") private String endPoint; - @Parameter(name=ApiConstants.API_KEY, type=CommandType.STRING, description="API key") + @Parameter(name=ApiConstants.API_KEY, type=CommandType.STRING, description="API key of Admin user") private String apiKey; - @Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="Secret Key") + @Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="Secret Key of Admin user") private String secretKey; ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java b/api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java index 626fb337aba..bc6576c23ff 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java @@ -23,9 +23,9 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.RegionResponse; +import org.apache.cloudstack.region.Region; import org.apache.log4j.Logger; -import com.cloud.region.Region; import com.cloud.user.Account; @APICommand(name = "updateRegion", description="Updates a region", responseObject=RegionResponse.class) @@ -37,7 +37,7 @@ public class UpdateRegionCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, required=true, description="ID of region to update") + @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") @@ -46,10 +46,10 @@ 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") + @Parameter(name=ApiConstants.API_KEY, type=CommandType.STRING, description="new API key for the Region") private String apiKey; - @Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="Secret Key") + @Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="new Secret Key for the Region") private String secretKey; ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java index 329bd9a4119..d333f60b2e3 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java @@ -79,13 +79,7 @@ public class DeleteUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - boolean result = false; - if(isPopagate){ - result = _accountService.deleteUser(this); - } else { - result = _regionService.deleteUser(this); - } + boolean result = _regionService.deleteUser(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java index f3a3b2b2094..91a92539823 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java @@ -93,13 +93,7 @@ public class DisableUserCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - UserAccount user = null; - if(isPopagate){ - user = _accountService.disableUser(getId()); - } else { - user = _regionService.disableUser(getId()); - } + UserAccount user = _regionService.disableUser(this); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java index d6577fb0d32..082b5acb780 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java @@ -76,13 +76,7 @@ public class EnableUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - UserAccount user = null; - if(isPopagate){ - user = _accountService.enableUser(getId()); - } else { - user = _regionService.enableUser(getId()); - } + UserAccount user = _regionService.enableUser(this); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java index 7369933cbe8..b6f23a220b9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java @@ -133,13 +133,7 @@ public class UpdateUserCmd extends BaseCmd { @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; - UserAccount user = null; - if(isPopagate){ - user = _accountService.updateUser(this); - } else { - user = _regionService.updateUser(this); - } + UserAccount user = _regionService.updateUser(this); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); diff --git a/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java index beddc3f4f33..4599a197d8b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java @@ -25,10 +25,9 @@ import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.RegionResponse; +import org.apache.cloudstack.region.Region; import org.apache.log4j.Logger; -import com.cloud.region.Region; - @APICommand(name = "listRegions", description="Lists Regions", responseObject=RegionResponse.class) public class ListRegionsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListRegionsCmd.class.getName()); @@ -43,7 +42,7 @@ public class ListRegionsCmd extends BaseListCmd { private Integer id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List Region by region name.") - private String domainName; + private String name; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -53,8 +52,8 @@ public class ListRegionsCmd extends BaseListCmd { return id; } - public String getRegionName() { - return domainName; + public String getName() { + return name; } ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/response/RegionResponse.java b/api/src/org/apache/cloudstack/api/response/RegionResponse.java index cbd14b6fb5a..f8bfe53aae3 100644 --- a/api/src/org/apache/cloudstack/api/response/RegionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RegionResponse.java @@ -18,10 +18,13 @@ package org.apache.cloudstack.api.response; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.region.Region; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@EntityReference(value = Region.class) public class RegionResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the region") private Integer id; diff --git a/api/src/com/cloud/region/Region.java b/api/src/org/apache/cloudstack/region/Region.java similarity index 96% rename from api/src/com/cloud/region/Region.java rename to api/src/org/apache/cloudstack/region/Region.java index 96d7dff5e10..7f0aeeab2ef 100644 --- a/api/src/com/cloud/region/Region.java +++ b/api/src/org/apache/cloudstack/region/Region.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; /** * diff --git a/api/src/org/apache/cloudstack/region/RegionService.java b/api/src/org/apache/cloudstack/region/RegionService.java new file mode 100644 index 00000000000..8679ca92b10 --- /dev/null +++ b/api/src/org/apache/cloudstack/region/RegionService.java @@ -0,0 +1,157 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.region; + +import java.util.List; + +import org.apache.cloudstack.api.command.admin.account.DeleteAccountCmd; +import org.apache.cloudstack.api.command.admin.account.DisableAccountCmd; +import org.apache.cloudstack.api.command.admin.account.EnableAccountCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.domain.DeleteDomainCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.DisableUserCmd; +import org.apache.cloudstack.api.command.admin.user.EnableUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.api.command.user.region.ListRegionsCmd; + +import com.cloud.domain.Domain; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.UserAccount; + + +public interface RegionService { + /** + * Adds a Region to the local Region + * @param id + * @param name + * @param endPoint + * @param apiKey + * @param secretKey + * @return Return added Region object + */ + public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey); + + /** + * Update details of the Region with specified Id + * @param id + * @param name + * @param endPoint + * @param apiKey + * @param secretKey + * @return Return updated Region object + */ + public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey); + + /** + * @param id + * @return True if region is successfully removed + */ + public boolean removeRegion(int id); + + /** List all Regions or by Id/Name + * @param id + * @param name + * @return List of Regions + */ + public List listRegions(ListRegionsCmd cmd); + + /** + * Deletes a user by userId + * isPopagate flag is set to true if sent from peer Region + * @param cmd + * + * @return true if delete was successful, false otherwise + */ + boolean deleteUserAccount(DeleteAccountCmd cmd); + + /** + * Updates an account + * isPopagate falg is set to true if sent from peer Region + * + * @param cmd + * - the parameter containing accountId or account nameand domainId + * @return updated account object + */ + Account updateAccount(UpdateAccountCmd cmd); + + /** + * Disables an account by accountName and domainId or accountId + * @param cmd + * @return + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException + */ + Account disableAccount(DisableAccountCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException; + + /** + * Enables an account by accountId + * @param cmd + * @return + */ + Account enableAccount(EnableAccountCmd cmd); + + /** + * Deletes user by Id + * @param deleteUserCmd + * @return true if delete was successful, false otherwise + */ + boolean deleteUser(DeleteUserCmd deleteUserCmd); + + /** + * update an existing domain + * + * @param cmd + * - the command containing domainId and new domainName + * @return Domain object if the command succeeded + */ + public Domain updateDomain(UpdateDomainCmd updateDomainCmd); + + /** + * Deletes domain + * @param cmd + * @return true if delete was successful, false otherwise + */ + public boolean deleteDomain(DeleteDomainCmd cmd); + + /** + * Update a user by userId + * + * @param userId + * @return UserAccount object + */ + public UserAccount updateUser(UpdateUserCmd updateUserCmd); + + /** + * Disables a user by userId + * + * @param cmd + * @return UserAccount object + */ + public UserAccount disableUser(DisableUserCmd cmd); + + /** + * Enables a user + * + * @param cmd + * @return UserAccount object + */ + public UserAccount enableUser(EnableUserCmd cmd); +} diff --git a/api/src/com/cloud/region/RegionSync.java b/api/src/org/apache/cloudstack/region/RegionSync.java similarity index 96% rename from api/src/com/cloud/region/RegionSync.java rename to api/src/org/apache/cloudstack/region/RegionSync.java index ed485df123b..5a1f5a6c19d 100644 --- a/api/src/com/cloud/region/RegionSync.java +++ b/api/src/org/apache/cloudstack/region/RegionSync.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import java.util.Date; diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index 99b8430d0fb..c45d14ee6eb 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -271,7 +271,7 @@ under the License. - + diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 86f0ea3a7c1..8c5ed27251f 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -136,6 +136,8 @@ import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.api.response.S3Response; +import org.apache.cloudstack.region.Region; + import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; @@ -205,7 +207,6 @@ import com.cloud.org.Cluster; import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; -import com.cloud.region.Region; import com.cloud.server.Criteria; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.TaggedResourceType; diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index d2d07125acb..cb2f414e913 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -105,6 +105,7 @@ import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import com.cloud.api.response.ApiResponseSerializer; import org.apache.cloudstack.api.response.ExceptionResponse; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.region.RegionManager; import com.cloud.async.AsyncCommandQueued; import com.cloud.async.AsyncJob; @@ -122,7 +123,6 @@ import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; -import com.cloud.region.RegionManager; import com.cloud.exception.RequestLimitException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 9fcfb814e7e..61e79a6821f 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -21,6 +21,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.cloudstack.region.RegionManagerImpl; +import org.apache.cloudstack.region.dao.RegionDaoImpl; +import org.apache.cloudstack.region.dao.RegionSyncDaoImpl; + import com.cloud.agent.manager.ClusteredAgentManagerImpl; import com.cloud.alert.AlertManagerImpl; import com.cloud.alert.dao.AlertDaoImpl; @@ -158,9 +162,6 @@ import com.cloud.projects.ProjectManagerImpl; import com.cloud.projects.dao.ProjectAccountDaoImpl; import com.cloud.projects.dao.ProjectDaoImpl; import com.cloud.projects.dao.ProjectInvitationDaoImpl; -import com.cloud.region.RegionManagerImpl; -import com.cloud.region.dao.RegionDaoImpl; -import com.cloud.region.dao.RegionSyncDaoImpl; import com.cloud.resource.ResourceManagerImpl; import com.cloud.resourcelimit.ResourceLimitManagerImpl; import com.cloud.service.dao.ServiceOfferingDaoImpl; diff --git a/server/src/com/cloud/domain/dao/DomainDaoImpl.java b/server/src/com/cloud/domain/dao/DomainDaoImpl.java index ecf83258b1e..b3a17069217 100644 --- a/server/src/com/cloud/domain/dao/DomainDaoImpl.java +++ b/server/src/com/cloud/domain/dao/DomainDaoImpl.java @@ -29,7 +29,6 @@ import org.apache.log4j.Logger; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; -import com.cloud.region.RegionManager; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; diff --git a/server/src/com/cloud/region/RegionManager.java b/server/src/com/cloud/region/RegionManager.java deleted file mode 100644 index 437e02d334d..00000000000 --- a/server/src/com/cloud/region/RegionManager.java +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.region; - -import java.util.Map; - -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 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); -} diff --git a/server/src/com/cloud/region/dao/RegionDaoImpl.java b/server/src/com/cloud/region/dao/RegionDaoImpl.java deleted file mode 100644 index 0d8a69d5620..00000000000 --- a/server/src/com/cloud/region/dao/RegionDaoImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.region.dao; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.region.RegionVO; -import com.cloud.utils.db.GenericDaoBase; - -@Local(value={RegionDao.class}) -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 a63ad195812..2ae0843b247 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -52,8 +52,6 @@ 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; @@ -74,6 +72,8 @@ import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; import com.cloud.uuididentity.dao.IdentityDao; +import org.apache.cloudstack.region.RegionVO; +import org.apache.cloudstack.region.dao.RegionDao; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; @@ -1252,7 +1252,6 @@ public class ConfigurationServerImpl implements ConfigurationServer { 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/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java index a2623084844..4b3a601b802 100755 --- a/server/src/com/cloud/user/AccountManager.java +++ b/server/src/com/cloud/user/AccountManager.java @@ -20,6 +20,10 @@ import java.util.List; import java.util.Map; import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; + import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; @@ -102,5 +106,94 @@ public interface AccountManager extends AccountService { void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation); - + + /** + * Deletes a user by userId + * + * @param accountId + * - id of the account do delete + * + * @return true if delete was successful, false otherwise + */ + boolean deleteUserAccount(long accountId); + + /** + * Updates an account + * + * @param cmd + * - the parameter containing accountId or account nameand domainId + * @return updated account object + */ + Account updateAccount(UpdateAccountCmd cmd); + + /** + * Disables an account by accountName and domainId + * + * @param accountName + * @param domainId + * @param accountId + * @param disabled + * account if success + * @return true if disable was successful, false otherwise + */ + Account disableAccount(String accountName, Long domainId, Long accountId) throws ConcurrentOperationException, ResourceUnavailableException; + + /** + * Enables an account by accountId + * + * @param accountName + * - the enableAccount command defining the accountId to be deleted. + * @param domainId + * TODO + * @param accountId + * @return account object + */ + Account enableAccount(String accountName, Long domainId, Long accountId); + + /** + * Deletes user by Id + * @param deleteUserCmd + * @return + */ + boolean deleteUser(DeleteUserCmd deleteUserCmd); + + /** + * Update a user by userId + * + * @param userId + * @return UserAccount object + */ + UserAccount updateUser(UpdateUserCmd cmd); + + /** + * Disables a user by userId + * + * @param userId + * - the userId + * @return UserAccount object + */ + UserAccount disableUser(long userId); + + /** + * Enables a user + * + * @param userId + * - the userId + * @return UserAccount object + */ + UserAccount enableUser(long userId); + + /** + * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP + * addresses + * allocated/etc. + * + * @param accountName + * - the LockAccount command defining the accountId to be locked. + * @param domainId + * TODO + * @param accountId + * @return account object + */ + Account lockAccount(String accountName, Long domainId, Long accountId); } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index c5c53e898dc..919b7c6e897 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -52,11 +52,12 @@ import com.cloud.api.query.vo.ControlledViewEntity; import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.region.RegionManager; + import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.configuration.dao.ConfigurationDaoImpl; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.DataCenterDao; @@ -97,7 +98,6 @@ import com.cloud.projects.ProjectManager; import com.cloud.projects.ProjectVO; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; -import com.cloud.region.RegionManager; import com.cloud.server.auth.UserAuthenticator; import com.cloud.storage.StorageManager; import com.cloud.storage.VMTemplateVO; @@ -830,13 +830,13 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag user.setRegistrationToken(registrationToken); } txn.commit(); - //Propogate Add account to other Regions - _regionMgr.propogateAddAccount(userName, password, firstName, lastName, email, timezone, accountName, accountType, domainId, + //Propagate Add account to other Regions + _regionMgr.propagateAddAccount(userName, password, firstName, lastName, email, timezone, accountName, accountType, domainId, networkDomain, details, account.getUuid(), user.getUuid()); //check success return _userAccountDao.findById(user.getId()); } else { - // Account is propogated from another Region + // Account is propagated from another Region Transaction txn = Transaction.currentTxn(); txn.start(); @@ -891,8 +891,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserVO user = null; if(regionId == null){ user = createUser(account.getId(), userName, password, firstName, lastName, email, timeZone); - //Propogate Add user to other Regions - _regionMgr.propogateAddUser(userName, password, firstName, lastName, email, timeZone, accountName, domain.getUuid(), user.getUuid()); + //Propagate Add user to peer Regions + _regionMgr.propagateAddUser(userName, password, firstName, lastName, email, timeZone, accountName, domain.getUuid(), user.getUuid()); } else { user = createUser(account.getId(), userName, password, firstName, lastName, email, timeZone, userUUID, regionId); } @@ -1744,7 +1744,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Create default security group _networkGroupMgr.createDefaultSecurityGroup(accountId); - //_regionMgr.propogateAddResource(); txn.commit(); return account; diff --git a/server/src/com/cloud/user/DomainManager.java b/server/src/com/cloud/user/DomainManager.java index aea653e6f4c..af102e20a5c 100644 --- a/server/src/com/cloud/user/DomainManager.java +++ b/server/src/com/cloud/user/DomainManager.java @@ -19,6 +19,8 @@ package com.cloud.user; import java.util.List; import java.util.Set; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; + import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; @@ -34,5 +36,15 @@ public interface DomainManager extends DomainService { List findInactiveDomains(); boolean deleteDomain(DomainVO domain, Boolean cleanup); - + + boolean deleteDomain(long domainId, Boolean cleanup); + + /** + * update an existing domain + * + * @param cmd + * - the command containing domainId and new domainName + * @return Domain object if the command succeeded + */ + Domain updateDomain(UpdateDomainCmd cmd); } diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 92277e85bd0..2fde0e18641 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -27,6 +27,7 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.region.RegionManager; import org.apache.log4j.Logger; import com.cloud.configuration.ResourceLimit; @@ -43,7 +44,6 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.ProjectManager; import com.cloud.projects.ProjectVO; import com.cloud.projects.dao.ProjectDao; -import com.cloud.region.RegionManager; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; @@ -187,8 +187,9 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, _regionMgr.getId())); _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain); - _regionMgr.propogateAddDomain(name, parentId, networkDomain, domain.getUuid()); txn.commit(); + //Propagate domain creation to peer Regions + _regionMgr.propagateAddDomain(name, parentId, networkDomain, domain.getUuid()); return domain; } else { Transaction txn = Transaction.currentTxn(); diff --git a/server/src/com/cloud/user/dao/UserDaoImpl.java b/server/src/com/cloud/user/dao/UserDaoImpl.java index 19ef69155ad..e1f4a2e25f3 100644 --- a/server/src/com/cloud/user/dao/UserDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserDaoImpl.java @@ -20,10 +20,7 @@ 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; import com.cloud.utils.db.SearchCriteria; diff --git a/server/src/com/cloud/region/RegionAccount.java b/server/src/org/apache/cloudstack/region/RegionAccount.java similarity index 99% rename from server/src/com/cloud/region/RegionAccount.java rename to server/src/org/apache/cloudstack/region/RegionAccount.java index cb942100077..dba31019b32 100644 --- a/server/src/com/cloud/region/RegionAccount.java +++ b/server/src/org/apache/cloudstack/region/RegionAccount.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import com.cloud.user.AccountVO; diff --git a/server/src/com/cloud/region/RegionDomain.java b/server/src/org/apache/cloudstack/region/RegionDomain.java similarity index 97% rename from server/src/com/cloud/region/RegionDomain.java rename to server/src/org/apache/cloudstack/region/RegionDomain.java index de82654c8bc..df46198976f 100644 --- a/server/src/com/cloud/region/RegionDomain.java +++ b/server/src/org/apache/cloudstack/region/RegionDomain.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import com.cloud.domain.DomainVO; diff --git a/server/src/org/apache/cloudstack/region/RegionManager.java b/server/src/org/apache/cloudstack/region/RegionManager.java new file mode 100644 index 00000000000..56bdb9baedf --- /dev/null +++ b/server/src/org/apache/cloudstack/region/RegionManager.java @@ -0,0 +1,216 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.region; + +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; + +import com.cloud.domain.Domain; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.UserAccount; + +public interface RegionManager { + + /** + * Propagates Account details to peer Regions + * @param userName + * @param password + * @param firstName + * @param lastName + * @param email + * @param timezone + * @param accountName + * @param accountType + * @param domainId + * @param networkDomain + * @param details + * @param accountUUID + * @param userUUID + * @return + */ + public boolean propagateAddAccount(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); + + /** + * Returns the Id of local Region + * @return + */ + public int getId(); + + /** + * Propagates User details to peer Regions + * @param userName + * @param password + * @param firstName + * @param lastName + * @param email + * @param timeZone + * @param accountName + * @param domainUUId + * @param userUUID + */ + public void propagateAddUser(String userName, String password, + String firstName, String lastName, String email, String timeZone, + String accountName, String domainUUId, String userUUID); + + /** + * Propagates Domain details to peer Regions + * @param name + * @param parentId + * @param networkDomain + * @param uuid + */ + public void propagateAddDomain(String name, Long parentId, String networkDomain, String uuid); + + + /** + * Adds a peer Region to the local Region + * @param id + * @param name + * @param endPoint + * @param apiKey + * @param secretKey + * @return Returns added Region object + */ + Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey); + + /** + * Update details of the Region with specified Id + * @param id + * @param name + * @param endPoint + * + * @param apiKey + * @param secretKey + * @return Returns update Region object + */ + Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey); + + /** + * @param id + * @return True if region is successfully removed + */ + boolean removeRegion(int id); + + /** List all Regions or by Id/Name + * @param id + * @param name + * @return List of Regions + */ + List listRegions(Integer id, String name); + + /** + * Deletes a user by userId and propagates the change to peer Regions + * + * @param accountId + * - id of the account do delete + * + * @return true if delete was successful, false otherwise + */ + boolean deleteUserAccount(long accountId); + + /** + * Updates an account + * isPopagate falg is set to true if sent from peer Region + * + * @param cmd + * - the parameter containing accountId or account nameand domainId + * @return updated account object + */ + Account updateAccount(UpdateAccountCmd cmd); + + /** + * Disables an account by accountName and domainId or accountId + * @param accountName + * @param domainId + * @param id + * @param lockRequested + * @return + * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + */ + Account disableAccount(String accountName, Long domainId, Long id, Boolean lockRequested) throws ConcurrentOperationException, ResourceUnavailableException; + + /** + * Enables an account by accountId + * + * @param accountName + * - the enableAccount command defining the accountId to be deleted. + * @param domainId + * TODO + * @param accountId + * @return account object + */ + Account enableAccount(String accountName, Long domainId, Long accountId); + + /** + * Deletes user by Id + * @param deleteUserCmd + * @return + */ + boolean deleteUser(DeleteUserCmd deleteUserCmd); + + /** + * update an existing domain + * + * @param cmd + * - the command containing domainId and new domainName + * @return Domain object if the command succeeded + */ + Domain updateDomain(UpdateDomainCmd updateDomainCmd); + + /** + * Deletes domain by Id + * @param id + * @param cleanup + * @return true if delete was successful, false otherwise + */ + boolean deleteDomain(Long id, Boolean cleanup); + + /** + * Update a user by userId + * + * @param userId + * @return UserAccount object + */ + UserAccount updateUser(UpdateUserCmd updateUserCmd); + + /** + * Disables a user by userId + * + * @param userId + * - the userId + * @return UserAccount object + */ + UserAccount disableUser(Long id); + + /** + * Enables a user + * + * @param userId + * - the userId + * @return UserAccount object + */ + UserAccount enableUser(long userId); +} diff --git a/server/src/com/cloud/region/RegionManagerImpl.java b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java similarity index 91% rename from server/src/com/cloud/region/RegionManagerImpl.java rename to server/src/org/apache/cloudstack/region/RegionManagerImpl.java index 988231eddf5..d93ab102d78 100755 --- a/server/src/com/cloud/region/RegionManagerImpl.java +++ b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import java.util.ArrayList; import java.util.List; @@ -28,7 +28,8 @@ import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; -import org.apache.cloudstack.api.command.user.region.ListRegionsCmd; +import org.apache.cloudstack.region.dao.RegionDao; +import org.apache.cloudstack.region.dao.RegionSyncDao; import org.apache.commons.httpclient.NameValuePair; import org.apache.log4j.Logger; @@ -38,8 +39,6 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.region.dao.RegionDao; -import com.cloud.region.dao.RegionSyncDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -54,8 +53,8 @@ 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{ +@Local(value = { RegionManager.class }) +public class RegionManagerImpl implements RegionManager, Manager{ public static final Logger s_logger = Logger.getLogger(RegionManagerImpl.class); @Inject @@ -102,16 +101,163 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ return _name; } + public int getId() { + return _id; + } + + /* + * Propagates Account creation to peer Regions + * Adds an entry in region_sync table on failure + */ @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"); + public boolean propagateAddAccount(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)); + //ToDo: 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(); + for (Region region : regions){ + if(region.getId() == getId()){ + continue; + } + s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); + if (RegionsApiUtil.makeAPICall(region, command, params)) { + s_logger.debug("Successfully added account :"+accountName+" to Region: "+region.getId()); + } else { + // api call failed. Add entry in region_sync table + addRegionSyncItem(region.getId(), command, params); + s_logger.error("Error while Adding account :"+accountName+" to Region: "+region.getId()); + } + } + return true; + } + + /* + * Propagates User creation to peer Regions + * Adds an entry in region_sync table on failure + */ + @Override + public void propagateAddUser(String userName, String password, + String firstName, String lastName, String email, String timezone, + String accountName, String domainUUId, String userUUID) { + + 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){ + if(region.getId() == getId()){ + continue; + } + s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); + if (RegionsApiUtil.makeAPICall(region, command, params)) { + s_logger.debug("Successfully added user :"+userName+" to Region: "+region.getId()); + } else { + // api call failed. Add entry in region_sync table + addRegionSyncItem(region.getId(), command, params); + s_logger.error("Error while Adding user :"+userName+" to Region: "+region.getId()); + } + } + return; + } + + /* + * Propagates Domain creation details to peer Regions + * Adds an entry in region_sync table on failure + */ + @Override + public void propagateAddDomain(String name, Long parentId, String networkDomain, String uuid) { + + 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){ + params.add(new NameValuePair(ApiConstants.PARENT_DOMAIN_ID, domain.getUuid())); + } + } + 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){ + if(region.getId() == getId()){ + continue; + } + s_logger.debug("Adding domain :"+name+" to Region: "+region.getId()); + if (RegionsApiUtil.makeAPICall(region, command, params)) { + s_logger.debug("Successfully added domain :"+name+" to Region: "+region.getId()); + } else { + // api call failed. Add entry in region_sync table + addRegionSyncItem(region.getId(), command, params); + s_logger.error("Error while Adding domain :"+name+" to Region: "+region.getId()); + } + } + return; + } + + /** + * Adds an entry to region_sync table + * Entry contains region Id along with failed api + * @param regionId + * @param command + * @param params + */ + private void addRegionSyncItem(int regionId, String command, List params){ + String api = RegionsApiUtil.buildParams(command, params); + RegionSyncVO sync = new RegionSyncVO(regionId, api); + if(_regionSyncDao.persist(sync) == null){ + s_logger.error("Failed to add Region Sync Item. RegionId: "+regionId + "API command: "+api); } } + /** + * {@inheritDoc} + */ + @Override + public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey) { + //Region Id should be unique + if( _regionDao.findById(id) != null ){ + throw new InvalidParameterValueException("Region with id: "+id+" already exists"); + } + //Region Name should be unique + if( _regionDao.findByName(name) != null ){ + throw new InvalidParameterValueException("Region with name: "+name+" already exists"); + } + RegionVO region = new RegionVO(id, name, endPoint, apiKey, secretKey); + return _regionDao.persist(region); + } + + /** + * {@inheritDoc} + */ @Override public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey) { RegionVO region = _regionDao.findById(id); @@ -120,6 +266,14 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ throw new InvalidParameterValueException("Region with id: "+id+" does not exist"); } + //Ensure region name is unique + if(name != null){ + RegionVO region1 = _regionDao.findByName(name); + if(region1 != null && id != region1.getId()){ + throw new InvalidParameterValueException("Region with name: "+name+" already exists"); + } + } + if(name != null){ region.setName(name); } @@ -140,76 +294,34 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ return _regionDao.findById(id); } + /** + * {@inheritDoc} + */ @Override public boolean removeRegion(int id) { RegionVO region = _regionDao.findById(id); - if(region != null){ - return _regionDao.remove(id); - } else { + if(region == null){ throw new InvalidParameterValueException("Failed to delete Region: " + id + ", Region not found"); - } + } + return _regionDao.remove(id); } + /** + * {@inheritDoc} + */ @Override - public List listRegions(ListRegionsCmd cmd) { - if(cmd.getId() != null){ - List regions = new ArrayList(); - regions.add(_regionDao.findById(cmd.getId())); - return regions; - } - return _regionDao.listAll(); - } - - public int getId() { - return _id; - } - - public void setId(int _id) { - this._id = _id; - } - - @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(); - for (Region region : regions){ - if(region.getId() == getId()){ - continue; - } - s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); - if (RegionsApiUtil.makeAPICall(region, command, params)) { - s_logger.debug("Successfully added account :"+accountName+" to Region: "+region.getId()); - } else { - addRegionSyncItem(region.getId(), command, params); - s_logger.error("Error while Adding account :"+accountName+" to Region: "+region.getId()); - } - } - return true; + public List listRegions(Integer id, String name) { + return _regionDao.listByNameAndId(id, name); } + /** + * {@inheritDoc} + */ @Override public boolean deleteUserAccount(long accountId) { AccountVO account = _accountDao.findById(accountId); if(account == null){ - return false; + throw new InvalidParameterValueException("The specified account does not exist in the system"); } String accountUUID = account.getUuid(); int regionId = account.getRegionId(); @@ -248,7 +360,10 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } } - + + /** + * {@inheritDoc} + */ @Override public Account updateAccount(UpdateAccountCmd cmd) { Long accountId = cmd.getId(); @@ -258,7 +373,7 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ String newAccountName = cmd.getNewName(); String networkDomain = cmd.getNetworkDomain(); //ToDo send details - Map details = cmd.getDetails(); + Map details = cmd.getDetails(); Account account = null; if (accountId != null) { @@ -266,13 +381,13 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } else { account = _accountDao.findEnabledAccount(accountName, domainId); } - + // Check if account exists if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { s_logger.error("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); - } - + } + String command = "updateAccount"; List params = new ArrayList(); params.add(new NameValuePair(ApiConstants.NEW_NAME, newAccountName)); @@ -319,6 +434,9 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } + /** + * {@inheritDoc} + */ @Override public Account disableAccount(String accountName, Long domainId, Long accountId, Boolean lockRequested) throws ConcurrentOperationException, ResourceUnavailableException { Account account = null; @@ -330,7 +448,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); - } + } + String accountUUID = account.getUuid(); String command = "disableAccount"; @@ -378,6 +497,9 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } + /** + * {@inheritDoc} + */ @Override public Account enableAccount(String accountName, Long domainId, Long accountId) { // Check if account exists @@ -390,7 +512,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); - } + } + String accountUUID = account.getUuid(); String command = "enableAccount"; @@ -434,6 +557,9 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } + /** + * {@inheritDoc} + */ @Override public boolean deleteUser(DeleteUserCmd cmd) { long id = cmd.getId(); @@ -442,8 +568,8 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ if (user == null) { throw new InvalidParameterValueException("The specified user doesn't exist in the system"); - } - + } + String userUUID = user.getUuid(); int regionId = user.getRegionId(); @@ -482,13 +608,68 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } + /** + * {@inheritDoc} + */ @Override - public boolean deleteDomain(Long id, Boolean cleanup) { - + public Domain updateDomain(UpdateDomainCmd cmd) { + long id = cmd.getId(); DomainVO domain = _domainDao.findById(id); if(domain == null){ throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); + } + + String domainUUID = domain.getUuid(); + + 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 = _domainMgr.updateDomain(cmd); + if(updatedDomain != null){ + List regions = _regionDao.listAll(); + for (Region region : regions){ + if(region.getId() == getId()){ + continue; + } + 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()); + } + } + } + return updatedDomain; + } else { + //First update in the Region where domain was created + Region region = _regionDao.findById(regionId); + 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 (DomainVO)updatedDomain; + } else { + throw new CloudRuntimeException("Error while updating user :"+domainUUID+" in source Region: "+region.getId()); + } } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean deleteDomain(Long id, Boolean cleanup) { + DomainVO domain = _domainDao.findById(id); + if(domain == null){ + throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); + } + String domainUUID = domain.getUuid(); String command = "deleteDomain"; @@ -528,15 +709,18 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } + /** + * {@inheritDoc} + */ @Override - public UserAccount updateUser(UpdateUserCmd cmd){ + public UserAccount updateUser(UpdateUserCmd cmd) { long id = cmd.getId(); UserVO user = _userDao.findById(id); - if (user == null) { throw new InvalidParameterValueException("The specified user doesn't exist in the system"); - } + } + String userUUID = user.getUuid(); String command = "updateUser"; @@ -582,60 +766,16 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } - @Override - public Domain updateDomain(UpdateDomainCmd cmd) { - long id = cmd.getId(); - DomainVO domain = _domainDao.findById(id); - if(domain == null){ - throw new InvalidParameterValueException("The specified domain doesn't exist in the system"); - } - String domainUUID = domain.getUuid(); - - 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 = _domainMgr.updateDomain(cmd); - if(updatedDomain != null){ - List regions = _regionDao.listAll(); - for (Region region : regions){ - if(region.getId() == getId()){ - continue; - } - 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()); - } - } - } - return updatedDomain; - } else { - //First update in the Region where domain was created - Region region = _regionDao.findById(regionId); - 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 (DomainVO)updatedDomain; - } else { - throw new CloudRuntimeException("Error while updating user :"+domainUUID+" in source Region: "+region.getId()); - } - } - } - + /** + * {@inheritDoc} + */ @Override public UserAccount disableUser(Long userId) { UserVO user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); - } + } + int regionId = user.getRegionId(); String command = "disableUser"; @@ -672,12 +812,16 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } + /** + * {@inheritDoc} + */ @Override - public UserAccount enableUser(Long userId) { + public UserAccount enableUser(long userId) { UserVO user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); - } + } + int regionId = user.getRegionId(); String command = "enableUser"; @@ -714,78 +858,4 @@ public class RegionManagerImpl implements RegionManager, RegionService, Manager{ } } - @Override - public void propogateAddUser(String userName, String password, - String firstName, String lastName, String email, String timezone, - String accountName, String domainUUId, String userUUID) { - - 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){ - if(region.getId() == getId()){ - continue; - } - s_logger.debug("Adding account :"+accountName+" to Region: "+region.getId()); - if (RegionsApiUtil.makeAPICall(region, command, params)) { - s_logger.debug("Successfully added user :"+userName+" to Region: "+region.getId()); - } else { - addRegionSyncItem(region.getId(), command, params); - s_logger.error("Error while Adding user :"+userName+" to Region: "+region.getId()); - } - } - return; - } - - @Override - public void propogateAddDomain(String name, Long parentId, String networkDomain, String uuid) { - - 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){ - params.add(new NameValuePair(ApiConstants.PARENT_DOMAIN_ID, domain.getUuid())); - } - } - 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){ - if(region.getId() == getId()){ - continue; - } - s_logger.debug("Adding domain :"+name+" to Region: "+region.getId()); - if (RegionsApiUtil.makeAPICall(region, command, params)) { - s_logger.debug("Successfully added domain :"+name+" to Region: "+region.getId()); - } else { - addRegionSyncItem(region.getId(), command, params); - s_logger.error("Error while Adding domain :"+name+" to Region: "+region.getId()); - } - } - return; - } - - private void addRegionSyncItem(int regionId, String command, List params){ - String api = RegionsApiUtil.buildParams(command, params); - RegionSyncVO sync = new RegionSyncVO(regionId, api); - if(_regionSyncDao.persist(sync) == null){ - s_logger.error("Failed to add Region Sync Item. RegionId: "+regionId + "API command: "+api); - } - } - } diff --git a/server/src/org/apache/cloudstack/region/RegionServiceImpl.java b/server/src/org/apache/cloudstack/region/RegionServiceImpl.java new file mode 100755 index 00000000000..db592adff82 --- /dev/null +++ b/server/src/org/apache/cloudstack/region/RegionServiceImpl.java @@ -0,0 +1,299 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.region; + +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.api.command.admin.account.DeleteAccountCmd; +import org.apache.cloudstack.api.command.admin.account.DisableAccountCmd; +import org.apache.cloudstack.api.command.admin.account.EnableAccountCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.domain.DeleteDomainCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.DisableUserCmd; +import org.apache.cloudstack.api.command.admin.user.EnableUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.api.command.user.region.ListRegionsCmd; +import org.apache.cloudstack.region.dao.RegionDao; +import org.apache.log4j.Logger; + +import com.cloud.domain.Domain; +import com.cloud.domain.dao.DomainDao; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.DomainManager; +import com.cloud.user.UserAccount; +import com.cloud.user.UserContext; +import com.cloud.user.dao.AccountDao; +import com.cloud.user.dao.UserDao; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.Manager; + +@Local(value = { RegionService.class }) +public class RegionServiceImpl implements RegionService, Manager { + public static final Logger s_logger = Logger.getLogger(RegionServiceImpl.class); + + @Inject + private RegionDao _regionDao; + @Inject + private AccountDao _accountDao; + @Inject + private UserDao _userDao; + @Inject + private DomainDao _domainDao; + @Inject + private RegionManager _regionMgr; + @Inject + private AccountManager _accountMgr; + @Inject + private DomainManager _domainMgr; + + private String _name; + + @Override + public boolean configure(final String name, final Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public Region addRegion(int id, String name, String endPoint, String apiKey, String secretKey) { + //Check for valid Name + //Check valid end_point url + return _regionMgr.addRegion(id, name, endPoint, apiKey, secretKey); + } + + /** + * {@inheritDoc} + */ + @Override + public Region updateRegion(int id, String name, String endPoint, String apiKey, String secretKey) { + //Check for valid Name + //Check valid end_point url + return _regionMgr.updateRegion(id, name, endPoint, apiKey, secretKey); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean removeRegion(int id) { + return _regionMgr.removeRegion(id); + } + + /** + * {@inheritDoc} + */ + @Override + public List listRegions(ListRegionsCmd cmd) { + return _regionMgr.listRegions(cmd.getId(), cmd.getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean deleteUserAccount(DeleteAccountCmd cmd) { + boolean result = false; + if(checkIsPropagate(cmd.getIsPropagate())){ + result = _accountMgr.deleteUserAccount(cmd.getId()); + } else { + result = _regionMgr.deleteUserAccount(cmd.getId()); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public Account updateAccount(UpdateAccountCmd cmd) { + Account result = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + result = _accountMgr.updateAccount(cmd); + } else { + result = _regionMgr.updateAccount(cmd); + } + + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public Account disableAccount(DisableAccountCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException { + Account result = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + if(cmd.getLockRequested()) + result = _accountMgr.lockAccount(cmd.getAccountName(), cmd.getDomainId(), cmd.getId()); + else + result = _accountMgr.disableAccount(cmd.getAccountName(), cmd.getDomainId(), cmd.getId()); + } else { + result = _regionMgr.disableAccount(cmd.getAccountName(), cmd.getDomainId(), cmd.getId(), cmd.getLockRequested()); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public Account enableAccount(EnableAccountCmd cmd) { + Account result = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + result = _accountMgr.enableAccount(cmd.getAccountName(), cmd.getDomainId(), cmd.getId()); + } else { + result = _regionMgr.enableAccount(cmd.getAccountName(), cmd.getDomainId(), cmd.getId()); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean deleteUser(DeleteUserCmd cmd) { + boolean result = false; + if(checkIsPropagate(cmd.getIsPropagate())){ + result = _accountMgr.deleteUser(cmd); + } else { + result = _regionMgr.deleteUser(cmd); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public Domain updateDomain(UpdateDomainCmd cmd) { + Domain domain = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + domain = _domainMgr.updateDomain(cmd); + } else { + domain = _regionMgr.updateDomain(cmd); + } + return domain; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean deleteDomain(DeleteDomainCmd cmd) { + boolean result = false; + if(checkIsPropagate(cmd.getIsPropagate())){ + result = _domainMgr.deleteDomain(cmd.getId(), cmd.getCleanup()); + } else { + result = _regionMgr.deleteDomain(cmd.getId(), cmd.getCleanup()); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public UserAccount updateUser(UpdateUserCmd cmd){ + UserAccount user = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + user = _accountMgr.updateUser(cmd); + } else { + user = _regionMgr.updateUser(cmd); + } + return user; + } + + /** + * {@inheritDoc} + */ + @Override + public UserAccount disableUser(DisableUserCmd cmd) { + UserAccount user = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + user = _accountMgr.disableUser(cmd.getId()); + } else { + user = _regionMgr.disableUser(cmd.getId()); + } + return user; + } + + /** + * {@inheritDoc} + */ + @Override + public UserAccount enableUser(EnableUserCmd cmd) { + UserAccount user = null; + if(checkIsPropagate(cmd.getIsPropagate())){ + user = _accountMgr.enableUser(cmd.getId()); + } else { + user = _regionMgr.enableUser(cmd.getId()); + } + return user; + } + + private boolean isRootAdmin(short accountType) { + return (accountType == Account.ACCOUNT_TYPE_ADMIN); + } + + /** + * Check isPopagate flag, Only ROOT Admin can use this param + * @param isPopagate + * @return + */ + private boolean checkIsPropagate(Boolean isPopagate){ + if(isPopagate == null || !isPopagate){ + return false; + } + // Only Admin can use isPopagate flag + UserContext ctx = UserContext.current(); + Account caller = ctx.getCaller(); + if(!isRootAdmin(caller.getType())){ + throw new PermissionDeniedException("isPropagate param cannot be used by non ROOT Admin"); + } + return true; + } + +} diff --git a/server/src/com/cloud/region/RegionSyncVO.java b/server/src/org/apache/cloudstack/region/RegionSyncVO.java similarity index 98% rename from server/src/com/cloud/region/RegionSyncVO.java rename to server/src/org/apache/cloudstack/region/RegionSyncVO.java index fc3f4239672..271f8e3a987 100644 --- a/server/src/com/cloud/region/RegionSyncVO.java +++ b/server/src/org/apache/cloudstack/region/RegionSyncVO.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import java.util.Date; diff --git a/server/src/com/cloud/region/RegionUser.java b/server/src/org/apache/cloudstack/region/RegionUser.java similarity index 97% rename from server/src/com/cloud/region/RegionUser.java rename to server/src/org/apache/cloudstack/region/RegionUser.java index 878655837cb..298638e4811 100644 --- a/server/src/com/cloud/region/RegionUser.java +++ b/server/src/org/apache/cloudstack/region/RegionUser.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import com.cloud.user.UserVO; diff --git a/server/src/com/cloud/region/RegionVO.java b/server/src/org/apache/cloudstack/region/RegionVO.java similarity index 98% rename from server/src/com/cloud/region/RegionVO.java rename to server/src/org/apache/cloudstack/region/RegionVO.java index a168f395aa6..0c36db2caff 100644 --- a/server/src/com/cloud/region/RegionVO.java +++ b/server/src/org/apache/cloudstack/region/RegionVO.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/server/src/com/cloud/region/RegionsApiUtil.java b/server/src/org/apache/cloudstack/region/RegionsApiUtil.java similarity index 87% rename from server/src/com/cloud/region/RegionsApiUtil.java rename to server/src/org/apache/cloudstack/region/RegionsApiUtil.java index a7c71379794..c7625db5534 100644 --- a/server/src/com/cloud/region/RegionsApiUtil.java +++ b/server/src/org/apache/cloudstack/region/RegionsApiUtil.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region; +package org.apache.cloudstack.region; import java.io.IOException; import java.io.InputStream; @@ -44,9 +44,20 @@ import com.cloud.user.UserAccountVO; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; +/** + * Utility class for making API calls between peer Regions + * + */ public class RegionsApiUtil { public static final Logger s_logger = Logger.getLogger(RegionsApiUtil.class); + /** + * Makes an api call using region service end_point, api command and params + * @param region + * @param command + * @param params + * @return True, if api is successful + */ protected static boolean makeAPICall(Region region, String command, List params){ try { String apiParams = buildParams(command, params); @@ -67,6 +78,14 @@ public class RegionsApiUtil { } } + /** + * Makes an api call using region service end_point, api command and params + * Returns Account object on success + * @param region + * @param command + * @param params + * @return + */ protected static RegionAccount makeAccountAPICall(Region region, String command, List params){ try { String url = buildUrl(buildParams(command, params), region); @@ -74,6 +93,7 @@ public class RegionsApiUtil { HttpMethod method = new GetMethod(url); if( client.executeMethod(method) == 200){ InputStream is = method.getResponseBodyAsStream(); + //Translate response to Account object XStream xstream = new XStream(new DomDriver()); xstream.alias("account", RegionAccount.class); xstream.alias("user", RegionUser.class); @@ -101,6 +121,14 @@ public class RegionsApiUtil { } } + /** + * Makes an api call using region service end_point, api command and params + * Returns Domain object on success + * @param region + * @param command + * @param params + * @return + */ protected static RegionDomain makeDomainAPICall(Region region, String command, List params){ try { String url = buildUrl(buildParams(command, params), region); @@ -109,6 +137,7 @@ public class RegionsApiUtil { if( client.executeMethod(method) == 200){ InputStream is = method.getResponseBodyAsStream(); XStream xstream = new XStream(new DomDriver()); + //Translate response to Domain object xstream.alias("domain", RegionDomain.class); xstream.aliasField("id", RegionDomain.class, "uuid"); xstream.aliasField("parentdomainid", RegionDomain.class, "parentUuid"); @@ -130,6 +159,14 @@ public class RegionsApiUtil { } } + /** + * Makes an api call using region service end_point, api command and params + * Returns UserAccount object on success + * @param region + * @param command + * @param params + * @return + */ protected static UserAccount makeUserAccountAPICall(Region region, String command, List params){ try { String url = buildUrl(buildParams(command, params), region); @@ -157,6 +194,12 @@ public class RegionsApiUtil { } } + /** + * Builds parameters string with command and encoded param values + * @param command + * @param params + * @return + */ protected static String buildParams(String command, List params) { StringBuffer paramString = new StringBuffer("command="+command); Iterator iter = params.iterator(); @@ -175,6 +218,13 @@ public class RegionsApiUtil { return paramString.toString(); } + /** + * Build URL for api call using region end_point + * Parameters are sorted and signed using secret_key + * @param apiParams + * @param region + * @return + */ private static String buildUrl(String apiParams, Region region) { String apiKey = region.getApiKey(); diff --git a/server/src/com/cloud/region/dao/RegionDao.java b/server/src/org/apache/cloudstack/region/dao/RegionDao.java similarity index 81% rename from server/src/com/cloud/region/dao/RegionDao.java rename to server/src/org/apache/cloudstack/region/dao/RegionDao.java index e334ef8f6eb..1360eac5cd0 100644 --- a/server/src/com/cloud/region/dao/RegionDao.java +++ b/server/src/org/apache/cloudstack/region/dao/RegionDao.java @@ -14,10 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region.dao; +package org.apache.cloudstack.region.dao; + +import java.util.List; + +import org.apache.cloudstack.region.RegionVO; -import com.cloud.region.RegionVO; import com.cloud.utils.db.GenericDao; public interface RegionDao extends GenericDao { + + RegionVO findByName(String name); + + List listByNameAndId(Integer id, String name); } diff --git a/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java b/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java new file mode 100644 index 00000000000..feb6e624244 --- /dev/null +++ b/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.region.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.cloudstack.region.RegionVO; +import org.apache.log4j.Logger; + +import com.cloud.user.UserVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={RegionDao.class}) +public class RegionDaoImpl extends GenericDaoBase implements RegionDao { + private static final Logger s_logger = Logger.getLogger(RegionDaoImpl.class); + protected SearchBuilder NameSearch; + protected SearchBuilder AllFieldsSearch; + + public RegionDaoImpl(){ + NameSearch = createSearchBuilder(); + NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); + NameSearch.done(); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("name", AllFieldsSearch.entity().getName(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public RegionVO findByName(String name) { + SearchCriteria sc = NameSearch.create(); + sc.setParameters("name", NameSearch); + return findOneBy(sc); + } + + @Override + public List listByNameAndId(Integer id, String name) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("id", id); + sc.setParameters("name", name); + return listBy(sc); + } +} diff --git a/server/src/com/cloud/region/dao/RegionSyncDao.java b/server/src/org/apache/cloudstack/region/dao/RegionSyncDao.java similarity index 90% rename from server/src/com/cloud/region/dao/RegionSyncDao.java rename to server/src/org/apache/cloudstack/region/dao/RegionSyncDao.java index 5387d2ea0e2..df287e51e32 100644 --- a/server/src/com/cloud/region/dao/RegionSyncDao.java +++ b/server/src/org/apache/cloudstack/region/dao/RegionSyncDao.java @@ -14,9 +14,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region.dao; +package org.apache.cloudstack.region.dao; + +import org.apache.cloudstack.region.RegionSyncVO; -import com.cloud.region.RegionSyncVO; import com.cloud.utils.db.GenericDao; public interface RegionSyncDao extends GenericDao { diff --git a/server/src/com/cloud/region/dao/RegionSyncDaoImpl.java b/server/src/org/apache/cloudstack/region/dao/RegionSyncDaoImpl.java similarity index 92% rename from server/src/com/cloud/region/dao/RegionSyncDaoImpl.java rename to server/src/org/apache/cloudstack/region/dao/RegionSyncDaoImpl.java index 766286e45cb..a8fa33f43e1 100644 --- a/server/src/com/cloud/region/dao/RegionSyncDaoImpl.java +++ b/server/src/org/apache/cloudstack/region/dao/RegionSyncDaoImpl.java @@ -14,13 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.region.dao; +package org.apache.cloudstack.region.dao; import javax.ejb.Local; +import org.apache.cloudstack.region.RegionSyncVO; import org.apache.log4j.Logger; -import com.cloud.region.RegionSyncVO; import com.cloud.utils.db.GenericDaoBase; @Local(value={RegionSyncDao.class}) diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 9a5dc2bf7b2..d50d1fa5397 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -2259,7 +2259,7 @@ CREATE TABLE `cloud`.`netscaler_pod_ref` ( CREATE TABLE `cloud`.`region` ( `id` int unsigned NOT NULL UNIQUE, - `name` varchar(255) NOT NULL, + `name` varchar(255) NOT NULL UNIQUE, `end_point` varchar(255) NOT NULL, `api_key` varchar(255), `secret_key` varchar(255), From c17c7007f4f37616ec4a16e7b4cc39338ce2ebdc Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Thu, 31 Jan 2013 18:26:54 +0530 Subject: [PATCH 18/24] Added RegionServiceImpl to DefaultComponentLibrary --- server/src/com/cloud/configuration/DefaultComponentLibrary.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 61e79a6821f..276afa38f75 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import org.apache.cloudstack.region.RegionManagerImpl; +import org.apache.cloudstack.region.RegionServiceImpl; import org.apache.cloudstack.region.dao.RegionDaoImpl; import org.apache.cloudstack.region.dao.RegionSyncDaoImpl; @@ -462,6 +463,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addManager("StorageNetworkManager", StorageNetworkManagerImpl.class); addManager("ExternalLoadBalancerUsageManager", ExternalLoadBalancerUsageManagerImpl.class); addManager("HA Manager", HighAvailabilityManagerImpl.class); + addManager("Region Service", RegionServiceImpl.class); addManager("Region Manager", RegionManagerImpl.class); addManager("VPC Manager", VpcManagerImpl.class); addManager("VpcVirtualRouterManager", VpcVirtualNetworkApplianceManagerImpl.class); From e7341313e999a64f6b221453be82f1561bce082d Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Thu, 31 Jan 2013 22:28:09 +0530 Subject: [PATCH 19/24] Added unit tests --- .../command/admin/domain/DeleteDomainCmd.java | 7 +- .../api/command/test/RegionCmdTest.java | 104 ++++++++++++++++++ .../cloudstack/region/RegionManagerImpl.java | 4 +- .../cloudstack/region/RegionServiceImpl.java | 3 +- .../cloudstack/region/RegionManagerTest.java | 74 +++++++++++++ 5 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 api/test/org/apache/cloudstack/api/command/test/RegionCmdTest.java create mode 100644 server/test/org/apache/cloudstack/region/RegionManagerTest.java diff --git a/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java index b0133916041..39250fd59a0 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java @@ -44,7 +44,7 @@ public class DeleteDomainCmd extends BaseAsyncCmd { private Boolean cleanup; @Parameter(name=ApiConstants.IS_PROPAGATE, type=CommandType.BOOLEAN, description="True if command is sent from another Region") - private Boolean isPropagate; + private Boolean propagate; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -58,8 +58,8 @@ public class DeleteDomainCmd extends BaseAsyncCmd { return cleanup; } - public Boolean getIsPropagate() { - return isPropagate; + public Boolean isPropagate() { + return propagate; } ///////////////////////////////////////////////////// @@ -94,7 +94,6 @@ public class DeleteDomainCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); - boolean isPopagate = (getIsPropagate() != null ) ? getIsPropagate() : false; boolean result = _regionService.deleteDomain(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/api/test/org/apache/cloudstack/api/command/test/RegionCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/RegionCmdTest.java new file mode 100644 index 00000000000..01cd33bec80 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/RegionCmdTest.java @@ -0,0 +1,104 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.region.AddRegionCmd; +import org.apache.cloudstack.api.response.RegionResponse; +import org.apache.cloudstack.region.Region; +import org.apache.cloudstack.region.RegionService; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +public class RegionCmdTest extends TestCase { + + private AddRegionCmd addRegionCmd; + private ResponseGenerator responseGenerator; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + + addRegionCmd = new AddRegionCmd() { + + @Override + public Integer getId() { + return 2; + } + + @Override + public String getRegionName() { + return "APAC"; + } + + }; + } + + @Test + public void testCreateSuccess() { + + RegionService regionService = Mockito.mock(RegionService.class); + + Region region = Mockito.mock(Region.class); + Mockito.when( + regionService.addRegion(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(region); + + addRegionCmd._regionService = regionService; + responseGenerator = Mockito.mock(ResponseGenerator.class); + + RegionResponse regionResponse = Mockito.mock(RegionResponse.class); + + Mockito.when(responseGenerator.createRegionResponse(region)).thenReturn( + regionResponse); + + addRegionCmd._responseGenerator = responseGenerator; + addRegionCmd.execute(); + + } + + @Test + public void testCreateFailure() { + + RegionService regionService = Mockito.mock(RegionService.class); + + Region region = Mockito.mock(Region.class); + Mockito.when( + regionService.addRegion(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(null); + + addRegionCmd._regionService = regionService; + + try { + addRegionCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add Region", + exception.getDescription()); + } + + } + +} diff --git a/server/src/org/apache/cloudstack/region/RegionManagerImpl.java b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java index d93ab102d78..bef23251101 100755 --- a/server/src/org/apache/cloudstack/region/RegionManagerImpl.java +++ b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java @@ -58,9 +58,9 @@ public class RegionManagerImpl implements RegionManager, Manager{ public static final Logger s_logger = Logger.getLogger(RegionManagerImpl.class); @Inject - private RegionDao _regionDao; + RegionDao _regionDao; @Inject - private AccountDao _accountDao; + AccountDao _accountDao; @Inject private AccountManager _accountMgr; @Inject diff --git a/server/src/org/apache/cloudstack/region/RegionServiceImpl.java b/server/src/org/apache/cloudstack/region/RegionServiceImpl.java index db592adff82..f5a0a8046d2 100755 --- a/server/src/org/apache/cloudstack/region/RegionServiceImpl.java +++ b/server/src/org/apache/cloudstack/region/RegionServiceImpl.java @@ -39,7 +39,6 @@ import org.apache.log4j.Logger; import com.cloud.domain.Domain; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; @@ -224,7 +223,7 @@ public class RegionServiceImpl implements RegionService, Manager { @Override public boolean deleteDomain(DeleteDomainCmd cmd) { boolean result = false; - if(checkIsPropagate(cmd.getIsPropagate())){ + if(checkIsPropagate(cmd.isPropagate())){ result = _domainMgr.deleteDomain(cmd.getId(), cmd.getCleanup()); } else { result = _regionMgr.deleteDomain(cmd.getId(), cmd.getCleanup()); diff --git a/server/test/org/apache/cloudstack/region/RegionManagerTest.java b/server/test/org/apache/cloudstack/region/RegionManagerTest.java new file mode 100644 index 00000000000..330f0b49d22 --- /dev/null +++ b/server/test/org/apache/cloudstack/region/RegionManagerTest.java @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.cloudstack.region; + + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.admin.domain.DeleteDomainCmd; +import org.apache.cloudstack.region.dao.RegionDao; +import org.apache.log4j.Logger; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.user.dao.AccountDao; + + + +public class RegionManagerTest extends TestCase { + private static final Logger s_logger = Logger.getLogger(RegionManagerTest.class); + + @Before + @Override + protected void setUp() { + + } + + @Test + public void testUniqueName() { + RegionManagerImpl regionMgr = new RegionManagerImpl(); + RegionDao regionDao = Mockito.mock(RegionDao.class); + RegionVO region = new RegionVO(2, "APAC", "", null, null); + Mockito.when(regionDao.findByName(Mockito.anyString())).thenReturn(region); + regionMgr._regionDao = regionDao; + try { + regionMgr.addRegion(2, "APAC", "", null, null); + } catch (InvalidParameterValueException e){ + Assert.assertEquals("Region with name: APAC already exists", e.getMessage()); + } + } + + @Test + public void testUserDelete() { + RegionManagerImpl regionMgr = new RegionManagerImpl(); + AccountDao accountDao = Mockito.mock(AccountDao.class); + Mockito.when(accountDao.findById(Mockito.anyLong())).thenReturn(null); + regionMgr._accountDao = accountDao; + try { + regionMgr.deleteUserAccount(5); + } catch (InvalidParameterValueException e){ + Assert.assertEquals("The specified account does not exist in the system", e.getMessage()); + } + } + +} From a33d8f96019e6f061fecc071273e8ee4fe7a67ce Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Thu, 31 Jan 2013 23:25:29 +0530 Subject: [PATCH 20/24] Fixed listRegions serach by id, name --- .../command/user/region/ListRegionsCmd.java | 2 +- .../cloudstack/region/RegionManagerImpl.java | 17 ++++++++++++++++- .../cloudstack/region/dao/RegionDao.java | 3 --- .../cloudstack/region/dao/RegionDaoImpl.java | 18 +----------------- 4 files changed, 18 insertions(+), 22 deletions(-) diff --git a/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java index 4599a197d8b..999eeb0b9c9 100644 --- a/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java @@ -38,7 +38,7 @@ public class ListRegionsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List Region by region ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.INTEGER, description="List Region by region ID.") private Integer id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List Region by region name.") diff --git a/server/src/org/apache/cloudstack/region/RegionManagerImpl.java b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java index bef23251101..cac5a68ed13 100755 --- a/server/src/org/apache/cloudstack/region/RegionManagerImpl.java +++ b/server/src/org/apache/cloudstack/region/RegionManagerImpl.java @@ -311,7 +311,22 @@ public class RegionManagerImpl implements RegionManager, Manager{ */ @Override public List listRegions(Integer id, String name) { - return _regionDao.listByNameAndId(id, name); + List regions = new ArrayList(); + if(id != null){ + RegionVO region = _regionDao.findById(id); + if(region != null){ + regions.add(region); + } + return regions; + } + if(name != null){ + RegionVO region = _regionDao.findByName(name); + if(region != null){ + regions.add(region); + } + return regions; + } + return _regionDao.listAll(); } /** diff --git a/server/src/org/apache/cloudstack/region/dao/RegionDao.java b/server/src/org/apache/cloudstack/region/dao/RegionDao.java index 1360eac5cd0..91b51d3763e 100644 --- a/server/src/org/apache/cloudstack/region/dao/RegionDao.java +++ b/server/src/org/apache/cloudstack/region/dao/RegionDao.java @@ -16,8 +16,6 @@ // under the License. package org.apache.cloudstack.region.dao; -import java.util.List; - import org.apache.cloudstack.region.RegionVO; import com.cloud.utils.db.GenericDao; @@ -26,5 +24,4 @@ public interface RegionDao extends GenericDao { RegionVO findByName(String name); - List listByNameAndId(Integer id, String name); } diff --git a/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java b/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java index feb6e624244..40998357ab0 100644 --- a/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java +++ b/server/src/org/apache/cloudstack/region/dao/RegionDaoImpl.java @@ -16,14 +16,11 @@ // under the License. package org.apache.cloudstack.region.dao; -import java.util.List; - import javax.ejb.Local; import org.apache.cloudstack.region.RegionVO; import org.apache.log4j.Logger; -import com.cloud.user.UserVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -38,25 +35,12 @@ public class RegionDaoImpl extends GenericDaoBase implements NameSearch = createSearchBuilder(); NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); NameSearch.done(); - - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), SearchCriteria.Op.EQ); - AllFieldsSearch.and("name", AllFieldsSearch.entity().getName(), SearchCriteria.Op.EQ); - AllFieldsSearch.done(); } @Override public RegionVO findByName(String name) { SearchCriteria sc = NameSearch.create(); - sc.setParameters("name", NameSearch); + sc.setParameters("name", name); return findOneBy(sc); } - - @Override - public List listByNameAndId(Integer id, String name) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("id", id); - sc.setParameters("name", name); - return listBy(sc); - } } From e7a554fc6a23a49949c2d88d6ef680682c6f6bc4 Mon Sep 17 00:00:00 2001 From: Murali Reddy Date: Fri, 1 Feb 2013 01:30:49 +0530 Subject: [PATCH 21/24] Merging events framework branch into master. This commit will bring following changes - introduced notion of event bus with publish, subscribe, unsubscribe semantics - a plug-in can implement the EventBus abstraction to provide event bug to CloudStack - A rabbitMQ based plug-in that can interact with AMQP servers to provide message broker based event-bug - stream lines, action events, usage events, alerts publishing in to convineance classed which are also used to publish corresponding event on to event bus - introduced notion of state change event. On a state change, in the state machine corrsponding to the resource, a state change event is published on the event bug - associated a state machined with Snapshot and Network objects - Virtual Machine, Volume, Snaphost, Network object state changes wil result in a state change event --- api/src/com/cloud/event/EventCategory.java | 55 ++ api/src/com/cloud/event/EventTypes.java | 351 ++++++++++- api/src/com/cloud/network/Network.java | 56 +- api/src/com/cloud/storage/Snapshot.java | 39 +- .../api/response/SnapshotResponse.java | 12 +- client/pom.xml | 5 + core/src/com/cloud/storage/SnapshotVO.java | 26 +- framework/events/pom.xml | 47 ++ .../cloudstack/framework/events/Event.java | 94 +++ .../cloudstack/framework/events/EventBus.java | 55 ++ .../framework/events/EventBusException.java | 26 + .../framework/events/EventSubscriber.java | 30 + .../framework/events/EventTopic.java | 57 ++ framework/pom.xml | 35 ++ plugins/event-bus/rabbitmq/pom.xml | 46 ++ .../mom/rabbitmq/RabbitMQEventBus.java | 555 ++++++++++++++++++ .../network/guru/OvsGuestNetworkGuru.java | 4 +- plugins/pom.xml | 1 + pom.xml | 1 + server/pom.xml | 5 + .../src/com/cloud/alert/AlertManagerImpl.java | 64 ++ server/src/com/cloud/api/ApiDBUtils.java | 207 +------ .../src/com/cloud/api/ApiResponseHelper.java | 191 +----- server/src/com/cloud/api/ApiServer.java | 5 +- .../baremetal/BareMetalTemplateAdapter.java | 30 +- .../baremetal/BareMetalVmManagerImpl.java | 63 +- .../DefaultInterceptorLibrary.java | 8 +- .../com/cloud/event/ActionEventCallback.java | 135 ----- .../src/com/cloud/event/ActionEventUtils.java | 288 +++++++++ .../src/com/cloud/event/AlertGenerator.java | 87 +++ server/src/com/cloud/event/EventUtils.java | 102 ---- .../src/com/cloud/event/UsageEventUtils.java | 119 ++++ .../com/cloud/network/NetworkManagerImpl.java | 204 +++---- .../com/cloud/network/NetworkServiceImpl.java | 90 +-- .../cloud/network/NetworkStateListener.java | 90 +++ server/src/com/cloud/network/NetworkVO.java | 1 + .../src/com/cloud/network/dao/NetworkDao.java | 4 +- .../com/cloud/network/dao/NetworkDaoImpl.java | 32 +- .../network/firewall/FirewallManagerImpl.java | 27 +- .../guru/ExternalGuestNetworkGuru.java | 7 +- .../cloud/network/guru/GuestNetworkGuru.java | 11 +- .../lb/LoadBalancingRulesManagerImpl.java | 11 +- .../cloud/network/rules/RulesManagerImpl.java | 12 +- .../security/SecurityGroupManagerImpl.java | 78 +-- .../vpn/RemoteAccessVpnManagerImpl.java | 61 +- .../cloud/server/ManagementServerImpl.java | 9 +- .../com/cloud/storage/StorageManagerImpl.java | 187 ++---- .../com/cloud/storage/dao/SnapshotDao.java | 13 +- .../cloud/storage/dao/SnapshotDaoImpl.java | 49 +- .../storage/download/DownloadMonitorImpl.java | 76 +-- .../listener/SnapshotStateListener.java | 85 +++ .../storage/listener/VolumeStateListener.java | 85 +++ .../storage/snapshot/SnapshotManagerImpl.java | 195 +++--- .../snapshot/SnapshotSchedulerImpl.java | 6 +- .../template/HyervisorTemplateAdapter.java | 29 +- .../cloud/template/TemplateManagerImpl.java | 95 +-- .../com/cloud/user/AccountManagerImpl.java | 8 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 59 +- .../src/com/cloud/vm/UserVmStateListener.java | 88 ++- .../com/cloud/snapshot/SnapshotDaoTest.java | 9 +- .../com/cloud/vpc/dao/MockNetworkDaoImpl.java | 17 +- tools/whisker/LICENSE | 500 +++++++++++++++- tools/whisker/descriptor-for-packaging.xml | 18 + 63 files changed, 3400 insertions(+), 1555 deletions(-) create mode 100644 api/src/com/cloud/event/EventCategory.java create mode 100644 framework/events/pom.xml create mode 100644 framework/events/src/org/apache/cloudstack/framework/events/Event.java create mode 100644 framework/events/src/org/apache/cloudstack/framework/events/EventBus.java create mode 100644 framework/events/src/org/apache/cloudstack/framework/events/EventBusException.java create mode 100644 framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java create mode 100644 framework/events/src/org/apache/cloudstack/framework/events/EventTopic.java create mode 100644 framework/pom.xml create mode 100644 plugins/event-bus/rabbitmq/pom.xml create mode 100644 plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java delete mode 100644 server/src/com/cloud/event/ActionEventCallback.java create mode 100755 server/src/com/cloud/event/ActionEventUtils.java create mode 100644 server/src/com/cloud/event/AlertGenerator.java delete mode 100755 server/src/com/cloud/event/EventUtils.java create mode 100644 server/src/com/cloud/event/UsageEventUtils.java create mode 100644 server/src/com/cloud/network/NetworkStateListener.java create mode 100644 server/src/com/cloud/storage/listener/SnapshotStateListener.java create mode 100644 server/src/com/cloud/storage/listener/VolumeStateListener.java diff --git a/api/src/com/cloud/event/EventCategory.java b/api/src/com/cloud/event/EventCategory.java new file mode 100644 index 00000000000..cee6529b550 --- /dev/null +++ b/api/src/com/cloud/event/EventCategory.java @@ -0,0 +1,55 @@ +/* + * 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.event; + +import java.util.ArrayList; +import java.util.List; + +public class EventCategory { + private static List eventCategories = new ArrayList(); + private String eventCategoryName; + + public EventCategory(String categoryName) { + this.eventCategoryName = categoryName; + eventCategories.add(this); + } + + public String getName() { + return eventCategoryName; + } + + public static List listAllEventCategories() { + return eventCategories; + } + + public static EventCategory getEventCategory(String categoryName) { + for (EventCategory category : eventCategories) { + if (category.getName().equalsIgnoreCase(categoryName)) { + return category; + } + } + return null; + } + + public static final EventCategory ACTION_EVENT = new EventCategory("ActionEvent"); + public static final EventCategory ALERT_EVENT = new EventCategory("AlertEvent"); + public static final EventCategory USAGE_EVENT = new EventCategory("UsageEvent"); + public static final EventCategory RESOURCE_STATE_CHANGE_EVENT = new EventCategory("ResourceStateEvent"); +} diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index d666c1e4130..0dd97cb438c 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -16,7 +16,41 @@ // under the License. package com.cloud.event; +import com.cloud.configuration.Configuration; +import com.cloud.dc.DataCenter; +import com.cloud.dc.Pod; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.dc.Vlan; +import com.cloud.domain.Domain; +import com.cloud.host.Host; +import com.cloud.network.*; +import com.cloud.network.as.*; +import com.cloud.network.router.VirtualRouter; +import com.cloud.network.rules.LoadBalancer; +import com.cloud.network.rules.StaticNat; +import com.cloud.network.security.SecurityGroup; +import com.cloud.network.vpc.PrivateGateway; +import com.cloud.network.vpc.StaticRoute; +import com.cloud.network.vpc.Vpc; +import com.cloud.offering.DiskOffering; +import com.cloud.offering.NetworkOffering; +import com.cloud.offering.ServiceOffering; +import com.cloud.projects.Project; +import com.cloud.storage.Snapshot; +import com.cloud.storage.Volume; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.vm.VirtualMachine; + +import java.util.HashMap; +import java.util.Map; + public class EventTypes { + + //map of Event and corresponding entity for which Event is applicable + private static Map entityEventDetails = null; + // VM Events public static final String EVENT_VM_CREATE = "VM.CREATE"; public static final String EVENT_VM_DESTROY = "VM.DESTROY"; @@ -319,10 +353,323 @@ public class EventTypes { public static final String EVENT_AUTOSCALEVMGROUP_UPDATE = "AUTOSCALEVMGROUP.UPDATE"; public static final String EVENT_AUTOSCALEVMGROUP_ENABLE = "AUTOSCALEVMGROUP.ENABLE"; public static final String EVENT_AUTOSCALEVMGROUP_DISABLE = "AUTOSCALEVMGROUP.DISABLE"; - + + public static final String EVENT_BAREMETAL_DHCP_SERVER_ADD = "PHYSICAL.DHCP.ADD"; public static final String EVENT_BAREMETAL_DHCP_SERVER_DELETE = "PHYSICAL.DHCP.DELETE"; - public static final String EVENT_BAREMETAL_PXE_SERVER_ADD = "PHYSICAL.PXE.ADD"; public static final String EVENT_BAREMETAL_PXE_SERVER_DELETE = "PHYSICAL.PXE.DELETE"; + + static { + + // TODO: need a way to force author adding event types to declare the entity details as well, with out braking + // current ActionEvent annotation semantics + + entityEventDetails = new HashMap(); + + entityEventDetails.put(EVENT_VM_CREATE, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_DESTROY, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_START, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_STOP, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_REBOOT, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_UPDATE, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_UPGRADE, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_RESETPASSWORD, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_MIGRATE, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_MOVE, VirtualMachine.class.getName()); + entityEventDetails.put(EVENT_VM_RESTORE, VirtualMachine.class.getName()); + + entityEventDetails.put(EVENT_ROUTER_CREATE, VirtualRouter.class.getName()); + entityEventDetails.put(EVENT_ROUTER_DESTROY, VirtualRouter.class.getName()); + entityEventDetails.put(EVENT_ROUTER_START, VirtualRouter.class.getName()); + entityEventDetails.put(EVENT_ROUTER_STOP, VirtualRouter.class.getName()); + entityEventDetails.put(EVENT_ROUTER_REBOOT, VirtualRouter.class.getName()); + entityEventDetails.put(EVENT_ROUTER_HA, VirtualRouter.class.getName()); + entityEventDetails.put(EVENT_ROUTER_UPGRADE, VirtualRouter.class.getName()); + + entityEventDetails.put(EVENT_PROXY_CREATE, "ConsoleProxy"); + entityEventDetails.put(EVENT_PROXY_DESTROY, "ConsoleProxy"); + entityEventDetails.put(EVENT_PROXY_START, "ConsoleProxy"); + entityEventDetails.put(EVENT_PROXY_STOP, "ConsoleProxy"); + entityEventDetails.put(EVENT_PROXY_REBOOT, "ConsoleProxy"); + entityEventDetails.put(EVENT_ROUTER_HA, "ConsoleProxy"); + entityEventDetails.put(EVENT_PROXY_HA, "ConsoleProxy"); + + entityEventDetails.put(EVENT_VNC_CONNECT, "VNC"); + entityEventDetails.put(EVENT_VNC_DISCONNECT, "VNC"); + + // Network Events + entityEventDetails.put(EVENT_NETWORK_CREATE, Network.class.getName()); + entityEventDetails.put(EVENT_NETWORK_DELETE, Network.class.getName()); + entityEventDetails.put(EVENT_NETWORK_UPDATE, Network.class.getName()); + entityEventDetails.put(EVENT_NETWORK_RESTART, Network.class.getName()); + entityEventDetails.put(EVENT_NET_IP_ASSIGN, PublicIpAddress.class.getName()); + entityEventDetails.put(EVENT_NET_IP_RELEASE, PublicIpAddress.class.getName()); + entityEventDetails.put(EVENT_NET_RULE_ADD, Network.class.getName()); + entityEventDetails.put(EVENT_NET_RULE_DELETE, Network.class.getName()); + entityEventDetails.put(EVENT_NET_RULE_MODIFY, Network.class.getName()); + entityEventDetails.put(EVENT_FIREWALL_OPEN, Network.class.getName()); + entityEventDetails.put(EVENT_FIREWALL_CLOSE, Network.class.getName()); + + // Load Balancers + entityEventDetails.put(EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, LoadBalancer.class.getName()); + entityEventDetails.put(EVENT_REMOVE_FROM_LOAD_BALANCER_RULE, LoadBalancer.class.getName()); + entityEventDetails.put(EVENT_LOAD_BALANCER_CREATE, LoadBalancer.class.getName()); + entityEventDetails.put(EVENT_LOAD_BALANCER_DELETE, LoadBalancer.class.getName()); + entityEventDetails.put(EVENT_LB_STICKINESSPOLICY_CREATE, LoadBalancer.class.getName()); + entityEventDetails.put(EVENT_LB_STICKINESSPOLICY_DELETE, LoadBalancer.class.getName()); + entityEventDetails.put(EVENT_LOAD_BALANCER_UPDATE, LoadBalancer.class.getName()); + + // Account events + entityEventDetails.put(EVENT_ACCOUNT_DISABLE, Account.class.getName()); + entityEventDetails.put(EVENT_ACCOUNT_CREATE, Account.class.getName()); + entityEventDetails.put(EVENT_ACCOUNT_DELETE, Account.class.getName()); + entityEventDetails.put(EVENT_ACCOUNT_MARK_DEFAULT_ZONE, Account.class.getName()); + + // UserVO Events + entityEventDetails.put(EVENT_USER_LOGIN, User.class.getName()); + entityEventDetails.put(EVENT_USER_LOGOUT, User.class.getName()); + entityEventDetails.put(EVENT_USER_CREATE, User.class.getName()); + entityEventDetails.put(EVENT_USER_DELETE, User.class.getName()); + entityEventDetails.put(EVENT_USER_DISABLE, User.class.getName()); + entityEventDetails.put(EVENT_USER_UPDATE, User.class.getName()); + entityEventDetails.put(EVENT_USER_ENABLE, User.class.getName()); + entityEventDetails.put(EVENT_USER_LOCK, User.class.getName()); + + // Template Events + entityEventDetails.put(EVENT_TEMPLATE_CREATE, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_DELETE, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_UPDATE, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_DOWNLOAD_START, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_DOWNLOAD_SUCCESS, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_DOWNLOAD_FAILED, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_COPY, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_EXTRACT, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_UPLOAD, VirtualMachineTemplate.class.getName()); + entityEventDetails.put(EVENT_TEMPLATE_CLEANUP, VirtualMachineTemplate.class.getName()); + + // Volume Events + entityEventDetails.put(EVENT_VOLUME_CREATE, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_DELETE, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_ATTACH, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_DETACH, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_EXTRACT, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_UPLOAD, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_MIGRATE, Volume.class.getName()); + entityEventDetails.put(EVENT_VOLUME_RESIZE, Volume.class.getName()); + + // Domains + entityEventDetails.put(EVENT_DOMAIN_CREATE, Domain.class.getName()); + entityEventDetails.put(EVENT_DOMAIN_DELETE, Domain.class.getName()); + entityEventDetails.put(EVENT_DOMAIN_UPDATE, Domain.class.getName()); + + // Snapshots + entityEventDetails.put(EVENT_SNAPSHOT_CREATE, Snapshot.class.getName()); + entityEventDetails.put(EVENT_SNAPSHOT_DELETE, Snapshot.class.getName()); + entityEventDetails.put(EVENT_SNAPSHOT_POLICY_CREATE, Snapshot.class.getName()); + entityEventDetails.put(EVENT_SNAPSHOT_POLICY_UPDATE, Snapshot.class.getName()); + entityEventDetails.put(EVENT_SNAPSHOT_POLICY_DELETE, Snapshot.class.getName()); + + // ISO + entityEventDetails.put(EVENT_ISO_CREATE, "Iso"); + entityEventDetails.put(EVENT_ISO_DELETE, "Iso"); + entityEventDetails.put(EVENT_ISO_COPY, "Iso"); + entityEventDetails.put(EVENT_ISO_ATTACH, "Iso"); + entityEventDetails.put(EVENT_ISO_DETACH, "Iso"); + entityEventDetails.put(EVENT_ISO_EXTRACT, "Iso"); + entityEventDetails.put(EVENT_ISO_UPLOAD, "Iso"); + + // SSVM + entityEventDetails.put(EVENT_SSVM_CREATE, "SecondaryStorageVm"); + entityEventDetails.put(EVENT_SSVM_DESTROY, "SecondaryStorageVm"); + entityEventDetails.put(EVENT_SSVM_START, "SecondaryStorageVm"); + entityEventDetails.put(EVENT_SSVM_STOP, "SecondaryStorageVm"); + entityEventDetails.put(EVENT_SSVM_REBOOT, "SecondaryStorageVm"); + entityEventDetails.put(EVENT_SSVM_HA, "SecondaryStorageVm"); + + // Service Offerings + entityEventDetails.put(EVENT_SERVICE_OFFERING_CREATE, ServiceOffering.class.getName()); + entityEventDetails.put(EVENT_SERVICE_OFFERING_EDIT, ServiceOffering.class.getName()); + entityEventDetails.put(EVENT_SERVICE_OFFERING_DELETE, ServiceOffering.class.getName()); + + // Disk Offerings + entityEventDetails.put(EVENT_DISK_OFFERING_CREATE, DiskOffering.class.getName()); + entityEventDetails.put(EVENT_DISK_OFFERING_EDIT, DiskOffering.class.getName()); + entityEventDetails.put(EVENT_DISK_OFFERING_DELETE, DiskOffering.class.getName()); + + // Network offerings + entityEventDetails.put(EVENT_NETWORK_OFFERING_CREATE, NetworkOffering.class.getName()); + entityEventDetails.put(EVENT_NETWORK_OFFERING_ASSIGN, NetworkOffering.class.getName()); + entityEventDetails.put(EVENT_NETWORK_OFFERING_EDIT, NetworkOffering.class.getName()); + entityEventDetails.put(EVENT_NETWORK_OFFERING_REMOVE, NetworkOffering.class.getName()); + entityEventDetails.put(EVENT_NETWORK_OFFERING_DELETE, NetworkOffering.class.getName()); + + // Pods + entityEventDetails.put(EVENT_POD_CREATE, Pod.class.getName()); + entityEventDetails.put(EVENT_POD_EDIT, Pod.class.getName()); + entityEventDetails.put(EVENT_POD_DELETE, Pod.class.getName()); + + // Zones + entityEventDetails.put(EVENT_ZONE_CREATE, DataCenter.class.getName()); + entityEventDetails.put(EVENT_ZONE_EDIT, DataCenter.class.getName()); + entityEventDetails.put(EVENT_ZONE_DELETE, DataCenter.class.getName()); + + // VLANs/IP ranges + entityEventDetails.put(EVENT_VLAN_IP_RANGE_CREATE, Vlan.class.getName()); + entityEventDetails.put(EVENT_VLAN_IP_RANGE_DELETE,Vlan.class.getName()); + + entityEventDetails.put(EVENT_STORAGE_IP_RANGE_CREATE, StorageNetworkIpRange.class.getName()); + entityEventDetails.put(EVENT_STORAGE_IP_RANGE_DELETE, StorageNetworkIpRange.class.getName()); + entityEventDetails.put(EVENT_STORAGE_IP_RANGE_UPDATE, StorageNetworkIpRange.class.getName()); + + // Configuration Table + entityEventDetails.put(EVENT_CONFIGURATION_VALUE_EDIT, Configuration.class.getName()); + + // Security Groups + entityEventDetails.put(EVENT_SECURITY_GROUP_AUTHORIZE_INGRESS, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_REVOKE_INGRESS, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_AUTHORIZE_EGRESS, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_REVOKE_EGRESS, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_CREATE, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_DELETE, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_ASSIGN, SecurityGroup.class.getName()); + entityEventDetails.put(EVENT_SECURITY_GROUP_REMOVE, SecurityGroup.class.getName()); + + // Host + entityEventDetails.put(EVENT_HOST_RECONNECT, Host.class.getName()); + + // Maintenance + entityEventDetails.put(EVENT_MAINTENANCE_CANCEL, Host.class.getName()); + entityEventDetails.put(EVENT_MAINTENANCE_CANCEL_PRIMARY_STORAGE, Host.class.getName()); + entityEventDetails.put(EVENT_MAINTENANCE_PREPARE, Host.class.getName()); + entityEventDetails.put(EVENT_MAINTENANCE_PREPARE_PRIMARY_STORAGE, Host.class.getName()); + + // VPN + entityEventDetails.put(EVENT_REMOTE_ACCESS_VPN_CREATE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_REMOTE_ACCESS_VPN_DESTROY, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_VPN_USER_ADD, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_VPN_USER_REMOVE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_GATEWAY_CREATE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_GATEWAY_DELETE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_CUSTOMER_GATEWAY_CREATE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_CUSTOMER_GATEWAY_DELETE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_CUSTOMER_GATEWAY_UPDATE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_CONNECTION_CREATE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_CONNECTION_DELETE, RemoteAccessVpn.class.getName()); + entityEventDetails.put(EVENT_S2S_VPN_CONNECTION_RESET, RemoteAccessVpn.class.getName()); + + // Custom certificates + entityEventDetails.put(EVENT_UPLOAD_CUSTOM_CERTIFICATE, "Certificate"); + + // OneToOnenat + entityEventDetails.put(EVENT_ENABLE_STATIC_NAT, StaticNat.class.getName()); + entityEventDetails.put(EVENT_DISABLE_STATIC_NAT, StaticNat.class.getName()); + + entityEventDetails.put(EVENT_ZONE_VLAN_ASSIGN,Vlan.class.getName()); + entityEventDetails.put(EVENT_ZONE_VLAN_RELEASE,Vlan.class.getName()); + + // Projects + entityEventDetails.put(EVENT_PROJECT_CREATE, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_UPDATE, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_DELETE, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_ACTIVATE, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_SUSPEND, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_ACCOUNT_ADD, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_INVITATION_UPDATE, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_INVITATION_REMOVE, Project.class.getName()); + entityEventDetails.put(EVENT_PROJECT_ACCOUNT_REMOVE, Project.class.getName()); + + // Network as a Service + entityEventDetails.put(EVENT_NETWORK_ELEMENT_CONFIGURE,Network.class.getName()); + + // Physical Network Events + entityEventDetails.put(EVENT_PHYSICAL_NETWORK_CREATE, PhysicalNetwork.class.getName()); + entityEventDetails.put(EVENT_PHYSICAL_NETWORK_DELETE, PhysicalNetwork.class.getName()); + entityEventDetails.put(EVENT_PHYSICAL_NETWORK_UPDATE, PhysicalNetwork.class.getName()); + + // Physical Network Service Provider Events + entityEventDetails.put(EVENT_SERVICE_PROVIDER_CREATE, PhysicalNetworkServiceProvider.class.getName()); + entityEventDetails.put(EVENT_SERVICE_PROVIDER_DELETE, PhysicalNetworkServiceProvider.class.getName()); + entityEventDetails.put(EVENT_SERVICE_PROVIDER_UPDATE, PhysicalNetworkServiceProvider.class.getName()); + + // Physical Network TrafficType Events + entityEventDetails.put(EVENT_TRAFFIC_TYPE_CREATE, PhysicalNetworkTrafficType.class.getName()); + entityEventDetails.put(EVENT_TRAFFIC_TYPE_DELETE, PhysicalNetworkTrafficType.class.getName()); + entityEventDetails.put(EVENT_TRAFFIC_TYPE_UPDATE, PhysicalNetworkTrafficType.class.getName()); + + // external network device events + entityEventDetails.put(EVENT_EXTERNAL_LB_DEVICE_ADD, PhysicalNetwork.class.getName()); + entityEventDetails.put(EVENT_EXTERNAL_LB_DEVICE_DELETE, PhysicalNetwork.class.getName()); + entityEventDetails.put(EVENT_EXTERNAL_LB_DEVICE_CONFIGURE, PhysicalNetwork.class.getName()); + + // external switch management device events (E.g.: Cisco Nexus 1000v Virtual Supervisor Module. + entityEventDetails.put(EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_ADD, "Nexus1000v"); + entityEventDetails.put(EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DELETE, "Nexus1000v"); + entityEventDetails.put(EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_CONFIGURE, "Nexus1000v"); + entityEventDetails.put(EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_ENABLE, "Nexus1000v"); + entityEventDetails.put(EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DISABLE, "Nexus1000v"); + + + entityEventDetails.put(EVENT_EXTERNAL_FIREWALL_DEVICE_ADD, PhysicalNetwork.class.getName()); + entityEventDetails.put(EVENT_EXTERNAL_FIREWALL_DEVICE_DELETE, PhysicalNetwork.class.getName()); + entityEventDetails.put(EVENT_EXTERNAL_FIREWALL_DEVICE_CONFIGURE, PhysicalNetwork.class.getName()); + + // VPC + entityEventDetails.put(EVENT_VPC_CREATE, Vpc.class.getName()); + entityEventDetails.put(EVENT_VPC_UPDATE, Vpc.class.getName()); + entityEventDetails.put(EVENT_VPC_DELETE, Vpc.class.getName()); + entityEventDetails.put(EVENT_VPC_RESTART, Vpc.class.getName()); + + // VPC offerings + entityEventDetails.put(EVENT_VPC_OFFERING_CREATE, Vpc.class.getName()); + entityEventDetails.put(EVENT_VPC_OFFERING_UPDATE, Vpc.class.getName()); + entityEventDetails.put(EVENT_VPC_OFFERING_DELETE, Vpc.class.getName()); + + // Private gateway + entityEventDetails.put(EVENT_PRIVATE_GATEWAY_CREATE, PrivateGateway.class.getName()); + entityEventDetails.put(EVENT_PRIVATE_GATEWAY_DELETE, PrivateGateway.class.getName()); + + // Static routes + entityEventDetails.put(EVENT_STATIC_ROUTE_CREATE, StaticRoute.class.getName()); + entityEventDetails.put(EVENT_STATIC_ROUTE_DELETE, StaticRoute.class.getName()); + + // tag related events + entityEventDetails.put(EVENT_TAGS_CREATE, "Tag"); + entityEventDetails.put(EVENT_TAGS_DELETE, "tag"); + + // external network device events + entityEventDetails.put(EVENT_EXTERNAL_NVP_CONTROLLER_ADD, "NvpController"); + entityEventDetails.put(EVENT_EXTERNAL_NVP_CONTROLLER_DELETE, "NvpController"); + entityEventDetails.put(EVENT_EXTERNAL_NVP_CONTROLLER_CONFIGURE, "NvpController"); + + // AutoScale + entityEventDetails.put(EVENT_COUNTER_CREATE, AutoScaleCounter.class.getName()); + entityEventDetails.put(EVENT_COUNTER_DELETE, AutoScaleCounter.class.getName()); + entityEventDetails.put(EVENT_CONDITION_CREATE, Condition.class.getName()); + entityEventDetails.put(EVENT_CONDITION_DELETE, Condition.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEPOLICY_CREATE, AutoScalePolicy.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEPOLICY_UPDATE, AutoScalePolicy.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEPOLICY_DELETE, AutoScalePolicy.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMPROFILE_CREATE, AutoScaleVmProfile.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMPROFILE_DELETE, AutoScaleVmProfile.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMPROFILE_UPDATE, AutoScaleVmProfile.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_CREATE, AutoScaleVmGroup.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_DELETE, AutoScaleVmGroup.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_UPDATE, AutoScaleVmGroup.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_ENABLE, AutoScaleVmGroup.class.getName()); + entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_DISABLE, AutoScaleVmGroup.class.getName()); + } + + public static String getEntityForEvent (String eventName) { + String entityClassName = entityEventDetails.get(eventName); + if (entityClassName == null || entityClassName.isEmpty()) { + return null; + } + int index = entityClassName.lastIndexOf("."); + String entityName = entityClassName; + if (index != -1) { + entityName = entityClassName.substring(index+1); + } + return entityName; + } } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 413b6d96665..1dbb327155e 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -16,26 +16,25 @@ // under the License. package com.cloud.network; -import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; -import com.cloud.utils.fsm.FiniteState; -import com.cloud.utils.fsm.StateMachine; +import com.cloud.utils.fsm.StateMachine2; +import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; import java.net.URI; import java.util.ArrayList; import java.util.List; -import java.util.Set; /** * owned by an account. */ -public interface Network extends ControlledEntity, InternalIdentity, Identity { +public interface Network extends ControlledEntity, StateObject, InternalIdentity, Identity { - public enum GuestType { + public enum GuestType { Shared, Isolated } @@ -204,7 +203,8 @@ public interface Network extends ControlledEntity, InternalIdentity, Identity { OperationFailed; } - enum State implements FiniteState { + public enum State { + Allocated("Indicates the network configuration is in allocated but not setup"), Setup("Indicates the network configuration is setup"), Implementing("Indicates the network configuration is being implemented"), @@ -212,39 +212,8 @@ public interface Network extends ControlledEntity, InternalIdentity, Identity { Shutdown("Indicates the network configuration is being destroyed"), Destroy("Indicates that the network is destroyed"); + protected static final StateMachine2 s_fsm = new StateMachine2(); - @Override - public StateMachine getStateMachine() { - return s_fsm; - } - - @Override - public State getNextState(Event event) { - return s_fsm.getNextState(this, event); - } - - @Override - public List getFromStates(Event event) { - return s_fsm.getFromStates(this, event); - } - - @Override - public Set getPossibleEvents() { - return s_fsm.getPossibleEvents(this); - } - - String _description; - - @Override - public String getDescription() { - return _description; - } - - private State(String description) { - _description = description; - } - - private static StateMachine s_fsm = new StateMachine(); static { s_fsm.addTransition(State.Allocated, Event.ImplementNetwork, State.Implementing); s_fsm.addTransition(State.Implementing, Event.OperationSucceeded, State.Implemented); @@ -253,6 +222,15 @@ public interface Network extends ControlledEntity, InternalIdentity, Identity { s_fsm.addTransition(State.Shutdown, Event.OperationSucceeded, State.Allocated); s_fsm.addTransition(State.Shutdown, Event.OperationFailed, State.Implemented); } + + public static StateMachine2 getStateMachine() { + return s_fsm; + } + + String _description; + private State(String description) { + _description = description; + } } String getName(); diff --git a/api/src/com/cloud/storage/Snapshot.java b/api/src/com/cloud/storage/Snapshot.java index 99bdee6bea9..2e2965ae149 100644 --- a/api/src/com/cloud/storage/Snapshot.java +++ b/api/src/com/cloud/storage/Snapshot.java @@ -16,14 +16,16 @@ // under the License. package com.cloud.storage; -import java.util.Date; - -import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.utils.fsm.StateMachine2; +import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; -public interface Snapshot extends ControlledEntity, Identity, InternalIdentity { +import java.util.Date; + +public interface Snapshot extends ControlledEntity, Identity, InternalIdentity, StateObject { public enum Type { MANUAL, RECURRING, @@ -51,13 +53,29 @@ public interface Snapshot extends ControlledEntity, Identity, InternalIdentity { } } - public enum Status { + public enum State { Creating, CreatedOnPrimary, BackingUp, BackedUp, Error; + private final static StateMachine2 s_fsm = new StateMachine2(); + + public static StateMachine2 getStateMachine() { + return s_fsm; + } + + static { + s_fsm.addTransition(null, Event.CreateRequested, Creating); + s_fsm.addTransition(Creating, Event.OperationSucceeded, CreatedOnPrimary); + s_fsm.addTransition(Creating, Event.OperationNotPerformed, BackedUp); + s_fsm.addTransition(Creating, Event.OperationFailed, Error); + s_fsm.addTransition(CreatedOnPrimary, Event.BackupToSecondary, BackingUp); + s_fsm.addTransition(BackingUp, Event.OperationSucceeded, BackedUp); + s_fsm.addTransition(BackingUp, Event.OperationFailed, Error); + } + public String toString() { return this.name(); } @@ -67,6 +85,15 @@ public interface Snapshot extends ControlledEntity, Identity, InternalIdentity { } } + enum Event { + CreateRequested, + OperationNotPerformed, + BackupToSecondary, + BackedupToSecondary, + OperationSucceeded, + OperationFailed + } + public static final long MANUAL_POLICY_ID = 0L; long getAccountId(); @@ -81,7 +108,7 @@ public interface Snapshot extends ControlledEntity, Identity, InternalIdentity { Type getType(); - Status getStatus(); + State getState(); HypervisorType getHypervisorType(); diff --git a/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java index 8ea0d7fb87f..58b7cf1525f 100644 --- a/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java @@ -16,16 +16,16 @@ // under the License. package org.apache.cloudstack.api.response; -import java.util.Date; -import java.util.List; - -import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.Snapshot; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; +import java.util.Date; +import java.util.List; + @EntityReference(value=Snapshot.class) @SuppressWarnings("unused") public class SnapshotResponse extends BaseResponse implements ControlledEntityResponse { @@ -81,7 +81,7 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.STATE) @Param(description = "the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage") - private Snapshot.Status state; + private Snapshot.State state; @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with snapshot", responseObject = ResourceTagResponse.class) private List tags; @@ -149,7 +149,7 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe this.intervalType = intervalType; } - public void setState(Snapshot.Status state) { + public void setState(Snapshot.State state) { this.state = state; } diff --git a/client/pom.xml b/client/pom.xml index 7ebe50c48f9..63ec2ef6686 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -116,6 +116,11 @@ cloud-plugin-host-allocator-random ${project.version} + + org.apache.cloudstack + cloud-mom-rabbitmq + ${project.version} + mysql mysql-connector-java diff --git a/core/src/com/cloud/storage/SnapshotVO.java b/core/src/com/cloud/storage/SnapshotVO.java index e5e36504ea6..c1c5f214d77 100644 --- a/core/src/com/cloud/storage/SnapshotVO.java +++ b/core/src/com/cloud/storage/SnapshotVO.java @@ -16,23 +16,13 @@ // under the License. package com.cloud.storage; -import java.util.Date; -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; -import org.apache.cloudstack.api.InternalIdentity; + +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; @Entity @Table(name="snapshots") @@ -69,7 +59,7 @@ public class SnapshotVO implements Snapshot { @Expose @Column(name="status", updatable = true, nullable=false) @Enumerated(value=EnumType.STRING) - private Status status; + private State status; @Column(name="snapshot_type") short snapshotType; @@ -127,7 +117,7 @@ public class SnapshotVO implements Snapshot { this.snapshotType = snapshotType; this.typeDescription = typeDescription; this.size = size; - this.status = Status.Creating; + this.status = State.Creating; this.prevSnapshotId = 0; this.hypervisorType = hypervisorType; this.version = "2.2"; @@ -252,11 +242,11 @@ public class SnapshotVO implements Snapshot { } @Override - public Status getStatus() { + public State getState() { return status; } - public void setStatus(Status status) { + public void setStatus(State status) { this.status = status; } diff --git a/framework/events/pom.xml b/framework/events/pom.xml new file mode 100644 index 00000000000..ef812e5a014 --- /dev/null +++ b/framework/events/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + cloud-framework-events + Apache CloudStack Event Notification Framework + + org.apache.cloudstack + cloudstack-framework + 4.1.0-SNAPSHOT + ../pom.xml + + + + org.apache.cloudstack + cloud-utils + ${project.version} + + + com.google.code.gson + gson + ${cs.gson.version} + + + + install + src + test + + diff --git a/framework/events/src/org/apache/cloudstack/framework/events/Event.java b/framework/events/src/org/apache/cloudstack/framework/events/Event.java new file mode 100644 index 00000000000..eb6f48de3b8 --- /dev/null +++ b/framework/events/src/org/apache/cloudstack/framework/events/Event.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.framework.events; + +import com.google.gson.Gson; + +public class Event { + + String eventCategory; + String eventType; + String eventSource; + String resourceType; + String resourceUUID; + String description; + + public Event(String eventSource, String eventCategory, String eventType, String resourceType, + String resourceUUID) { + this.eventCategory = eventCategory; + this.eventType = eventType; + this.eventSource = eventSource; + this.resourceType = resourceType; + this.resourceUUID = resourceUUID; + } + + public String getEventCategory() { + return eventCategory; + } + + public void setEventCategory(String category) { + eventCategory = category; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String type) { + eventType = type; + } + + public String getEventSource() { + return eventSource; + } + + void setEventSource(String source) { + eventSource = source; + } + + public String getDescription() { + return description; + } + + public void setDescription (Object message) { + Gson gson = new Gson(); + this.description = gson.toJson(message).toString(); + } + + public void setDescription(String description) { + this.description = description; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public void setResourceUUID(String uuid) { + this.resourceUUID = uuid; + } + + public String getResourceUUID () { + return resourceUUID; + } +} \ No newline at end of file diff --git a/framework/events/src/org/apache/cloudstack/framework/events/EventBus.java b/framework/events/src/org/apache/cloudstack/framework/events/EventBus.java new file mode 100644 index 00000000000..c16ee6f96f4 --- /dev/null +++ b/framework/events/src/org/apache/cloudstack/framework/events/EventBus.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.framework.events; + +import com.cloud.utils.component.Adapter; + +import java.util.UUID; + +/** + * Interface to publish and subscribe to CloudStack events + * + */ +public interface EventBus extends Adapter{ + + /** + * publish an event on to the event bus + * + * @param event event that needs to be published on the event bus + */ + void publish(Event event) throws EventBusException; + + /** + * subscribe to events that matches specified event topics + * + * @param topic defines category and type of the events being subscribed to + * @param subscriber subscriber that intends to receive event notification + * @return UUID returns the subscription ID + */ + UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException; + + /** + * unsubscribe to events of a category and a type + * + * @param subscriber subscriber that intends to unsubscribe from the event notification + */ + void unsubscribe(UUID subscriberId, EventSubscriber subscriber) throws EventBusException; + +} diff --git a/framework/events/src/org/apache/cloudstack/framework/events/EventBusException.java b/framework/events/src/org/apache/cloudstack/framework/events/EventBusException.java new file mode 100644 index 00000000000..5654ba04804 --- /dev/null +++ b/framework/events/src/org/apache/cloudstack/framework/events/EventBusException.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.framework.events; + +public class EventBusException extends Exception{ + public EventBusException (String msg) { + super(msg); + } +} diff --git a/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java b/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java new file mode 100644 index 00000000000..b1c30c21587 --- /dev/null +++ b/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.framework.events; + +public interface EventSubscriber { + + /** + * Callback method. EventBus calls this method on occurrence of subscribed event + * + * @param event details of the event + */ + void onEvent(Event event); +} diff --git a/framework/events/src/org/apache/cloudstack/framework/events/EventTopic.java b/framework/events/src/org/apache/cloudstack/framework/events/EventTopic.java new file mode 100644 index 00000000000..19b727d4519 --- /dev/null +++ b/framework/events/src/org/apache/cloudstack/framework/events/EventTopic.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.framework.events; + +public class EventTopic { + + String eventCategory; + String eventType; + String resourceType; + String resourceUUID; + String eventSource; + + public EventTopic(String eventCategory, String eventType, String resourceType, String resourceUUID, String eventSource) { + this.eventCategory = eventCategory; + this.eventType = eventType; + this.resourceType = resourceType; + this.resourceUUID = resourceUUID; + this.eventSource = eventSource; + } + + public String getEventCategory() { + return eventCategory; + } + + public String getEventType() { + return eventType; + } + + public String getResourceType() { + return resourceType; + } + + public String getEventSource() { + return eventSource; + } + + public String getResourceUUID() { + return resourceUUID; + } +} diff --git a/framework/pom.xml b/framework/pom.xml new file mode 100644 index 00000000000..81e091605b9 --- /dev/null +++ b/framework/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + cloudstack-framework + Apache CloudStack framework POM + pom + + org.apache.cloudstack + cloudstack + 4.1.0-SNAPSHOT + + + install + + + events + + diff --git a/plugins/event-bus/rabbitmq/pom.xml b/plugins/event-bus/rabbitmq/pom.xml new file mode 100644 index 00000000000..6a47983a9b5 --- /dev/null +++ b/plugins/event-bus/rabbitmq/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + cloud-mom-rabbitmq + Apache CloudStack Plugin - RabbitMQ Event Bus + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + + + com.rabbitmq + amqp-client + 2.8.7 + + + org.apache.cloudstack + cloud-framework-events + ${project.version} + + + + install + src + + diff --git a/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java new file mode 100644 index 00000000000..3a06c42d277 --- /dev/null +++ b/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -0,0 +1,555 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.mom.rabbitmq; + +import com.rabbitmq.client.*; +import org.apache.cloudstack.framework.events.*; +import org.apache.log4j.Logger; + +import com.cloud.utils.Ternary; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.io.IOException; +import java.net.ConnectException; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@Local(value=EventBus.class) +public class RabbitMQEventBus implements EventBus { + + // details of AMQP server + private static String _amqpHost; + private static Integer _port; + private static String _username; + private static String _password; + + // AMQP exchange name where all CloudStack events will be published + private static String _amqpExchangeName; + + // hashmap to book keep the registered subscribers + private static ConcurrentHashMap> _subscribers; + + // connection to AMQP server, + private static Connection _connection=null; + + // AMQP server should consider messages acknowledged once delivered if _autoAck is true + private static boolean _autoAck = true; + + private ExecutorService executorService; + private String _name; + private static DisconnectHandler disconnectHandler; + private static Integer _retryInterval; + private static final Logger s_logger = Logger.getLogger(RabbitMQEventBus.class); + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + + _amqpHost = (String) params.get("server"); + if (_amqpHost == null || _amqpHost.isEmpty()) { + throw new ConfigurationException("Unable to get the AMQP server details"); + } + + _username = (String) params.get("username"); + if (_username == null || _username.isEmpty()) { + throw new ConfigurationException("Unable to get the username details"); + } + + _password = (String) params.get("password"); + if (_password == null || _password.isEmpty()) { + throw new ConfigurationException("Unable to get the password details"); + } + + _amqpExchangeName = (String) params.get("exchangename"); + if (_amqpExchangeName == null || _amqpExchangeName.isEmpty()) { + throw new ConfigurationException("Unable to get the _exchange details on the AMQP server"); + } + + try { + String portStr = (String) params.get("port"); + if (portStr == null || portStr.isEmpty()) { + throw new ConfigurationException("Unable to get the port details of AMQP server"); + } + _port = Integer.parseInt(portStr); + + String retryIntervalStr = (String) params.get("retryinterval"); + if (retryIntervalStr == null || retryIntervalStr.isEmpty()) { + // default to 10s to try out reconnect + retryIntervalStr = "10000"; + } + _retryInterval = Integer.parseInt(retryIntervalStr); + } catch (NumberFormatException e) { + throw new ConfigurationException("Invalid port number/retry interval"); + } + + _subscribers = new ConcurrentHashMap>(); + + executorService = Executors.newCachedThreadPool(); + disconnectHandler = new DisconnectHandler(); + _name = name; + return true; + } + + /** Call to subscribe to interested set of events + * + * @param topic defines category and type of the events being subscribed to + * @param subscriber subscriber that intends to receive event notification + * @return UUID that represents the subscription with event bus + * @throws EventBusException + */ + @Override + public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException { + + if (subscriber == null || topic == null) { + throw new EventBusException("Invalid EventSubscriber/EventTopic object passed."); + } + + // create a UUID, that will be used for managing subscriptions and also used as queue name + // for on the queue used for the subscriber on the AMQP broker + UUID queueId = UUID.randomUUID(); + String queueName = queueId.toString(); + + try { + String bindingKey = createBindingKey(topic); + + // store the subscriber details before creating channel + _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); + + // create a channel dedicated for this subscription + Connection connection = getConnection(); + Channel channel = createChannel(connection); + + // create a queue and bind it to the exchange with binding key formed from event topic + createExchange(channel, _amqpExchangeName); + channel.queueDeclare(queueName, false, false, false, null); + channel.queueBind(queueName, _amqpExchangeName, bindingKey); + + // register a callback handler to receive the events that a subscriber subscribed to + channel.basicConsume(queueName, _autoAck, queueName, + new DefaultConsumer(channel) { + @Override + public void handleDelivery(String queueName, + Envelope envelope, + AMQP.BasicProperties properties, + byte[] body) + throws IOException { + Ternary queueDetails = _subscribers.get(queueName); + if (queueDetails != null) { + EventSubscriber subscriber = queueDetails.third(); + String routingKey = envelope.getRoutingKey(); + String eventSource = getEventSourceFromRoutingKey(routingKey); + String eventCategory = getEventCategoryFromRoutingKey(routingKey); + String eventType = getEventTypeFromRoutingKey(routingKey); + String resourceType = getResourceTypeFromRoutingKey(routingKey); + String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); + Event event = new Event(eventSource, eventCategory, eventType, + resourceType, resourceUUID); + event.setDescription(new String(body)); + + // deliver the event to call back object provided by subscriber + subscriber.onEvent(event); + } + } + } + ); + + // update the channel details for the subscription + Ternary queueDetails = _subscribers.get(queueName); + queueDetails.second(channel); + _subscribers.put(queueName, queueDetails); + + } catch (AlreadyClosedException closedException) { + s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + + " will be active after reconnection"); + } catch (ConnectException connectException) { + s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + + " will be active after reconnection"); + } catch (Exception e) { + throw new EventBusException("Failed to subscribe to event due to " + e.getMessage()); + } + + return queueId; + } + + @Override + public void unsubscribe(UUID subscriberId, EventSubscriber subscriber) throws EventBusException { + try { + String classname = subscriber.getClass().getName(); + String queueName = UUID.nameUUIDFromBytes(classname.getBytes()).toString(); + Ternary queueDetails = _subscribers.get(queueName); + Channel channel = queueDetails.second(); + channel.basicCancel(queueName); + _subscribers.remove(queueName, queueDetails); + } catch (Exception e) { + throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage()); + } + } + + // publish event on to the exchange created on AMQP server + @Override + public void publish(Event event) throws EventBusException { + + String routingKey = createRoutingKey(event); + String eventDescription = event.getDescription(); + + try { + Connection connection = getConnection(); + Channel channel = createChannel(connection); + createExchange(channel, _amqpExchangeName); + publishEventToExchange(channel, _amqpExchangeName, routingKey, eventDescription); + channel.close(); + } catch (AlreadyClosedException e) { + closeConnection(); + throw new EventBusException("Failed to publish event to message broker as connection to AMQP broker in lost"); + } catch (Exception e) { + throw new EventBusException("Failed to publish event to message broker due to " + e.getMessage()); + } + } + + /** creates a routing key from the event details. + * created routing key will be used while publishing the message to exchange on AMQP server + */ + private String createRoutingKey(Event event) { + + StringBuilder routingKey = new StringBuilder(); + + String eventSource = replaceNullWithWildcard(event.getEventSource()); + eventSource = eventSource.replace(".", "-"); + + String eventCategory = replaceNullWithWildcard(event.getEventCategory()); + eventCategory = eventCategory.replace(".", "-"); + + String eventType = replaceNullWithWildcard(event.getEventType()); + eventType = eventType.replace(".", "-"); + + String resourceType = replaceNullWithWildcard(event.getResourceType()); + resourceType = resourceType.replace(".", "-"); + + String resourceUuid = replaceNullWithWildcard(event.getResourceUUID()); + resourceUuid = resourceUuid.replace(".", "-"); + + // routing key will be of format: eventSource.eventCategory.eventType.resourceType.resourceUuid + routingKey.append(eventSource); + routingKey.append("."); + routingKey.append(eventCategory); + routingKey.append("."); + routingKey.append(eventType); + routingKey.append("."); + routingKey.append(resourceType); + routingKey.append("."); + routingKey.append(resourceUuid); + + return routingKey.toString(); + } + + /** creates a binding key from the event topic that subscriber specified + * binding key will be used to bind the queue created for subscriber to exchange on AMQP server + */ + private String createBindingKey(EventTopic topic) { + + StringBuilder bindingKey = new StringBuilder(); + + String eventSource = replaceNullWithWildcard(topic.getEventSource()); + eventSource = eventSource.replace(".", "-"); + + String eventCategory = replaceNullWithWildcard(topic.getEventCategory()); + eventCategory = eventCategory.replace(".", "-"); + + String eventType = replaceNullWithWildcard(topic.getEventType()); + eventType = eventType.replace(".", "-"); + + String resourceType = replaceNullWithWildcard(topic.getResourceType()); + resourceType = resourceType.replace(".", "-"); + + String resourceUuid = replaceNullWithWildcard(topic.getResourceUUID()); + resourceUuid = resourceUuid.replace(".", "-"); + + // binding key will be of format: eventSource.eventCategory.eventType.resourceType.resourceUuid + bindingKey.append(eventSource); + bindingKey.append("."); + bindingKey.append(eventCategory); + bindingKey.append("."); + bindingKey.append(eventType); + bindingKey.append("."); + bindingKey.append(resourceType); + bindingKey.append("."); + bindingKey.append(resourceUuid); + + return bindingKey.toString(); + } + + private synchronized Connection getConnection() throws Exception { + if (_connection == null) { + try { + return createConnection(); + } catch (Exception e) { + s_logger.error("Failed to create a connection to AMQP server due to " + e.getMessage()); + throw e; + } + } else { + return _connection; + } + } + + private synchronized Connection createConnection() throws Exception { + try { + ConnectionFactory factory = new ConnectionFactory(); + factory.setUsername(_username); + factory.setPassword(_password); + factory.setVirtualHost("/"); + factory.setHost(_amqpHost); + factory.setPort(_port); + Connection connection = factory.newConnection(); + connection.addShutdownListener(disconnectHandler); + _connection = connection; + return _connection; + } catch (Exception e) { + throw e; + } + } + + private synchronized void closeConnection() { + try { + if (_connection != null) { + _connection.close(); + } + } catch (Exception e) { + s_logger.warn("Failed to close connection to AMQP server due to " + e.getMessage()); + } + _connection = null; + } + + private synchronized void abortConnection () { + if (_connection == null) + return; + + try { + _connection.abort(); + } catch (Exception e) { + s_logger.warn("Failed to abort connection due to " + e.getMessage()); + } + _connection = null; + } + + private String replaceNullWithWildcard(String key) { + if (key == null || key.isEmpty()) { + return "*"; + } else { + return key; + } + } + + private Channel createChannel(Connection connection) throws Exception { + try { + return connection.createChannel(); + } catch (java.io.IOException exception) { + s_logger.warn("Failed to create a channel due to " + exception.getMessage()); + throw exception; + } + } + + private void createExchange(Channel channel, String exchangeName) throws Exception { + try { + channel.exchangeDeclare(exchangeName, "topic", true); + } catch (java.io.IOException exception) { + s_logger.error("Failed to create exchange" + exchangeName + " on RabbitMQ server"); + throw exception; + } + } + + private void publishEventToExchange(Channel channel, String exchangeName, + String routingKey, String eventDescription) throws Exception { + try { + byte[] messageBodyBytes = eventDescription.getBytes(); + channel.basicPublish(exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes); + } catch (Exception e) { + s_logger.error("Failed to publish event " + routingKey + " on exchange " + exchangeName + + " of message broker due to " + e.getMessage()); + throw e; + } + } + + private String getEventCategoryFromRoutingKey(String routingKey) { + String[] keyParts = routingKey.split("\\."); + return keyParts[1]; + } + + private String getEventTypeFromRoutingKey(String routingKey) { + String[] keyParts = routingKey.split("\\."); + return keyParts[2]; + } + + private String getEventSourceFromRoutingKey(String routingKey) { + String[] keyParts = routingKey.split("\\."); + return keyParts[0]; + } + + private String getResourceTypeFromRoutingKey(String routingKey) { + String[] keyParts = routingKey.split("\\."); + return keyParts[3]; + } + + private String getResourceUUIDFromRoutingKey(String routingKey) { + String[] keyParts = routingKey.split("\\."); + return keyParts[4]; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + ReconnectionTask reconnect = new ReconnectionTask(); // initiate connection to AMQP server + executorService.submit(reconnect); + return true; + } + + @Override + public boolean stop() { + + if (_connection.isOpen()) { + for (String subscriberId : _subscribers.keySet()) { + Ternary subscriberDetails = _subscribers.get(subscriberId); + Channel channel = subscriberDetails.second(); + String queueName = subscriberId; + try { + channel.queueDelete(queueName); + channel.abort(); + } catch (IOException ioe) { + s_logger.warn("Failed to delete queue: " + queueName + " on AMQP server due to " + ioe.getMessage() ); + } + } + } + + closeConnection(); + return true; + } + + // logic to deal with loss of connection to AMQP server + private class DisconnectHandler implements ShutdownListener { + + @Override + public void shutdownCompleted(ShutdownSignalException shutdownSignalException) { + if (!shutdownSignalException.isInitiatedByApplication()) { + + for (String subscriberId : _subscribers.keySet()) { + Ternary subscriberDetails = _subscribers.get(subscriberId); + subscriberDetails.second(null); + _subscribers.put(subscriberId, subscriberDetails); + } + + abortConnection(); // disconnected to AMQP server, so abort the connection and channels + s_logger.warn("Connection has been shutdown by AMQP server. Attempting to reconnect."); + + // initiate re-connect process + ReconnectionTask reconnect = new ReconnectionTask(); + executorService.submit(reconnect); + } + } + } + + // retry logic to connect back to AMQP server after loss of connection + private class ReconnectionTask implements Runnable { + + boolean connected = false; + Connection connection = null; + + public void run() { + + while (!connected) { + try { + Thread.sleep(_retryInterval); + } catch (InterruptedException ie) { + // ignore timer interrupts + } + + try { + try { + connection = createConnection(); + connected = true; + } catch (IOException ie) { + continue; // can't establish connection to AMQP server yet, so continue + } + + // prepare consumer on AMQP server for each of subscriber + for (String subscriberId : _subscribers.keySet()) { + Ternary subscriberDetails = _subscribers.get(subscriberId); + String bindingKey = subscriberDetails.first(); + EventSubscriber subscriber = subscriberDetails.third(); + + /** create a queue with subscriber ID as queue name and bind it to the exchange + * with binding key formed from event topic + */ + Channel channel = createChannel(connection); + createExchange(channel, _amqpExchangeName); + channel.queueDeclare(subscriberId, false, false, false, null); + channel.queueBind(subscriberId, _amqpExchangeName, bindingKey); + + // register a callback handler to receive the events that a subscriber subscribed to + channel.basicConsume(subscriberId, _autoAck, subscriberId, + new DefaultConsumer(channel) { + @Override + public void handleDelivery(String queueName, + Envelope envelope, + AMQP.BasicProperties properties, + byte[] body) + throws IOException { + + Ternary subscriberDetails + = _subscribers.get(queueName); // queue name == subscriber ID + + if (subscriberDetails != null) { + EventSubscriber subscriber = subscriberDetails.third(); + String routingKey = envelope.getRoutingKey(); + String eventSource = getEventSourceFromRoutingKey(routingKey); + String eventCategory = getEventCategoryFromRoutingKey(routingKey); + String eventType = getEventTypeFromRoutingKey(routingKey); + String resourceType = getResourceTypeFromRoutingKey(routingKey); + String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); + + // create event object from the message details obtained from AMQP server + Event event = new Event(eventSource, eventCategory, eventType, + resourceType, resourceUUID); + event.setDescription(new String(body)); + + // deliver the event to call back object provided by subscriber + subscriber.onEvent(event); + } + } + } + ); + + // update the channel details for the subscription + subscriberDetails.second(channel); + _subscribers.put(subscriberId, subscriberDetails); + } + } catch (Exception e) { + s_logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage()); + } + } + return; + } + } +} \ No newline at end of file diff --git a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java index 30a11294051..2104322a869 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java @@ -18,6 +18,7 @@ package com.cloud.network.guru; import javax.ejb.Local; +import com.cloud.event.ActionEventUtils; import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; @@ -25,7 +26,6 @@ import com.cloud.dc.DataCenter.NetworkType; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.network.Network; @@ -95,7 +95,7 @@ public class OvsGuestNetworkGuru extends GuestNetworkGuru { throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a part of network " + network + " implement ", DataCenter.class, dcId); } implemented.setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet)); - EventUtils.saveEvent(UserContext.current().getCallerUserId(), network.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: "+vnet+ " Network Id: "+network.getId(), 0); + ActionEventUtils.onCompletedActionEvent(UserContext.current().getCallerUserId(), network.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + network.getId(), 0); } else { implemented.setBroadcastUri(network.getBroadcastUri()); } diff --git a/plugins/pom.xml b/plugins/pom.xml index c5b6e58e1bb..f91c6eed58b 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -41,6 +41,7 @@ hypervisors/ovm hypervisors/xen hypervisors/kvm + event-bus/rabbitmq hypervisors/simulator hypervisors/baremetal network-elements/elastic-loadbalancer diff --git a/pom.xml b/pom.xml index 35d6520ce6b..59feef5b2f4 100644 --- a/pom.xml +++ b/pom.xml @@ -163,6 +163,7 @@ patches client test + framework diff --git a/server/pom.xml b/server/pom.xml index 4c3ba6f9e76..ef1b68a1a53 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -80,6 +80,11 @@ tests test + + org.apache.cloudstack + cloud-framework-events + ${project.version} + install diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java index a4c0facc97d..1a93f97a704 100755 --- a/server/src/com/cloud/alert/AlertManagerImpl.java +++ b/server/src/com/cloud/alert/AlertManagerImpl.java @@ -59,6 +59,7 @@ import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterIpAddressDao; import com.cloud.dc.dao.HostPodDao; +import com.cloud.event.AlertGenerator; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; @@ -260,6 +261,10 @@ public class AlertManagerImpl implements AlertManager { @Override public void sendAlert(short alertType, long dataCenterId, Long podId, String subject, String body) { + + // publish alert + AlertGenerator.publishAlertOnEventBus(getAlertType(alertType), dataCenterId, podId, subject, body); + // TODO: queue up these messages and send them as one set of issues once a certain number of issues is reached? If that's the case, // shouldn't we have a type/severity as part of the API so that severe errors get sent right away? try { @@ -271,6 +276,65 @@ public class AlertManagerImpl implements AlertManager { } } + private String getAlertType(short alertType) { + if (alertType == ALERT_TYPE_MEMORY) { + return "ALERT.MEMORY"; + } else if (alertType == ALERT_TYPE_CPU) { + return "ALERT.MEMORY"; + } else if (alertType == ALERT_TYPE_STORAGE) { + return "ALERT.STORAGE"; + } else if (alertType == ALERT_TYPE_STORAGE_ALLOCATED) { + return "ALERT.STORAGE.ALLOCATED"; + } else if (alertType == ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP) { + return "ALERT.NETWORK.PUBLICIP"; + } else if (alertType == ALERT_TYPE_PRIVATE_IP) { + return "ALERT.NETWORK.PRIVATEIP"; + } else if (alertType == ALERT_TYPE_SECONDARY_STORAGE) { + return "ALERT.STORAGE.SECONDARY"; + } else if (alertType == ALERT_TYPE_HOST) { + return "ALERT.COMPUTE.HOST"; + } else if (alertType == ALERT_TYPE_USERVM) { + return "ALERT.USERVM"; + } else if (alertType == ALERT_TYPE_DOMAIN_ROUTER) { + return "ALERT.SERVICE.DOMAINROUTER"; + } else if (alertType == ALERT_TYPE_CONSOLE_PROXY) { + return "ALERT.SERVICE.CONSOLEPROXY"; + } else if (alertType == ALERT_TYPE_ROUTING) { + return "ALERT.NETWORK.ROUTING"; + } else if (alertType == ALERT_TYPE_STORAGE_MISC) { + return "ALERT.STORAGE.MISC"; + } else if (alertType == ALERT_TYPE_USAGE_SERVER) { + return "ALERT.USAGE"; + } else if (alertType == ALERT_TYPE_MANAGMENT_NODE) { + return "ALERT.MANAGEMENT"; + } else if (alertType == ALERT_TYPE_DOMAIN_ROUTER_MIGRATE) { + return "ALERT.NETWORK.DOMAINROUTERMIGRATE"; + } else if (alertType == ALERT_TYPE_CONSOLE_PROXY_MIGRATE) { + return "ALERT.SERVICE.CONSOLEPROXYMIGRATE"; + } else if (alertType == ALERT_TYPE_USERVM_MIGRATE) { + return "ALERT.USERVM.MIGRATE"; + } else if (alertType == ALERT_TYPE_VLAN) { + return "ALERT.NETWORK.VLAN"; + } else if (alertType == ALERT_TYPE_SSVM) { + return "ALERT.SERVICE.SSVM"; + } else if (alertType == ALERT_TYPE_USAGE_SERVER_RESULT) { + return "ALERT.USAGE.RESULT"; + } else if (alertType == ALERT_TYPE_STORAGE_DELETE) { + return "ALERT.STORAGE.DELETE"; + } else if (alertType == ALERT_TYPE_UPDATE_RESOURCE_COUNT) { + return "ALERT.RESOURCE.COUNT"; + } else if (alertType == ALERT_TYPE_USAGE_SANITY_RESULT) { + return "ALERT.USAGE.SANITY"; + } else if (alertType == ALERT_TYPE_DIRECT_ATTACHED_PUBLIC_IP) { + return "ALERT.NETWORK.DIRECTPUBLICIP"; + } else if (alertType == ALERT_TYPE_LOCAL_STORAGE) { + return "ALERT.STORAGE.LOCAL"; + } else if (alertType == ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED) { + return "ALERT.RESOURCE.EXCEED"; + } + return "UNKNOWN"; + } + @Override @DB public void recalculateCapacity() { // FIXME: the right way to do this is to register a listener (see RouterStatsListener, VMSyncListener) diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 0b08b26cc32..143e2800db8 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -16,68 +16,8 @@ // under the License. package com.cloud.api; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.cloudstack.api.ApiConstants.HostDetails; -import org.apache.cloudstack.api.ApiConstants.VMDetails; -import org.apache.cloudstack.api.response.AccountResponse; -import org.apache.cloudstack.api.response.AsyncJobResponse; -import org.apache.cloudstack.api.response.DiskOfferingResponse; -import org.apache.cloudstack.api.response.DomainRouterResponse; -import org.apache.cloudstack.api.response.EventResponse; -import org.apache.cloudstack.api.response.HostResponse; -import org.apache.cloudstack.api.response.InstanceGroupResponse; -import org.apache.cloudstack.api.response.ProjectAccountResponse; -import org.apache.cloudstack.api.response.ProjectInvitationResponse; -import org.apache.cloudstack.api.response.ProjectResponse; -import org.apache.cloudstack.api.response.ResourceTagResponse; -import org.apache.cloudstack.api.response.SecurityGroupResponse; -import org.apache.cloudstack.api.response.ServiceOfferingResponse; -import org.apache.cloudstack.api.response.StoragePoolResponse; -import org.apache.cloudstack.api.response.UserResponse; -import org.apache.cloudstack.api.response.UserVmResponse; -import org.apache.cloudstack.api.response.VolumeResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.api.query.dao.AccountJoinDao; -import com.cloud.api.query.dao.AsyncJobJoinDao; -import com.cloud.api.query.dao.DataCenterJoinDao; -import com.cloud.api.query.dao.DiskOfferingJoinDao; -import com.cloud.api.query.dao.DomainRouterJoinDao; -import com.cloud.api.query.dao.HostJoinDao; -import com.cloud.api.query.dao.InstanceGroupJoinDao; -import com.cloud.api.query.dao.ProjectAccountJoinDao; -import com.cloud.api.query.dao.ProjectInvitationJoinDao; -import com.cloud.api.query.dao.ProjectJoinDao; -import com.cloud.api.query.dao.ResourceTagJoinDao; -import com.cloud.api.query.dao.SecurityGroupJoinDao; -import com.cloud.api.query.dao.ServiceOfferingJoinDao; -import com.cloud.api.query.dao.StoragePoolJoinDao; -import com.cloud.api.query.dao.UserAccountJoinDao; -import com.cloud.api.query.dao.UserVmJoinDao; -import com.cloud.api.query.dao.VolumeJoinDao; -import com.cloud.api.query.vo.AccountJoinVO; -import com.cloud.api.query.vo.AsyncJobJoinVO; -import com.cloud.api.query.vo.DataCenterJoinVO; -import com.cloud.api.query.vo.DiskOfferingJoinVO; -import com.cloud.api.query.vo.DomainRouterJoinVO; -import com.cloud.api.query.vo.EventJoinVO; -import com.cloud.api.query.vo.HostJoinVO; -import com.cloud.api.query.vo.InstanceGroupJoinVO; -import com.cloud.api.query.vo.ProjectAccountJoinVO; -import com.cloud.api.query.vo.ProjectInvitationJoinVO; -import com.cloud.api.query.vo.ProjectJoinVO; -import com.cloud.api.query.vo.ResourceTagJoinVO; -import com.cloud.api.query.vo.SecurityGroupJoinVO; -import com.cloud.api.query.vo.ServiceOfferingJoinVO; -import com.cloud.api.query.vo.StoragePoolJoinVO; -import com.cloud.api.query.vo.UserAccountJoinVO; -import com.cloud.api.query.vo.UserVmJoinVO; -import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.api.query.dao.*; +import com.cloud.api.query.vo.*; import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -89,18 +29,8 @@ import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationService; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.dc.AccountVlanMapVO; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.HostPodVO; -import com.cloud.dc.Vlan; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.AccountVlanMapDao; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.VlanDao; +import com.cloud.dc.*; +import com.cloud.dc.dao.*; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.Event; @@ -112,65 +42,23 @@ import com.cloud.host.HostStats; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.IPAddressVO; -import com.cloud.network.IpAddress; -import com.cloud.network.LoadBalancerVO; -import com.cloud.network.Network; +import com.cloud.network.*; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.NetworkDomainVO; -import com.cloud.network.NetworkManager; -import com.cloud.network.NetworkModel; -import com.cloud.network.NetworkProfile; -import com.cloud.network.NetworkRuleConfigVO; -import com.cloud.network.NetworkVO; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PhysicalNetworkVO; -import com.cloud.network.Site2SiteVpnGatewayVO; -import com.cloud.network.Site2SiteCustomerGatewayVO; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.as.AutoScalePolicy; -import com.cloud.network.as.AutoScalePolicyConditionMapVO; -import com.cloud.network.as.AutoScalePolicyVO; -import com.cloud.network.as.AutoScaleVmGroupPolicyMapVO; -import com.cloud.network.as.AutoScaleVmGroupVO; -import com.cloud.network.as.AutoScaleVmProfileVO; -import com.cloud.network.as.ConditionVO; -import com.cloud.network.as.CounterVO; -import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao; -import com.cloud.network.as.dao.AutoScalePolicyDao; -import com.cloud.network.as.dao.AutoScaleVmGroupDao; -import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao; -import com.cloud.network.as.dao.AutoScaleVmProfileDao; -import com.cloud.network.as.dao.ConditionDao; -import com.cloud.network.as.dao.CounterDao; -import com.cloud.network.dao.FirewallRulesCidrsDao; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.NetworkDomainDao; -import com.cloud.network.dao.NetworkRuleConfigDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; -import com.cloud.network.dao.Site2SiteVpnGatewayDao; -import com.cloud.network.dao.Site2SiteCustomerGatewayDao; +import com.cloud.network.as.*; +import com.cloud.network.as.dao.*; +import com.cloud.network.dao.*; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.dao.SecurityGroupDao; -import com.cloud.network.vpc.StaticRouteVO; -import com.cloud.network.vpc.VpcGatewayVO; -import com.cloud.network.vpc.VpcManager; -import com.cloud.network.vpc.VpcOffering; -import com.cloud.network.vpc.VpcVO; +import com.cloud.network.vpc.*; import com.cloud.network.vpc.dao.StaticRouteDao; +import com.cloud.network.vpc.dao.VpcDao; import com.cloud.network.vpc.dao.VpcGatewayDao; import com.cloud.network.vpc.dao.VpcOfferingDao; import com.cloud.offering.DiskOffering; @@ -183,57 +71,16 @@ import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; import com.cloud.projects.ProjectService; import com.cloud.resource.ResourceManager; -import com.cloud.server.Criteria; -import com.cloud.server.ManagementServer; -import com.cloud.server.ResourceTag; +import com.cloud.server.*; import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.server.StatsCollector; -import com.cloud.server.TaggedResourceService; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.DiskOfferingVO; -import com.cloud.storage.GuestOS; -import com.cloud.storage.GuestOSCategoryVO; -import com.cloud.storage.Snapshot; -import com.cloud.storage.SnapshotVO; +import com.cloud.storage.*; import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolVO; -import com.cloud.storage.StorageStats; -import com.cloud.storage.UploadVO; -import com.cloud.storage.VMTemplateHostVO; -import com.cloud.storage.VMTemplateS3VO; -import com.cloud.storage.VMTemplateSwiftVO; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; -import com.cloud.storage.VolumeHostVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; -import com.cloud.storage.dao.GuestOSCategoryDao; -import com.cloud.storage.dao.GuestOSDao; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotPolicyDao; -import com.cloud.storage.dao.StoragePoolDao; -import com.cloud.storage.dao.UploadDao; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VMTemplateDetailsDao; -import com.cloud.storage.dao.VMTemplateHostDao; -import com.cloud.storage.dao.VMTemplateS3Dao; -import com.cloud.storage.dao.VMTemplateSwiftDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeHostDao; +import com.cloud.storage.dao.*; import com.cloud.storage.snapshot.SnapshotPolicy; -import com.cloud.user.Account; -import com.cloud.user.AccountDetailsDao; -import com.cloud.user.AccountVO; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.SSHKeyPairVO; -import com.cloud.user.User; -import com.cloud.user.UserAccount; -import com.cloud.user.UserStatisticsVO; -import com.cloud.user.UserVO; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; @@ -242,23 +89,13 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; -import com.cloud.vm.ConsoleProxyVO; -import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.InstanceGroup; -import com.cloud.vm.InstanceGroupVO; -import com.cloud.vm.NicProfile; -import com.cloud.vm.UserVmDetailVO; -import com.cloud.vm.UserVmManager; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VmStats; -import com.cloud.vm.dao.ConsoleProxyDao; -import com.cloud.vm.dao.DomainRouterDao; -import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.UserVmDetailsDao; -import com.cloud.vm.dao.VMInstanceDao; -import com.cloud.network.vpc.dao.VpcDao; +import com.cloud.vm.*; +import com.cloud.vm.dao.*; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.*; + +import java.util.*; public class ApiDBUtils { private static ManagementServer _ms; @@ -699,7 +536,7 @@ public class ApiDBUtils { public static Snapshot findSnapshotById(long snapshotId) { SnapshotVO snapshot = _snapshotDao.findById(snapshotId); - if (snapshot != null && snapshot.getRemoved() == null && snapshot.getStatus() == Snapshot.Status.BackedUp) { + if (snapshot != null && snapshot.getRemoved() == null && snapshot.getState() == Snapshot.State.BackedUp) { return snapshot; } else { return null; diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 641f25ba0b9..54639a87b3e 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -16,125 +16,9 @@ // under the License. package com.cloud.api; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.ResponseGenerator; -import org.apache.log4j.Logger; - -import org.apache.cloudstack.acl.ControlledEntity; -import org.apache.cloudstack.acl.ControlledEntity.ACLType; -import org.apache.cloudstack.api.ApiConstants.HostDetails; -import org.apache.cloudstack.api.ApiConstants.VMDetails; -import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; -import org.apache.cloudstack.api.response.AccountResponse; - import com.cloud.api.query.ViewResponseHelper; -import com.cloud.api.query.vo.AccountJoinVO; -import com.cloud.api.query.vo.AsyncJobJoinVO; -import com.cloud.api.query.vo.ControlledViewEntity; -import com.cloud.api.query.vo.DataCenterJoinVO; -import com.cloud.api.query.vo.DiskOfferingJoinVO; -import com.cloud.api.query.vo.DomainRouterJoinVO; -import com.cloud.api.query.vo.EventJoinVO; -import com.cloud.api.query.vo.HostJoinVO; -import com.cloud.api.query.vo.InstanceGroupJoinVO; -import com.cloud.api.query.vo.ProjectAccountJoinVO; -import com.cloud.api.query.vo.ProjectInvitationJoinVO; -import com.cloud.api.query.vo.ProjectJoinVO; -import com.cloud.api.query.vo.ResourceTagJoinVO; -import com.cloud.api.query.vo.SecurityGroupJoinVO; -import com.cloud.api.query.vo.ServiceOfferingJoinVO; -import com.cloud.api.query.vo.StoragePoolJoinVO; -import com.cloud.api.query.vo.UserAccountJoinVO; -import com.cloud.api.query.vo.UserVmJoinVO; -import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.api.query.vo.*; import com.cloud.api.response.ApiResponseSerializer; -import org.apache.cloudstack.api.response.AsyncJobResponse; -import org.apache.cloudstack.api.response.AutoScalePolicyResponse; -import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; -import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; -import org.apache.cloudstack.api.response.CapabilityResponse; -import org.apache.cloudstack.api.response.CapacityResponse; -import org.apache.cloudstack.api.response.ClusterResponse; -import org.apache.cloudstack.api.response.ConditionResponse; -import org.apache.cloudstack.api.response.ConfigurationResponse; -import org.apache.cloudstack.api.response.ControlledEntityResponse; -import org.apache.cloudstack.api.response.CounterResponse; -import org.apache.cloudstack.api.response.CreateCmdResponse; -import org.apache.cloudstack.api.response.DiskOfferingResponse; -import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.cloudstack.api.response.DomainRouterResponse; -import org.apache.cloudstack.api.response.EventResponse; -import org.apache.cloudstack.api.response.ExtractResponse; -import org.apache.cloudstack.api.response.FirewallResponse; -import org.apache.cloudstack.api.response.FirewallRuleResponse; -import org.apache.cloudstack.api.response.GuestOSResponse; -import org.apache.cloudstack.api.response.HostResponse; -import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; -import org.apache.cloudstack.api.response.ControlledViewEntityResponse; -import org.apache.cloudstack.api.response.IPAddressResponse; -import org.apache.cloudstack.api.response.InstanceGroupResponse; -import org.apache.cloudstack.api.response.IpForwardingRuleResponse; -import org.apache.cloudstack.api.response.LBStickinessPolicyResponse; -import org.apache.cloudstack.api.response.LBStickinessResponse; -import org.apache.cloudstack.api.response.LDAPConfigResponse; -import org.apache.cloudstack.api.response.LoadBalancerResponse; -import org.apache.cloudstack.api.response.NetworkACLResponse; -import org.apache.cloudstack.api.response.NetworkOfferingResponse; -import org.apache.cloudstack.api.response.NetworkResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.api.response.PodResponse; -import org.apache.cloudstack.api.response.PrivateGatewayResponse; -import org.apache.cloudstack.api.response.ProjectAccountResponse; -import org.apache.cloudstack.api.response.ProjectInvitationResponse; -import org.apache.cloudstack.api.response.ProjectResponse; -import org.apache.cloudstack.api.response.ProviderResponse; -import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; -import org.apache.cloudstack.api.response.ResourceCountResponse; -import org.apache.cloudstack.api.response.ResourceLimitResponse; -import org.apache.cloudstack.api.response.ResourceTagResponse; -import org.apache.cloudstack.api.response.SecurityGroupResponse; -import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; -import org.apache.cloudstack.api.response.ServiceOfferingResponse; -import org.apache.cloudstack.api.response.ServiceResponse; -import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; -import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; -import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; -import org.apache.cloudstack.api.response.SnapshotPolicyResponse; -import org.apache.cloudstack.api.response.SnapshotResponse; -import org.apache.cloudstack.api.response.SnapshotScheduleResponse; -import org.apache.cloudstack.api.response.StaticRouteResponse; -import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; -import org.apache.cloudstack.api.response.StoragePoolResponse; -import org.apache.cloudstack.api.response.SwiftResponse; -import org.apache.cloudstack.api.response.SystemVmInstanceResponse; -import org.apache.cloudstack.api.response.SystemVmResponse; -import org.apache.cloudstack.api.response.TemplatePermissionsResponse; -import org.apache.cloudstack.api.response.TemplateResponse; -import org.apache.cloudstack.api.response.TrafficTypeResponse; -import org.apache.cloudstack.api.response.UserResponse; -import org.apache.cloudstack.api.response.UserVmResponse; -import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; -import org.apache.cloudstack.api.response.VlanIpRangeResponse; -import org.apache.cloudstack.api.response.VolumeResponse; -import org.apache.cloudstack.api.response.VpcOfferingResponse; -import org.apache.cloudstack.api.response.VpcResponse; -import org.apache.cloudstack.api.response.VpnUsersResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import org.apache.cloudstack.api.response.S3Response; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; @@ -143,53 +27,21 @@ import com.cloud.configuration.Configuration; import com.cloud.configuration.Resource.ResourceOwnerType; import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.HostPodVO; -import com.cloud.dc.Pod; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.dc.Vlan; +import com.cloud.dc.*; import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.VlanVO; import com.cloud.domain.Domain; import com.cloud.event.Event; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.hypervisor.HypervisorCapabilities; -import com.cloud.network.IPAddressVO; -import com.cloud.network.IpAddress; -import com.cloud.network.Network; +import com.cloud.network.*; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.NetworkProfile; -import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PhysicalNetworkTrafficType; -import com.cloud.network.PhysicalNetworkVO; -import com.cloud.network.RemoteAccessVpn; -import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.network.Site2SiteVpnConnection; -import com.cloud.network.Site2SiteVpnGateway; -import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VpnUser; -import com.cloud.network.as.AutoScalePolicy; -import com.cloud.network.as.AutoScaleVmGroup; -import com.cloud.network.as.AutoScaleVmProfile; -import com.cloud.network.as.AutoScaleVmProfileVO; -import com.cloud.network.as.Condition; -import com.cloud.network.as.ConditionVO; -import com.cloud.network.as.Counter; +import com.cloud.network.as.*; import com.cloud.network.router.VirtualRouter; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.LoadBalancer; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.StickinessPolicy; +import com.cloud.network.rules.*; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityRule; import com.cloud.network.security.SecurityRule.SecurityRuleType; @@ -207,25 +59,11 @@ import com.cloud.projects.ProjectInvitation; import com.cloud.server.Criteria; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.storage.GuestOS; -import com.cloud.storage.GuestOSCategoryVO; -import com.cloud.storage.S3; -import com.cloud.storage.Snapshot; +import com.cloud.storage.*; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.TemplateType; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolVO; -import com.cloud.storage.StorageStats; -import com.cloud.storage.Swift; -import com.cloud.storage.UploadVO; -import com.cloud.storage.VMTemplateHostVO; -import com.cloud.storage.VMTemplateS3VO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; -import com.cloud.storage.VMTemplateSwiftVO; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeVO; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.storage.snapshot.SnapshotSchedule; import com.cloud.template.VirtualMachineTemplate; @@ -242,6 +80,21 @@ import com.cloud.vm.InstanceGroup; import com.cloud.vm.NicProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.Type; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.response.*; +import org.apache.log4j.Logger; + +import java.text.DecimalFormat; +import java.util.*; + +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; public class ApiResponseHelper implements ResponseGenerator { @@ -378,7 +231,7 @@ public class ApiResponseHelper implements ResponseGenerator { snapshotResponse.setCreated(snapshot.getCreated()); snapshotResponse.setName(snapshot.getName()); snapshotResponse.setIntervalType(ApiDBUtils.getSnapshotIntervalTypes(snapshot.getId())); - snapshotResponse.setState(snapshot.getStatus()); + snapshotResponse.setState(snapshot.getState()); //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Snapshot, snapshot.getId()); diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index ed2720082c4..b4612ae6999 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -50,10 +50,10 @@ import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import com.cloud.event.ActionEventUtils; import com.cloud.utils.ReflectUtil; import org.apache.cloudstack.acl.APILimitChecker; import org.apache.cloudstack.acl.APIChecker; -import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.*; import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; @@ -116,7 +116,6 @@ import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; -import com.cloud.event.EventUtils; import com.cloud.exception.AccountLimitException; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.InsufficientCapacityException; @@ -467,7 +466,7 @@ public class ApiServer implements HttpRequestHandler { asyncCmd.setStartEventId(startEventId); // save the scheduled event - Long eventId = EventUtils.saveScheduledEvent((callerUserId == null) ? User.UID_SYSTEM : callerUserId, + Long eventId = ActionEventUtils.onScheduledActionEvent((callerUserId == null) ? User.UID_SYSTEM : callerUserId, asyncCmd.getEntityOwnerId(), asyncCmd.getEventType(), asyncCmd.getEventDescription(), startEventId); if (startEventId == 0) { diff --git a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java index 25298a9eebd..74200e2d138 100755 --- a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java +++ b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java @@ -16,20 +16,10 @@ // under the License. package com.cloud.baremetal; -import java.util.Date; -import java.util.List; - -import javax.ejb.Local; - -import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; -import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; -import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; -import org.apache.log4j.Logger; - import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.DataCenterVO; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; +import com.cloud.event.UsageEventUtils; import com.cloud.exception.ResourceAllocationException; import com.cloud.host.Host; import com.cloud.host.HostVO; @@ -46,6 +36,14 @@ import com.cloud.user.Account; import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import java.util.Date; +import java.util.List; @Local(value=TemplateAdapter.class) public class BareMetalTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter { @@ -82,9 +80,9 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem private void templateCreateUsage(VMTemplateVO template, HostVO host) { if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, template.getAccountId(), host.getDataCenterId(), - template.getId(), template.getName(), null, template.getSourceTemplateId(), 0L); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_TEMPLATE_CREATE, template.getAccountId(), host.getDataCenterId(), + template.getId(), template.getName(), null, template.getSourceTemplateId(), 0L, + template.getClass().getName(), template.getUuid()); } } @@ -172,8 +170,8 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem _tmpltZoneDao.remove(templateZone.getId()); } - UsageEventVO usageEvent = new UsageEventVO(eventType, account.getId(), pxeServer.getDataCenterId(), templateId, null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(eventType, account.getId(), pxeServer.getDataCenterId(), + templateId, null, template.getClass().getName(), template.getUuid()); } finally { if (lock != null) { _tmpltHostDao.releaseFromLockTable(lock.getId()); diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index 57cfb396d3e..6ff37ea2b22 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -16,28 +16,11 @@ // under the License. package com.cloud.baremetal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; -import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; -import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; -import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; -import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; -import org.apache.log4j.Logger; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; import com.cloud.agent.api.baremetal.IpmiBootorResetCommand; import com.cloud.agent.manager.Commands; -import org.apache.cloudstack.api.command.user.vm.StartVMCmd; import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; @@ -47,14 +30,8 @@ import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.domain.DomainVO; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.StorageUnavailableException; +import com.cloud.event.UsageEventUtils; +import com.cloud.exception.*; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -71,11 +48,7 @@ import com.cloud.storage.Volume; import com.cloud.template.TemplateAdapter; import com.cloud.template.TemplateAdapter.TemplateAdapterType; import com.cloud.template.TemplateProfile; -import com.cloud.user.Account; -import com.cloud.user.AccountVO; -import com.cloud.user.SSHKeyPair; -import com.cloud.user.User; -import com.cloud.user.UserContext; +import com.cloud.user.*; import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; @@ -88,19 +61,26 @@ import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.utils.net.NetUtils; -import com.cloud.vm.BareMetalVmService; -import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.UserVmManagerImpl; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VirtualMachine; +import com.cloud.vm.*; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachine.Type; -import com.cloud.vm.VirtualMachineName; -import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile.Param; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.StartVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; @Local(value={BareMetalVmManager.class, BareMetalVmService.class}) public class BareMetalVmManagerImpl extends UserVmManagerImpl implements BareMetalVmManager, BareMetalVmService, Manager, @@ -367,8 +347,9 @@ public class BareMetalVmManagerImpl extends UserVmManagerImpl implements BareMet s_logger.debug("Successfully allocated DB entry for " + vm); } UserContext.current().setEventDetails("Vm Id: " + vm.getId()); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, accountId, cmd.getZoneId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(), HypervisorType.BareMetal.toString()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, cmd.getZoneId(), vm.getId(), + vm.getHostName(), offering.getId(), template.getId(), HypervisorType.BareMetal.toString(), + VirtualMachine.class.getName(), vm.getUuid()); _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.user_vm); diff --git a/server/src/com/cloud/configuration/DefaultInterceptorLibrary.java b/server/src/com/cloud/configuration/DefaultInterceptorLibrary.java index ced2618cec6..13a22dbe827 100644 --- a/server/src/com/cloud/configuration/DefaultInterceptorLibrary.java +++ b/server/src/com/cloud/configuration/DefaultInterceptorLibrary.java @@ -16,18 +16,18 @@ // under the License. package com.cloud.configuration; -import java.util.List; - -import com.cloud.event.ActionEventCallback; +import com.cloud.event.ActionEventUtils; import com.cloud.utils.component.AnnotationInterceptor; import com.cloud.utils.component.InterceptorLibrary; import com.cloud.utils.db.DatabaseCallback; +import java.util.List; + public class DefaultInterceptorLibrary implements InterceptorLibrary { @Override public void addInterceptors(List> interceptors) { interceptors.add(new DatabaseCallback()); - interceptors.add(new ActionEventCallback()); + interceptors.add(new ActionEventUtils.ActionEventCallback()); } } diff --git a/server/src/com/cloud/event/ActionEventCallback.java b/server/src/com/cloud/event/ActionEventCallback.java deleted file mode 100644 index f941400de64..00000000000 --- a/server/src/com/cloud/event/ActionEventCallback.java +++ /dev/null @@ -1,135 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.event; - -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Method; - -import net.sf.cglib.proxy.Callback; -import net.sf.cglib.proxy.MethodInterceptor; -import net.sf.cglib.proxy.MethodProxy; - -import com.cloud.user.UserContext; -import com.cloud.utils.component.AnnotationInterceptor; - -public class ActionEventCallback implements MethodInterceptor, AnnotationInterceptor { - - @Override - public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { - EventVO event = interceptStart(method); - boolean success = true; - try { - return methodProxy.invokeSuper(object, args); - } catch (Exception e){ - success = false; - interceptException(method, event); - throw e; - } finally { - if(success){ - interceptComplete(method, event); - } - } - } - - @Override - public boolean needToIntercept(AnnotatedElement element) { - if (!(element instanceof Method)) { - return false; - - } - Method method = (Method)element; - ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); - if (actionEvent != null) { - return true; - } - - return false; - } - - @Override - public EventVO interceptStart(AnnotatedElement element) { - EventVO event = null; - Method method = (Method)element; - ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); - if (actionEvent != null) { - boolean async = actionEvent.async(); - if(async){ - UserContext ctx = UserContext.current(); - long userId = ctx.getCallerUserId(); - long accountId = ctx.getAccountId(); - long startEventId = ctx.getStartEventId(); - String eventDescription = actionEvent.eventDescription(); - if(ctx.getEventDetails() != null){ - eventDescription += ". "+ctx.getEventDetails(); - } - EventUtils.saveStartedEvent(userId, accountId, actionEvent.eventType(), eventDescription, startEventId); - } - } - return event; - } - - @Override - public void interceptComplete(AnnotatedElement element, EventVO event) { - Method method = (Method)element; - ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); - if (actionEvent != null) { - UserContext ctx = UserContext.current(); - long userId = ctx.getCallerUserId(); - long accountId = ctx.getAccountId(); - long startEventId = ctx.getStartEventId(); - String eventDescription = actionEvent.eventDescription(); - if(ctx.getEventDetails() != null){ - eventDescription += ". "+ctx.getEventDetails(); - } - if(actionEvent.create()){ - //This start event has to be used for subsequent events of this action - startEventId = EventUtils.saveCreatedEvent(userId, accountId, EventVO.LEVEL_INFO, actionEvent.eventType(), "Successfully created entity for "+eventDescription); - ctx.setStartEventId(startEventId); - } else { - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_INFO, actionEvent.eventType(), "Successfully completed "+eventDescription, startEventId); - } - } - } - - @Override - public void interceptException(AnnotatedElement element, EventVO event) { - Method method = (Method)element; - ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); - if (actionEvent != null) { - UserContext ctx = UserContext.current(); - long userId = ctx.getCallerUserId(); - long accountId = ctx.getAccountId(); - long startEventId = ctx.getStartEventId(); - String eventDescription = actionEvent.eventDescription(); - if(ctx.getEventDetails() != null){ - eventDescription += ". "+ctx.getEventDetails(); - } - if(actionEvent.create()){ - long eventId = EventUtils.saveCreatedEvent(userId, accountId, EventVO.LEVEL_ERROR, actionEvent.eventType(), "Error while creating entity for "+eventDescription); - ctx.setStartEventId(eventId); - } else { - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, actionEvent.eventType(), "Error while "+eventDescription, startEventId); - } - } - } - - @Override - public Callback getCallback() { - return this; - } - -} diff --git a/server/src/com/cloud/event/ActionEventUtils.java b/server/src/com/cloud/event/ActionEventUtils.java new file mode 100755 index 00000000000..744f46f3bc2 --- /dev/null +++ b/server/src/com/cloud/event/ActionEventUtils.java @@ -0,0 +1,288 @@ +// 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.event; + +import com.cloud.event.dao.EventDao; +import com.cloud.server.ManagementServer; +import com.cloud.user.Account; +import com.cloud.user.AccountVO; +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.utils.component.Adapters; +import com.cloud.utils.component.AnnotationInterceptor; +import com.cloud.utils.component.ComponentLocator; +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.log4j.Logger; + +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Method; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +public class ActionEventUtils { + + private static EventDao _eventDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(EventDao.class); + private static AccountDao _accountDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(AccountDao.class); + protected static UserDao _userDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(UserDao.class); + private static final Logger s_logger = Logger.getLogger(ActionEventUtils.class); + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + + public static Long onActionEvent(Long userId, Long accountId, Long domainId, String type, String description) { + + publishOnEventBus(userId, accountId, EventCategory.ACTION_EVENT.getName(), + type, com.cloud.event.Event.State.Completed); + + Event event = persistActionEvent(userId, accountId, domainId, null, type, Event.State.Completed, + description, null); + + return event.getId(); + } + + /* + * Save event after scheduling an async job + */ + public static Long onScheduledActionEvent(Long userId, Long accountId, String type, String description, + long startEventId) { + + publishOnEventBus(userId, accountId, EventCategory.ACTION_EVENT.getName(), type, + com.cloud.event.Event.State.Scheduled); + + Event event = persistActionEvent(userId, accountId, null, null, type, Event.State.Scheduled, + description, startEventId); + + return event.getId(); + } + + /* + * Save event after starting execution of an async job + */ + public static Long onStartedActionEvent(Long userId, Long accountId, String type, String description, + long startEventId) { + + publishOnEventBus(userId, accountId, EventCategory.ACTION_EVENT.getName(), type, + com.cloud.event.Event.State.Started); + + Event event = persistActionEvent(userId, accountId, null, null, type, Event.State.Started, + description, startEventId); + return event.getId(); + } + + public static Long onCompletedActionEvent(Long userId, Long accountId, String level, String type, + String description, long startEventId) { + + publishOnEventBus(userId, accountId, EventCategory.ACTION_EVENT.getName(), type, + com.cloud.event.Event.State.Completed); + + Event event = persistActionEvent(userId, accountId, null, level, type, Event.State.Completed, + description, startEventId); + + return event.getId(); + } + + public static Long onCreatedActionEvent(Long userId, Long accountId, String level, String type, String description) { + + publishOnEventBus(userId, accountId, EventCategory.ACTION_EVENT.getName(), type, + com.cloud.event.Event.State.Created); + + Event event = persistActionEvent(userId, accountId, null, level, type, Event.State.Created, description, null); + + return event.getId(); + } + + private static Event persistActionEvent(Long userId, Long accountId, Long domainId, String level, String type, + Event.State state, String description, Long startEventId) { + EventVO event = new EventVO(); + event.setUserId(userId); + event.setAccountId(accountId); + event.setType(type); + event.setState(state); + event.setDescription(description); + if (domainId != null) { + event.setDomainId(domainId); + } else { + event.setDomainId(getDomainId(accountId)); + } + if (level != null && !level.isEmpty()) { + event.setLevel(level); + } + if (startEventId != null) { + event.setStartId(startEventId); + } + event = _eventDao.persist(event); + return event; + } + + private static void publishOnEventBus(long userId, long accountId, String eventCategory, + String eventType, Event.State state) { + if (_eventBus == null) { + return; // no provider is configured to provide events bus, so just return + } + + org.apache.cloudstack.framework.events.Event event = new org.apache.cloudstack.framework.events.Event( + ManagementServer.Name, + eventCategory, + eventType, + EventTypes.getEntityForEvent(eventType), null); + + Map eventDescription = new HashMap(); + Account account = _accountDao.findById(accountId); + User user = _userDao.findById(userId); + eventDescription.put("user", user.getUuid()); + eventDescription.put("account", account.getUuid()); + eventDescription.put("event", eventType); + eventDescription.put("status", state.toString()); + event.setDescription(eventDescription); + + try { + _eventBus.publish(event); + } catch (EventBusException e) { + s_logger.warn("Failed to publish action event on the the event bus."); + } + } + + private static long getDomainId(long accountId){ + AccountVO account = _accountDao.findByIdIncludingRemoved(accountId); + return account.getDomainId(); + } + + public static class ActionEventCallback implements MethodInterceptor, AnnotationInterceptor { + + @Override + public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + EventVO event = interceptStart(method); + boolean success = true; + try { + return methodProxy.invokeSuper(object, args); + } catch (Exception e){ + success = false; + interceptException(method, event); + throw e; + } finally { + if(success){ + interceptComplete(method, event); + } + } + } + + @Override + public boolean needToIntercept(AnnotatedElement element) { + if (!(element instanceof Method)) { + return false; + + } + Method method = (Method)element; + ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); + if (actionEvent != null) { + return true; + } + + return false; + } + + @Override + public EventVO interceptStart(AnnotatedElement element) { + EventVO event = null; + Method method = (Method)element; + ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); + if (actionEvent != null) { + boolean async = actionEvent.async(); + if(async){ + UserContext ctx = UserContext.current(); + long userId = ctx.getCallerUserId(); + long accountId = ctx.getAccountId(); + long startEventId = ctx.getStartEventId(); + String eventDescription = actionEvent.eventDescription(); + if(ctx.getEventDetails() != null){ + eventDescription += ". "+ctx.getEventDetails(); + } + ActionEventUtils.onStartedActionEvent(userId, accountId, actionEvent.eventType(), eventDescription, startEventId); + } + } + return event; + } + + @Override + public void interceptComplete(AnnotatedElement element, EventVO event) { + Method method = (Method)element; + ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); + if (actionEvent != null) { + UserContext ctx = UserContext.current(); + long userId = ctx.getCallerUserId(); + long accountId = ctx.getAccountId(); + long startEventId = ctx.getStartEventId(); + String eventDescription = actionEvent.eventDescription(); + if(ctx.getEventDetails() != null){ + eventDescription += ". "+ctx.getEventDetails(); + } + if(actionEvent.create()){ + //This start event has to be used for subsequent events of this action + startEventId = ActionEventUtils.onCreatedActionEvent(userId, accountId, EventVO.LEVEL_INFO, actionEvent.eventType(), "Successfully created entity for " + eventDescription); + ctx.setStartEventId(startEventId); + } else { + ActionEventUtils.onCompletedActionEvent(userId, accountId, EventVO.LEVEL_INFO, actionEvent.eventType(), "Successfully completed " + eventDescription, startEventId); + } + } + } + + @Override + public void interceptException(AnnotatedElement element, EventVO event) { + Method method = (Method)element; + ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); + if (actionEvent != null) { + UserContext ctx = UserContext.current(); + long userId = ctx.getCallerUserId(); + long accountId = ctx.getAccountId(); + long startEventId = ctx.getStartEventId(); + String eventDescription = actionEvent.eventDescription(); + if(ctx.getEventDetails() != null){ + eventDescription += ". "+ctx.getEventDetails(); + } + if(actionEvent.create()){ + long eventId = ActionEventUtils.onCreatedActionEvent(userId, accountId, EventVO.LEVEL_ERROR, actionEvent.eventType(), "Error while creating entity for " + eventDescription); + ctx.setStartEventId(eventId); + } else { + ActionEventUtils.onCompletedActionEvent(userId, accountId, EventVO.LEVEL_ERROR, actionEvent.eventType(), "Error while " + eventDescription, startEventId); + } + } + } + + @Override + public Callback getCallback() { + return this; + } + } +} diff --git a/server/src/com/cloud/event/AlertGenerator.java b/server/src/com/cloud/event/AlertGenerator.java new file mode 100644 index 00000000000..42863778cfd --- /dev/null +++ b/server/src/com/cloud/event/AlertGenerator.java @@ -0,0 +1,87 @@ +// 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.event; + +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.HostPodVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.dc.dao.HostPodDao; +import com.cloud.server.ManagementServer; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import org.apache.cloudstack.framework.events.*; +import org.apache.log4j.Logger; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +public class AlertGenerator { + + private static final Logger s_logger = Logger.getLogger(AlertGenerator.class); + private static DataCenterDao _dcDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(DataCenterDao.class); + private static HostPodDao _podDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(HostPodDao.class); + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + + public static void publishAlertOnEventBus(String alertType, long dataCenterId, Long podId, String subject, String body) { + if (_eventBus == null) { + return; // no provider is configured to provider events bus, so just return + } + + org.apache.cloudstack.framework.events.Event event = + new org.apache.cloudstack.framework.events.Event(ManagementServer.Name, + EventCategory.ALERT_EVENT.getName(), + alertType, + null, + null); + + Map eventDescription = new HashMap(); + DataCenterVO dc = _dcDao.findById(dataCenterId); + HostPodVO pod = _podDao.findById(podId); + + eventDescription.put("event", alertType); + if (dc != null) { + eventDescription.put("dataCenterId", dc.getUuid()); + } else { + eventDescription.put("dataCenterId", null); + } + if (pod != null) { + eventDescription.put("podId", pod.getUuid()); + } else { + eventDescription.put("podId", null); + } + event.setDescription(eventDescription); + + try { + _eventBus.publish(event); + } catch (EventBusException e) { + s_logger.warn("Failed to publish alert on the the event bus."); + } + } +} diff --git a/server/src/com/cloud/event/EventUtils.java b/server/src/com/cloud/event/EventUtils.java deleted file mode 100755 index 3672ee72d4e..00000000000 --- a/server/src/com/cloud/event/EventUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.event; - -import com.cloud.event.dao.EventDao; -import com.cloud.server.ManagementServer; -import com.cloud.user.AccountVO; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.component.ComponentLocator; - -public class EventUtils { - private static EventDao _eventDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(EventDao.class); - private static AccountDao _accountDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(AccountDao.class); - - public static Long saveEvent(Long userId, Long accountId, Long domainId, String type, String description) { - EventVO event = new EventVO(); - event.setUserId(userId); - event.setAccountId(accountId); - event.setDomainId(domainId); - event.setType(type); - event.setDescription(description); - event = _eventDao.persist(event); - return event.getId(); - } - - /* - * Save event after scheduling an async job - */ - public static Long saveScheduledEvent(Long userId, Long accountId, String type, String description, long startEventId) { - EventVO event = new EventVO(); - event.setUserId(userId); - event.setAccountId(accountId); - event.setDomainId(getDomainId(accountId)); - event.setType(type); - event.setStartId(startEventId); - event.setState(Event.State.Scheduled); - event.setDescription("Scheduled async job for "+description); - event = _eventDao.persist(event); - return event.getId(); - } - - /* - * Save event after starting execution of an async job - */ - public static Long saveStartedEvent(Long userId, Long accountId, String type, String description, long startEventId) { - EventVO event = new EventVO(); - event.setUserId(userId); - event.setAccountId(accountId); - event.setDomainId(getDomainId(accountId)); - event.setType(type); - event.setState(Event.State.Started); - event.setDescription("Starting job for "+description); - event.setStartId(startEventId); - event = _eventDao.persist(event); - return event.getId(); - } - - public static Long saveEvent(Long userId, Long accountId, String level, String type, String description, long startEventId) { - EventVO event = new EventVO(); - event.setUserId(userId); - event.setAccountId(accountId); - event.setDomainId(getDomainId(accountId)); - event.setType(type); - event.setDescription(description); - event.setLevel(level); - event.setStartId(startEventId); - event = _eventDao.persist(event); - return (event != null ? event.getId() : null); - } - - public static Long saveCreatedEvent(Long userId, Long accountId, String level, String type, String description) { - EventVO event = new EventVO(); - event.setUserId(userId); - event.setAccountId(accountId); - event.setDomainId(getDomainId(accountId)); - event.setType(type); - event.setLevel(level); - event.setState(Event.State.Created); - event.setDescription(description); - event = _eventDao.persist(event); - return event.getId(); - } - - private static long getDomainId(long accountId){ - AccountVO account = _accountDao.findByIdIncludingRemoved(accountId); - return account.getDomainId(); - } -} diff --git a/server/src/com/cloud/event/UsageEventUtils.java b/server/src/com/cloud/event/UsageEventUtils.java new file mode 100644 index 00000000000..904525ea2f0 --- /dev/null +++ b/server/src/com/cloud/event/UsageEventUtils.java @@ -0,0 +1,119 @@ +package com.cloud.event; + +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.event.dao.UsageEventDao; +import com.cloud.server.ManagementServer; +import com.cloud.user.Account; +import com.cloud.user.dao.AccountDao; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.Event; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.log4j.Logger; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +public class UsageEventUtils { + + private static UsageEventDao _usageEventDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(UsageEventDao.class); + private static AccountDao _accountDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(AccountDao.class); + private static DataCenterDao _dcDao = ComponentLocator.getLocator(ManagementServer.Name).getDao(DataCenterDao.class); + private static final Logger s_logger = Logger.getLogger(UsageEventUtils.class); + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + + public static void publishUsageEvent(String usageType, long accountId, long zoneId, + long resourceId, String resourceName, + Long offeringId, Long templateId, Long size, + String entityType, String entityUUID) { + saveUsageEvent(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size); + publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID); + } + + public static void publishUsageEvent(String usageType, long accountId, long zoneId, long resourceId, + String resourceName, String entityType, String entityUUID) { + saveUsageEvent(usageType, accountId, zoneId, resourceId, resourceName); + publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID); + } + + public static void publishUsageEvent(String usageType, long accountId, long zoneId, + long ipAddressId, String ipAddress, boolean isSourceNat, + String guestType, boolean isSystem, String entityType, String entityUUID) { + saveUsageEvent(usageType, accountId, zoneId, ipAddressId, ipAddress, isSourceNat, guestType, isSystem); + publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID); + } + + public static void publishUsageEvent(String usageType, long accountId, long zoneId, long resourceId, + String resourceName, Long offeringId, Long templateId, String resourceType, + String entityType, String entityUUID) { + saveUsageEvent(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, resourceType); + publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID); + } + + public static void publishUsageEvent(String usageType, long accountId,long zoneId, long vmId, + long securityGroupId, String entityType, String entityUUID) { + saveUsageEvent(usageType, accountId, zoneId, vmId, securityGroupId); + publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID); + } + + public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, Long size) { + _usageEventDao.persist( new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size)); + } + + public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName) { + _usageEventDao.persist( new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName)); + } + + public static void saveUsageEvent(String usageType, long accountId, long zoneId, long ipAddressId, String ipAddress, boolean isSourceNat, String guestType, boolean isSystem) { + _usageEventDao.persist( new UsageEventVO(usageType, accountId, zoneId, ipAddressId, ipAddress, isSourceNat, guestType, isSystem)); + } + + public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, String resourceType) { + _usageEventDao.persist( new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, resourceType)); + } + + public static void saveUsageEvent(String usageType, long accountId,long zoneId, long vmId, long securityGroupId) { + _usageEventDao.persist( new UsageEventVO( usageType, accountId, zoneId, vmId, securityGroupId)); + } + + private static void publishUsageEvent(String usageEventType, Long accountId, Long zoneId, String resourceType, String resourceUUID) { + + if (_eventBus == null) { + return; // no provider is configured to provider events bus, so just return + } + + Account account = _accountDao.findById(accountId); + DataCenterVO dc = _dcDao.findById(zoneId); + + Event event = new Event(ManagementServer.Name, EventCategory.USAGE_EVENT.getName(), usageEventType, + resourceType, resourceUUID); + + Map eventDescription = new HashMap(); + eventDescription.put("account", account.getUuid()); + eventDescription.put("zone", dc.getUuid()); + eventDescription.put("event", usageEventType); + eventDescription.put("resource", resourceType); + eventDescription.put("id", resourceUUID); + event.setDescription(eventDescription); + + try { + _eventBus.publish(event); + } catch (EventBusException e) { + s_logger.warn("Failed to publish usage event on the the event bus."); + } + } +} diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 0a4851f3005..3d83487e89b 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -16,39 +16,9 @@ // under the License. package com.cloud.network; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -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.cloudstack.acl.ControlledEntity.ACLType; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.log4j.Logger; - import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; -import com.cloud.agent.api.AgentControlAnswer; -import com.cloud.agent.api.AgentControlCommand; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckNetworkAnswer; -import com.cloud.agent.api.CheckNetworkCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.agent.api.*; import com.cloud.agent.api.to.NicTO; import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; @@ -56,15 +26,9 @@ 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.dc.AccountVlanMapVO; -import com.cloud.dc.DataCenter; +import com.cloud.dc.*; import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.Pod; -import com.cloud.dc.PodVlanMapVO; -import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.VlanVO; import com.cloud.dc.dao.AccountVlanMapDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.PodVlanMapDao; @@ -75,63 +39,30 @@ import com.cloud.deploy.DeploymentPlan; import com.cloud.domain.Domain; import com.cloud.domain.dao.DomainDao; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; +import com.cloud.event.UsageEventUtils; import com.cloud.event.dao.UsageEventDao; -import com.cloud.exception.AccountLimitException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.ConnectionException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.UnsupportedServiceException; +import com.cloud.exception.*; 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.network.IpAddress.State; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; +import com.cloud.network.Network.*; import com.cloud.network.Networks.AddressFormat; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; -import com.cloud.network.element.DhcpServiceProvider; -import com.cloud.network.element.IpDeployer; -import com.cloud.network.element.LoadBalancingServiceProvider; -import com.cloud.network.element.NetworkElement; -import com.cloud.network.element.StaticNatServiceProvider; -import com.cloud.network.element.UserDataServiceProvider; +import com.cloud.network.dao.*; +import com.cloud.network.element.*; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; import com.cloud.network.lb.LoadBalancingRulesManager; -import com.cloud.network.rules.FirewallManager; -import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.*; import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.PortForwardingRuleVO; -import com.cloud.network.rules.RulesManager; -import com.cloud.network.rules.StaticNat; -import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.StaticNatRuleImpl; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.vpc.NetworkACLManager; import com.cloud.network.vpc.VpcManager; @@ -144,11 +75,7 @@ import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.org.Grouping; -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.*; import com.cloud.user.dao.AccountDao; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; @@ -156,30 +83,30 @@ import com.cloud.utils.component.Adapters; 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.*; 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.fsm.NoTransitionException; +import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; -import com.cloud.vm.Nic; -import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.ReservationContextImpl; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; +import com.cloud.vm.*; import com.cloud.vm.VirtualMachine.Type; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.VirtualMachineProfileImpl; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.net.URI; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; /** * NetworkManagerImpl implements NetworkManager. @@ -222,8 +149,6 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { @Inject LoadBalancingRulesManager _lbMgr; @Inject - UsageEventDao _usageEventDao; - @Inject RemoteAccessVpnService _vpnMgr; @Inject PodVlanMapDao _podVlanMapDao; @@ -272,8 +197,14 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { @Inject NetworkACLManager _networkACLMgr; @Inject + UsageEventDao _usageEventDao; + @Inject NetworkModel _networkModel; + protected StateMachine2 _stateMachine; + private final HashMap _systemNetworks = new HashMap(5); + private static Long _privateOfferingId = null; + ScheduledExecutorService _executor; SearchBuilder AssignIpAddressSearch; @@ -405,11 +336,9 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { VlanVO vlan = _vlanDao.findById(addr.getVlanId()); String guestType = vlan.getVlanType().toString(); - - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType, - addr.getSystem()); - _usageEventDao.persist(usageEvent); + addr.getSystem(), addr.getClass().getName(), addr.getUuid()); // don't increment resource count for direct ip addresses if (addr.getAssociatedWithNetworkId() != null) { _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.public_ip); @@ -1046,6 +975,8 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { _agentMgr.registerForHostEvents(this, true, false, true); + Network.State.getStateMachine().registerListener(new NetworkStateListener(_usageEventDao, _networksDao)); + s_logger.info("Network Manager is configured."); return true; @@ -1069,6 +1000,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } protected NetworkManagerImpl() { + setStateMachine(); } @Override @@ -1425,9 +1357,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); network.setReservationId(context.getReservationId()); - network.setState(Network.State.Implementing); - - _networksDao.update(networkId, network); + stateTransitTo(network, Event.ImplementNetwork); Network result = guru.implement(network, offering, dest, context); network.setCidr(result.getCidr()); @@ -1440,16 +1370,23 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { // implement network elements and re-apply all the network rules implementNetworkElementsAndResources(dest, context, network, offering); - network.setState(Network.State.Implemented); + stateTransitTo(network,Event.OperationSucceeded); + network.setRestartRequired(false); _networksDao.update(network.getId(), network); implemented.set(guru, network); return implemented; + } catch (NoTransitionException e) { + s_logger.error(e.getMessage()); + return null; } finally { if (implemented.first() == null) { s_logger.debug("Cleaning up because we're unable to implement the network " + network); - network.setState(Network.State.Shutdown); - _networksDao.update(networkId, network); + try { + stateTransitTo(network,Event.OperationFailed); + } catch (NoTransitionException e) { + s_logger.error(e.getMessage()); + } shutdownNetwork(networkId, context, false); } @@ -2045,9 +1982,12 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.debug("Network is not implemented: " + network); return false; } - - network.setState(Network.State.Shutdown); - _networksDao.update(network.getId(), network); + try { + stateTransitTo(network, Event.DestroyNetwork); + } catch (NoTransitionException e) { + network.setState(Network.State.Shutdown); + _networksDao.update(network.getId(), network); + } boolean success = shutdownNetworkElementsAndResources(context, cleanupElements, network); @@ -2062,15 +2002,22 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { guru.shutdown(profile, _networkOfferingDao.findById(network.getNetworkOfferingId())); applyProfileToNetwork(network, profile); - - network.setState(Network.State.Allocated); - network.setRestartRequired(false); + try { + stateTransitTo(network, Event.OperationSucceeded); + } catch (NoTransitionException e) { + network.setState(Network.State.Allocated); + network.setRestartRequired(false); + } _networksDao.update(network.getId(), network); _networksDao.clearCheckForGc(networkId); result = true; } else { - network.setState(Network.State.Implemented); - _networksDao.update(network.getId(), network); + try { + stateTransitTo(network, Event.OperationFailed); + } catch (NoTransitionException e) { + network.setState(Network.State.Implemented); + _networksDao.update(network.getId(), network); + } result = false; } txn.commit(); @@ -2230,8 +2177,11 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.warn("Failed to delete network " + network + "; was unable to cleanup corresponding ip ranges"); } else { // commit transaction only when ips and vlans for the network are released successfully - network.setState(Network.State.Destroy); - _networksDao.update(network.getId(), network); + try { + stateTransitTo(network, Event.DestroyNetwork); + } catch (NoTransitionException e) { + s_logger.debug(e.getMessage()); + } _networksDao.remove(network.getId()); NetworkOffering ntwkOff = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); @@ -2737,10 +2687,9 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { String guestType = vlan.getVlanType().toString(); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_RELEASE, + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, ip.getAllocatedToAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), - ip.isSourceNat(), guestType, ip.getSystem()); - _usageEventDao.persist(usageEvent); + ip.isSourceNat(), guestType, ip.getSystem(), ip.getClass().getName(), ip.getUuid()); } ip = _ipAddressDao.markAsUnavailable(addrId); @@ -3458,6 +3407,15 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { return _networkLockTimeout; } + + protected boolean stateTransitTo(NetworkVO network, Network.Event e) throws NoTransitionException { + return _stateMachine.transitTo(network, e, null, _networksDao); + } + + private void setStateMachine() { + _stateMachine = Network.State.getStateMachine(); + } + private Map> getServiceProvidersMap(long networkId) { Map> map = new HashMap>(); List nsms = _ntwkSrvcDao.getServicesInNetwork(networkId); @@ -3471,7 +3429,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } return map; } - + @Override public List getProvidersForServiceInNetwork(Network network, Service service) { Map> service2ProviderMap = getServiceProvidersMap(network.getId()); diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java index 7530e943116..bcd3f350166 100755 --- a/server/src/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/com/cloud/network/NetworkServiceImpl.java @@ -16,31 +16,6 @@ // under the License. package com.cloud.network; -import java.security.InvalidParameterException; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.acl.ControlledEntity.ACLType; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; -import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; -import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; -import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; - import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; @@ -58,17 +33,10 @@ import com.cloud.domain.DomainVO; 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.UsageEventUtils; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.UnsupportedServiceException; +import com.cloud.exception.*; import com.cloud.network.IpAddress.State; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestType; @@ -79,16 +47,7 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetwork.BroadcastDomainRange; import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkDomainDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; +import com.cloud.network.dao.*; import com.cloud.network.element.NetworkElement; import com.cloud.network.element.VirtualRouterElement; import com.cloud.network.element.VpcVirtualRouterElement; @@ -109,13 +68,7 @@ import com.cloud.projects.ProjectManager; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.DomainManager; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.User; -import com.cloud.user.UserContext; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.utils.AnnotationHelper; import com.cloud.utils.NumbersUtil; @@ -123,25 +76,28 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.*; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.ReservationContextImpl; -import com.cloud.vm.SecondaryStorageVmVO; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; +import com.cloud.vm.*; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.security.InvalidParameterException; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; /** * NetworkServiceImpl implements NetworkService. @@ -1623,10 +1579,8 @@ public class NetworkServiceImpl implements NetworkService, Manager { continue; } long isDefault = (nic.isDefaultNic()) ? 1 : 0; - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), null, oldNetworkOfferingId, null, 0L); - _usageEventDao.persist(usageEvent); - usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), networkOfferingId, null, isDefault); - _usageEventDao.persist(usageEvent); + UsageEventUtils.saveUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), null, oldNetworkOfferingId, null, 0L); + UsageEventUtils.saveUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), networkOfferingId, null, isDefault); } txn.commit(); } else { diff --git a/server/src/com/cloud/network/NetworkStateListener.java b/server/src/com/cloud/network/NetworkStateListener.java new file mode 100644 index 00000000000..130063348eb --- /dev/null +++ b/server/src/com/cloud/network/NetworkStateListener.java @@ -0,0 +1,90 @@ +package com.cloud.network; + +import com.cloud.event.EventCategory; +import com.cloud.event.dao.UsageEventDao; +import com.cloud.network.Network.Event; +import com.cloud.network.Network.State; +import com.cloud.network.dao.NetworkDao; +import com.cloud.server.ManagementServer; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.fsm.StateListener; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.log4j.Logger; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +public class NetworkStateListener implements StateListener { + + protected UsageEventDao _usageEventDao; + protected NetworkDao _networkDao; + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + + private static final Logger s_logger = Logger.getLogger(NetworkStateListener.class); + + public NetworkStateListener(UsageEventDao usageEventDao, NetworkDao networkDao) { + this._usageEventDao = usageEventDao; + this._networkDao = networkDao; + } + + @Override + public boolean preStateTransitionEvent(State oldState, Event event, State newState, Network vo, boolean status, Object opaque) { + pubishOnEventBus(event.name(), "preStateTransitionEvent", vo, oldState, newState); + return true; + } + + @Override + public boolean postStateTransitionEvent(State oldState, Event event, State newState, Network vo, boolean status, Object opaque) { + pubishOnEventBus(event.name(), "postStateTransitionEvent", vo, oldState, newState); + return true; + } + + private void pubishOnEventBus(String event, String status, Network vo, State oldState, State newState) { + + if (_eventBus == null) { + return; // no provider is configured to provide events bus, so just return + } + + String resourceName = getEntityFromClassName(Network.class.getName()); + org.apache.cloudstack.framework.events.Event eventMsg = new org.apache.cloudstack.framework.events.Event( + ManagementServer.Name, + EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(), + event, + resourceName, + vo.getUuid()); + Map eventDescription = new HashMap(); + eventDescription.put("resource", resourceName); + eventDescription.put("id", vo.getUuid()); + eventDescription.put("old-state", oldState.name()); + eventDescription.put("new-state", newState.name()); + eventMsg.setDescription(eventDescription); + try { + _eventBus.publish(eventMsg); + } catch (EventBusException e) { + s_logger.warn("Failed to publish state change event on the the event bus."); + } + } + + private String getEntityFromClassName(String entityClassName) { + int index = entityClassName.lastIndexOf("."); + String entityName = entityClassName; + if (index != -1) { + entityName = entityClassName.substring(index+1); + } + return entityName; + } +} diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 14b643b29b7..d0209d7f916 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -246,6 +246,7 @@ public class NetworkVO implements Network { return state; } + // don't use this directly when possible, use Network state machine instead public void setState(State state) { this.state = state; } diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index 1fefb75a360..18dcb6f7d98 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -24,10 +24,12 @@ import com.cloud.network.Network.GuestType; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.Network.State; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.fsm.StateDao; -public interface NetworkDao extends GenericDao { +public interface NetworkDao extends GenericDao , StateDao { List listByOwner(long ownerId); diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 29e2f818d55..2c5b46da577 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -28,6 +28,8 @@ import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.Network.State; +import com.cloud.network.Network.Event; import com.cloud.network.NetworkAccountDaoImpl; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkDomainVO; @@ -42,19 +44,18 @@ import com.cloud.offerings.dao.NetworkOfferingDaoImpl; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.GenericSearchBuilder; -import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.*; 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.Func; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SequenceFetcher; -import com.cloud.utils.db.Transaction; import com.cloud.utils.net.NetUtils; +import javax.ejb.Local; +import javax.persistence.TableGenerator; +import java.util.List; +import java.util.Map; +import java.util.Random; + @Local(value = NetworkDao.class) @DB(txn = false) public class NetworkDaoImpl extends GenericDaoBase implements NetworkDao { @@ -564,6 +565,20 @@ public class NetworkDaoImpl extends GenericDaoBase implements N return customSearch(sc, null).get(0); } + @Override + public boolean updateState(State currentState, Event event, State nextState, Network vo, Object data) { + // TODO: ensure this update is correct + Transaction txn = Transaction.currentTxn(); + txn.start(); + + NetworkVO networkVo = (NetworkVO) vo; + networkVo.setState(nextState); + super.update(networkVo.getId(), networkVo); + + txn.commit(); + return true; + } + @Override public List listNetworksByAccount(long accountId, long zoneId, Network.GuestType type, boolean isSystem) { SearchCriteria sc = OfferingAccountNetworkSearch.create(); @@ -580,7 +595,6 @@ public class NetworkDaoImpl extends GenericDaoBase implements N public List listRedundantNetworks() { SearchCriteria sc = AllFieldsSearch.create(); sc.setJoinParameters("offerings", "isRedundant", true); - return listBy(sc, null); } } diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index d4958f323e4..a3f60cb65f8 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -40,7 +40,7 @@ import com.cloud.configuration.dao.ConfigurationDao; 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.UsageEventUtils; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.InvalidParameterValueException; @@ -61,18 +61,12 @@ import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.element.FirewallServiceProvider; import com.cloud.network.element.NetworkACLServiceProvider; -import com.cloud.network.element.NetworkElement; import com.cloud.network.element.PortForwardingServiceProvider; import com.cloud.network.element.StaticNatServiceProvider; -import com.cloud.network.rules.FirewallManager; -import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.*; import com.cloud.network.rules.FirewallRule.FirewallRuleType; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.State; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.PortForwardingRuleVO; -import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.vpc.VpcManager; import com.cloud.projects.Project.ListProjectResourcesCriteria; @@ -88,17 +82,18 @@ import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.*; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.UserVmVO; import com.cloud.vm.dao.UserVmDao; +import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.*; @Local(value = { FirewallService.class, FirewallManager.class}) public class FirewallManagerImpl implements FirewallService, FirewallManager, NetworkRuleApplier, Manager { @@ -709,8 +704,8 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ne } if (generateUsageEvent && needUsageEvent) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), + null, rule.getClass().getName(), rule.getUuid()); } txn.commit(); diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index f8a8a95ec05..bd6305d745c 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -20,17 +20,16 @@ import java.util.List; import javax.ejb.Local; +import com.cloud.event.ActionEventUtils; import org.apache.log4j.Logger; import com.cloud.configuration.Config; -import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.dao.DataCenterDao; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; @@ -42,9 +41,7 @@ import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetwork.IsolationMethod; -import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offering.NetworkOffering; @@ -142,7 +139,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { } implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag)); - EventUtils.saveEvent(UserContext.current().getCallerUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: "+vnet+ " Network Id: "+config.getId(), 0); + ActionEventUtils.onCompletedActionEvent(UserContext.current().getCallerUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(), 0); } else { vlanTag = Integer.parseInt(config.getBroadcastUri().getHost()); implemented.setBroadcastUri(config.getBroadcastUri()); diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index 95878859598..e5371f50095 100755 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -19,12 +19,12 @@ package com.cloud.network.guru; import java.util.ArrayList; import java.util.List; import java.util.Random; -import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.ejb.Local; +import com.cloud.event.ActionEventUtils; import org.apache.log4j.Logger; import com.cloud.configuration.Config; @@ -36,7 +36,6 @@ import com.cloud.dc.dao.VlanDao; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; @@ -298,8 +297,8 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur "part of network " + network + " implement ", DataCenter.class, dcId); } implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vnet)); - EventUtils.saveEvent(UserContext.current().getCallerUserId(), network.getAccountId(), - EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: "+vnet+ " Network Id: "+network.getId(), 0); + ActionEventUtils.onCompletedActionEvent(UserContext.current().getCallerUserId(), network.getAccountId(), + EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + network.getId(), 0); } else { implemented.setBroadcastUri(network.getBroadcastUri()); } @@ -433,9 +432,9 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur s_logger.debug("Releasing vnet for the network id=" + profile.getId()); _dcDao.releaseVnet(profile.getBroadcastUri().getHost(), profile.getDataCenterId(), profile.getPhysicalNetworkId(), profile.getAccountId(), profile.getReservationId()); - EventUtils.saveEvent(UserContext.current().getCallerUserId(), profile.getAccountId(), + ActionEventUtils.onCompletedActionEvent(UserContext.current().getCallerUserId(), profile.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_RELEASE, "Released Zone Vlan: " - +profile.getBroadcastUri().getHost()+" for Network: "+profile.getId(), 0); + + profile.getBroadcastUri().getHost() + " for Network: " + profile.getId(), 0); } profile.setBroadcastUri(null); } diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index 482c1fe9b88..8e47545974c 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -30,6 +30,7 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; +import com.cloud.event.UsageEventUtils; import org.apache.cloudstack.api.command.user.loadbalancer.*; import org.apache.log4j.Logger; @@ -47,7 +48,6 @@ import com.cloud.dc.dao.VlanDao; 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.InsufficientAddressCapacityException; @@ -93,7 +93,6 @@ import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.element.LoadBalancingServiceProvider; -import com.cloud.network.element.NetworkElement; import com.cloud.network.lb.LoadBalancingRule.LbAutoScalePolicy; import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup; import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmProfile; @@ -871,8 +870,8 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (generateUsageEvent) { // Generate usage event right after all rules were marked for revoke - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(), null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(), + null, LoadBalancingRule.class.getName(), lb.getUuid()); } txn.commit(); @@ -1104,8 +1103,8 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa } s_logger.debug("Load balancer " + newRule.getId() + " for Ip address id=" + sourceIpId + ", public port " + srcPortStart + ", private port " + defPortStart + " is added successfully."); UserContext.current().setEventDetails("Load balancer Id: " + newRule.getId()); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(), ipAddr.getDataCenterId(), newRule.getId(), null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(), + ipAddr.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(), newRule.getUuid()); txn.commit(); return newRule; diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index fe86a8ebc99..605ffd6e794 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -20,7 +20,7 @@ import com.cloud.configuration.ConfigurationManager; 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.UsageEventUtils; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.InsufficientAddressCapacityException; @@ -276,9 +276,9 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { throw new CloudRuntimeException("Unable to update the state to add for " + newRule); } UserContext.current().setEventDetails("Rule Id: " + newRule.getId()); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), - ipAddress.getDataCenterId(), newRule.getId(), null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), + ipAddress.getDataCenterId(), newRule.getId(), null, PortForwardingRule.class.getName(), + newRule.getUuid()); txn.commit(); return newRule; } catch (Exception e) { @@ -358,8 +358,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { throw new CloudRuntimeException("Unable to update the state to add for " + newRule); } UserContext.current().setEventDetails("Rule Id: " + newRule.getId()); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), 0, newRule.getId(), null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), 0, newRule.getId(), + null, FirewallRule.class.getName(), newRule.getUuid()); txn.commit(); StaticNatRule staticNatRule = new StaticNatRuleImpl(newRule, dstIp); diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index b564e3d5759..5635f52c43c 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -16,30 +16,6 @@ // under the License. package com.cloud.network.security; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Date; -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.TreeMap; -import java.util.TreeSet; -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.cloudstack.api.command.user.securitygroup.*; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.log4j.Logger; - import com.cloud.agent.AgentManager; import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.SecurityGroupRulesCmd; @@ -47,33 +23,20 @@ import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto; import com.cloud.agent.manager.Commands; import com.cloud.api.query.dao.SecurityGroupJoinDao; import com.cloud.api.query.vo.SecurityGroupJoinVO; - -import org.apache.cloudstack.api.command.user.securitygroup.RevokeSecurityGroupEgressCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; 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.UsageEventDao; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceInUseException; +import com.cloud.event.UsageEventUtils; +import com.cloud.exception.*; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkModel; import com.cloud.network.security.SecurityGroupWork.Step; import com.cloud.network.security.SecurityRule.SecurityRuleType; -import com.cloud.network.security.dao.SecurityGroupDao; -import com.cloud.network.security.dao.SecurityGroupRuleDao; -import com.cloud.network.security.dao.SecurityGroupRulesDao; -import com.cloud.network.security.dao.SecurityGroupVMMapDao; -import com.cloud.network.security.dao.SecurityGroupWorkDao; -import com.cloud.network.security.dao.VmRulesetLogDao; -import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.network.security.dao.*; import com.cloud.projects.ProjectManager; import com.cloud.server.ManagementServer; import com.cloud.tags.dao.ResourceTagDao; @@ -85,7 +48,6 @@ import com.cloud.user.dao.AccountDao; import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; @@ -93,26 +55,26 @@ import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.utils.net.NetUtils; -import com.cloud.vm.Nic; -import com.cloud.vm.NicProfile; -import com.cloud.vm.UserVmManager; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; +import com.cloud.vm.*; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; - import edu.emory.mathcs.backport.java.util.Collections; +import org.apache.cloudstack.api.command.user.securitygroup.*; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; @Local(value = { SecurityGroupManager.class, SecurityGroupService.class }) public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityGroupService, Manager, StateListener { @@ -159,8 +121,6 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG @Inject ProjectManager _projectMgr; @Inject - UsageEventDao _usageEventDao; - @Inject ResourceTagDao _resourceTagDao; ScheduledExecutorService _executorPool; @@ -460,8 +420,9 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG // For each group, find the security rules that allow the group for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao //Add usage events for security group assign - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SECURITY_GROUP_ASSIGN, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), mapVO.getSecurityGroupId()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_ASSIGN, vm.getAccountId(), + vm.getDataCenterIdToDeployIn(), vm.getId(), mapVO.getSecurityGroupId(), + vm.getClass().getName(), vm.getUuid()); List allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); // For each security rule that allows a group that the vm belongs to, find the group it belongs to @@ -476,8 +437,9 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG // For each group, find the security rules rules that allow the group for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao //Add usage events for security group remove - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SECURITY_GROUP_REMOVE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), mapVO.getSecurityGroupId()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_REMOVE, + vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), mapVO.getSecurityGroupId(), + vm.getClass().getName(), vm.getUuid()); List allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); // For each security rule that allows a group that the vm belongs to, find the group it belongs to diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index e360bcae8ad..858c3624b3f 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -16,44 +16,24 @@ // under the License. package com.cloud.network.vpn; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.api.command.user.vpn.ListVpnUsersCmd; -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.command.user.vpn.ListRemoteAccessVpnsCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; +import com.cloud.event.UsageEventUtils; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.AccountLimitException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.IPAddressVO; -import com.cloud.network.Network; +import com.cloud.network.*; import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.RemoteAccessVpn; -import com.cloud.network.RemoteAccessVpnVO; -import com.cloud.network.VpnUser; import com.cloud.network.VpnUser.State; -import com.cloud.network.VpnUserVO; import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.dao.VpnUserDao; -import com.cloud.network.element.NetworkElement; import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.rules.FirewallManager; import com.cloud.network.rules.FirewallRule; @@ -74,14 +54,19 @@ 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.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.*; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.Transaction; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.command.user.vpn.ListRemoteAccessVpnsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnUsersCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; @Local(value = RemoteAccessVpnService.class) public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manager { @@ -281,8 +266,8 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag for(VpnUserVO user : vpnUsers){ // VPN_USER_REMOVE event is already generated for users in Revoke state if(user.getState() != VpnUser.State.Revoke){ - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), + 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid()); } } if (vpnFwRules != null) { @@ -333,8 +318,8 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } VpnUser user = _vpnUsersDao.persist(new VpnUserVO(vpnOwnerId, owner.getDomainId(), username, password)); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), + user.getUsername(), user.getClass().getName(), user.getUuid()); txn.commit(); return user; } @@ -350,8 +335,8 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag txn.start(); user.setState(State.Revoke); _vpnUsersDao.update(user.getId(), user); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), + user.getUsername(), user.getClass().getName(), user.getUuid()); txn.commit(); return true; } @@ -407,8 +392,8 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag List vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); for(VpnUserVO user : vpnUsers){ if(user.getState() != VpnUser.State.Revoke){ - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, + user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid()); } } txn.commit(); @@ -483,8 +468,8 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); _vpnUsersDao.remove(user.getId()); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), + 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid()); txn.commit(); } s_logger.warn("Failed to apply vpn for user " + user.getUsername() + ", accountId=" + user.getAccountId()); diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 40c55084ea9..0b5c53113ba 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -29,7 +29,6 @@ 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.Set; @@ -42,6 +41,7 @@ import java.util.concurrent.TimeUnit; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; +import com.cloud.event.ActionEventUtils; import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; @@ -60,7 +60,6 @@ import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd; import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; -import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; @@ -128,7 +127,6 @@ import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.ConcurrentOperationException; @@ -230,7 +228,6 @@ import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SSHKeysHelper; import com.cloud.vm.ConsoleProxyVO; -import com.cloud.vm.DomainRouterVO; import com.cloud.vm.InstanceGroupVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.UserVmVO; @@ -2422,12 +2419,12 @@ public class ManagementServerImpl implements ManagementServer { @Override public Long saveStartedEvent(Long userId, Long accountId, String type, String description, long startEventId) { - return EventUtils.saveStartedEvent(userId, accountId, type, description, startEventId); + return ActionEventUtils.onStartedActionEvent(userId, accountId, type, description, startEventId); } @Override public Long saveCompletedEvent(Long userId, Long accountId, String level, String type, String description, long startEventId) { - return EventUtils.saveEvent(userId, accountId, level, type, description, startEventId); + return ActionEventUtils.onCompletedActionEvent(userId, accountId, level, type, description, startEventId); } @Override diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 07f4d8ac7cb..5a799f9c87b 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -16,68 +16,14 @@ // 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.cloudstack.api.command.admin.storage.*; -import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; -import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; -import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd; -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.storage.ResizeVolumeCommand; -import com.cloud.agent.api.storage.ResizeVolumeAnswer; +import com.cloud.agent.api.*; +import com.cloud.agent.api.storage.*; 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 org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; import com.cloud.async.AsyncJobManager; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; @@ -104,21 +50,9 @@ 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.UsageEventUtils; 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.exception.*; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; @@ -140,32 +74,17 @@ 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.VMTemplateS3Dao; -import com.cloud.storage.dao.VMTemplateSwiftDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeHostDao; +import com.cloud.storage.dao.*; import com.cloud.storage.download.DownloadMonitor; import com.cloud.storage.listener.StoragePoolMonitor; +import com.cloud.storage.listener.VolumeStateListener; import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.snapshot.SnapshotScheduler; 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.*; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; @@ -178,36 +97,35 @@ 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.GenericSearchBuilder; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.*; 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.*; 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; +import com.cloud.vm.dao.*; +import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; +import org.apache.cloudstack.api.command.admin.storage.DeletePoolCmd; +import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd; +import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.math.BigDecimal; +import java.net.*; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; @Local(value = { StorageManager.class, StorageService.class }) public class StorageManagerImpl implements StorageManager, Manager, ClusterManagerListener { @@ -301,8 +219,6 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @Inject protected ClusterDao _clusterDao; @Inject - protected UsageEventDao _usageEventDao; - @Inject protected VirtualMachineManager _vmMgr; @Inject protected DomainRouterDao _domrDao; @@ -653,9 +569,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag Pair volumeDetails = createVolumeFromSnapshot(volume, snapshot); if (volumeDetails != null) { createdVolume = volumeDetails.first(); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), createdVolume.getDataCenterId(), createdVolume.getId(), createdVolume.getName(), - createdVolume.getDiskOfferingId(), null, createdVolume.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), + createdVolume.getDataCenterId(), createdVolume.getId(), createdVolume.getName(), createdVolume.getDiskOfferingId(), + null, createdVolume.getSize(), Volume.class.getName(), createdVolume.getUuid()); } return createdVolume; } @@ -775,8 +691,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag volume.setPoolId(destPool.getId()); volume.setPodId(destPool.getPodId()); stateTransitTo(volume, Event.CopySucceeded); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), null, volume.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), + null, volume.getSize(), Volume.class.getName(), volume.getUuid()); _volumeHostDao.remove(volumeHostVO.getId()); txn.commit(); return volume; @@ -1050,6 +967,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag LocalStorageSearch.join("poolHost", storageHostSearch, storageHostSearch.entity().getPoolId(), LocalStorageSearch.entity().getId(), JoinBuilder.JoinType.INNER); LocalStorageSearch.and("type", LocalStorageSearch.entity().getPoolType(), SearchCriteria.Op.IN); LocalStorageSearch.done(); + + Volume.State.getStateMachine().registerListener( new VolumeStateListener()); + return true; } @@ -1967,8 +1887,8 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId); } - if (snapshotCheck.getStatus() != Snapshot.Status.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for volume creation"); + if (snapshotCheck.getState() != Snapshot.State.BackedUp) { + throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for volume creation"); } diskOfferingId = snapshotCheck.getDiskOfferingId(); @@ -2058,9 +1978,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag volume = _volsDao.persist(volume); if(cmd.getSnapshotId() == null){ - //for volume created from snapshot, create usage event after volume creation - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId, null, size); - _usageEventDao.persist(usageEvent); + //for volume created from snapshot, create usage event after volume creation + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId, null, size, + Volume.class.getName(), volume.getUuid()); } UserContext.current().setEventDetails("Volume Id: " + volume.getId()); @@ -2305,8 +2226,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Decrement the resource count for volumes belonging user VM's only _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume); // Log usage event for volumes belonging user VM's only - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), + Volume.class.getName(), volume.getUuid()); } try { @@ -2471,7 +2393,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } // remove snapshots in Error state - List snapshots = _snapshotDao.listAllByStatus(Snapshot.Status.Error); + List snapshots = _snapshotDao.listAllByStatus(Snapshot.State.Error); for (SnapshotVO snapshotVO : snapshots) { try{ _snapshotDao.expunge(snapshotVO.getId()); @@ -3140,10 +3062,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Save usage event and update resource count for user vm volumes if (vm instanceof UserVm) { - - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offering.getId(), null, size); - _usageEventDao.persist(usageEvent); - + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), + vol.getDataCenterId(), vol.getId(), vol.getName(), offering.getId(), null, size, + Volume.class.getName(), vol.getUuid()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume); } return toDiskProfile(vol, offering); @@ -3204,9 +3125,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag offeringId = offering.getId(); } - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offeringId, template.getId(), - vol.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), + vol.getDataCenterId(), vol.getId(), vol.getName(), offeringId, template.getId(), + vol.getSize(), Volume.class.getName(), vol.getUuid()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume); } diff --git a/server/src/com/cloud/storage/dao/SnapshotDao.java b/server/src/com/cloud/storage/dao/SnapshotDao.java index b32d2782b6a..3b961f6fa89 100644 --- a/server/src/com/cloud/storage/dao/SnapshotDao.java +++ b/server/src/com/cloud/storage/dao/SnapshotDao.java @@ -16,15 +16,16 @@ // under the License. package com.cloud.storage.dao; -import java.util.List; - import com.cloud.storage.Snapshot; import com.cloud.storage.Snapshot.Type; import com.cloud.storage.SnapshotVO; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; -public interface SnapshotDao extends GenericDao { +import java.util.List; + +public interface SnapshotDao extends GenericDao, StateDao { List listByVolumeId(long volumeId); List listByVolumeId(Filter filter, long volumeId); SnapshotVO findNextSnapshot(long parentSnapId); @@ -39,7 +40,7 @@ public interface SnapshotDao extends GenericDao { List listByHostId(Filter filter, long hostId); List listByHostId(long hostId); public Long countSnapshotsForAccount(long accountId); - List listByInstanceId(long instanceId, Snapshot.Status... status); - List listByStatus(long volumeId, Snapshot.Status... status); - List listAllByStatus(Snapshot.Status... status); + List listByInstanceId(long instanceId, Snapshot.State... status); + List listByStatus(long volumeId, Snapshot.State... status); + List listAllByStatus(Snapshot.State... status); } diff --git a/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java b/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java index 65e2f5f1d76..3fe1aba5a98 100644 --- a/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java +++ b/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java @@ -16,33 +16,27 @@ // under the License. package com.cloud.storage.dao; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.List; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.storage.Snapshot; +import com.cloud.storage.Snapshot.Event; +import com.cloud.storage.Snapshot.State; import com.cloud.storage.Snapshot.Type; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.*; 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.Func; -import com.cloud.utils.db.Transaction; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.dao.VMInstanceDaoImpl; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; @Local (value={SnapshotDao.class}) public class SnapshotDaoImpl extends GenericDaoBase implements SnapshotDao { @@ -113,7 +107,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements public List listByHostId(Filter filter, long hostId ) { SearchCriteria sc = HostIdSearch.create(); sc.setParameters("hostId", hostId); - sc.setParameters("status", Snapshot.Status.BackedUp); + sc.setParameters("status", Snapshot.State.BackedUp); return listBy(sc, filter); } @@ -145,7 +139,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements HostIdSearch = createSearchBuilder(); HostIdSearch.and("hostId", HostIdSearch.entity().getSecHostId(), SearchCriteria.Op.EQ); - HostIdSearch.and("status", HostIdSearch.entity().getStatus(), SearchCriteria.Op.EQ); + HostIdSearch.and("status", HostIdSearch.entity().getState(), SearchCriteria.Op.EQ); HostIdSearch.done(); VolumeIdTypeSearch = createSearchBuilder(); @@ -172,7 +166,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements StatusSearch = createSearchBuilder(); StatusSearch.and("volumeId", StatusSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN); + StatusSearch.and("status", StatusSearch.entity().getState(), SearchCriteria.Op.IN); StatusSearch.done(); CountSnapshotsByAccount = createSearchBuilder(Long.class); @@ -182,7 +176,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements CountSnapshotsByAccount.done(); InstanceIdSearch = createSearchBuilder(); - InstanceIdSearch.and("status", InstanceIdSearch.entity().getStatus(), SearchCriteria.Op.IN); + InstanceIdSearch.and("status", InstanceIdSearch.entity().getState(), SearchCriteria.Op.IN); SearchBuilder instanceSearch = _instanceDao.createSearchBuilder(); instanceSearch.and("instanceId", instanceSearch.entity().getId(), SearchCriteria.Op.EQ); @@ -274,7 +268,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements } @Override - public List listByInstanceId(long instanceId, Snapshot.Status... status) { + public List listByInstanceId(long instanceId, Snapshot.State... status) { SearchCriteria sc = this.InstanceIdSearch.create(); if (status != null && status.length != 0) { @@ -287,7 +281,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements } @Override - public List listByStatus(long volumeId, Snapshot.Status... status) { + public List listByStatus(long volumeId, Snapshot.State... status) { SearchCriteria sc = this.StatusSearch.create(); sc.setParameters("volumeId", volumeId); sc.setParameters("status", (Object[])status); @@ -309,9 +303,20 @@ public class SnapshotDaoImpl extends GenericDaoBase implements } @Override - public List listAllByStatus(Snapshot.Status... status) { + public List listAllByStatus(Snapshot.State... status) { SearchCriteria sc = this.StatusSearch.create(); sc.setParameters("status", (Object[])status); return listBy(sc, null); } + + @Override + public boolean updateState(State currentState, Event event, State nextState, Snapshot snapshot, Object data) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + SnapshotVO snapshotVO = (SnapshotVO)snapshot; + snapshotVO.setStatus(nextState); + super.update(snapshotVO.getId(), snapshotVO); + txn.commit(); + return true; + } } diff --git a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java index 27367779650..cf51567c951 100755 --- a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java +++ b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java @@ -16,36 +16,14 @@ // under the License. package com.cloud.storage.download; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Timer; -import java.util.concurrent.ConcurrentHashMap; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; -import com.cloud.agent.api.storage.DeleteTemplateCommand; -import com.cloud.agent.api.storage.DeleteVolumeCommand; -import com.cloud.agent.api.storage.DownloadCommand; -import com.cloud.agent.api.storage.ListVolumeAnswer; -import com.cloud.agent.api.storage.ListVolumeCommand; +import com.cloud.agent.api.storage.*; import com.cloud.agent.api.storage.DownloadCommand.Proxy; import com.cloud.agent.api.storage.DownloadCommand.ResourceType; -import com.cloud.agent.api.storage.DownloadProgressCommand; import com.cloud.agent.api.storage.DownloadProgressCommand.RequestType; -import com.cloud.agent.api.storage.ListTemplateAnswer; -import com.cloud.agent.api.storage.ListTemplateCommand; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.configuration.Config; @@ -54,8 +32,7 @@ import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; -import com.cloud.event.dao.UsageEventDao; +import com.cloud.event.UsageEventUtils; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.StorageUnavailableException; @@ -65,26 +42,9 @@ import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.resource.ResourceManager; import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.StorageManager; -import com.cloud.storage.SwiftVO; -import com.cloud.storage.VMTemplateHostVO; -import com.cloud.storage.VMTemplateStorageResourceAssoc; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeHostVO; -import com.cloud.storage.VolumeVO; +import com.cloud.storage.*; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; -import com.cloud.storage.Volume.Event; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.VMTemplateZoneVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.storage.dao.SwiftDao; -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.VMTemplateZoneDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeHostDao; +import com.cloud.storage.dao.*; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.swift.SwiftManager; import com.cloud.storage.template.TemplateConstants; @@ -92,19 +52,21 @@ import com.cloud.storage.template.TemplateInfo; import com.cloud.user.Account; import com.cloud.user.ResourceLimitService; import com.cloud.utils.component.Inject; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.*; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.fsm.NoTransitionException; import com.cloud.vm.SecondaryStorageVm; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.UserVmManager; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.SecondaryStorageVmDao; import edu.emory.mathcs.backport.java.util.Collections; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; @Local(value={DownloadMonitor.class}) @@ -147,11 +109,6 @@ public class DownloadMonitorImpl implements DownloadMonitor { ConfigurationDao _configDao; @Inject UserVmManager _vmMgr; - - - @Inject - private UsageEventDao _usageEventDao; - @Inject private ClusterDao _clusterDao; @Inject @@ -517,8 +474,9 @@ public class DownloadMonitorImpl implements DownloadMonitor { eventType = EventTypes.EVENT_ISO_CREATE; } if(template.getAccountId() != Account.ACCOUNT_ID_SYSTEM){ - UsageEventVO usageEvent = new UsageEventVO(eventType, template.getAccountId(), host.getDataCenterId(), template.getId(), template.getName(), null, template.getSourceTemplateId() , size); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(eventType, template.getAccountId(), host.getDataCenterId(), + template.getId(), template.getName(), null, template.getSourceTemplateId(), size, + template.getClass().getName(), template.getUuid()); } } txn.commit(); @@ -550,8 +508,8 @@ public class DownloadMonitorImpl implements DownloadMonitor { } String eventType = EventTypes.EVENT_VOLUME_UPLOAD; if(volume.getAccountId() != Account.ACCOUNT_ID_SYSTEM){ - UsageEventVO usageEvent = new UsageEventVO(eventType, volume.getAccountId(), host.getDataCenterId(), volume.getId(), volume.getName(), null, 0l , size); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(eventType, volume.getAccountId(), host.getDataCenterId(), + volume.getId(), volume.getName(), null, 0l, size, volume.getClass().getName(), volume.getUuid()); } }else if (dnldStatus == Status.DOWNLOAD_ERROR || dnldStatus == Status.ABANDONED || dnldStatus == Status.UNKNOWN){ //Decrement the volume count diff --git a/server/src/com/cloud/storage/listener/SnapshotStateListener.java b/server/src/com/cloud/storage/listener/SnapshotStateListener.java new file mode 100644 index 00000000000..2b19887e83a --- /dev/null +++ b/server/src/com/cloud/storage/listener/SnapshotStateListener.java @@ -0,0 +1,85 @@ +package com.cloud.storage.listener; + +import com.cloud.event.EventCategory; +import com.cloud.storage.Snapshot; +import com.cloud.storage.Snapshot.Event; +import com.cloud.storage.Snapshot.State; +import com.cloud.server.ManagementServer; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.fsm.StateListener; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.log4j.Logger; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +public class SnapshotStateListener implements StateListener { + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + + private static final Logger s_logger = Logger.getLogger(VolumeStateListener.class); + + public SnapshotStateListener() { + + } + + @Override + public boolean preStateTransitionEvent(State oldState, Event event, State newState, Snapshot vo, boolean status, Object opaque) { + pubishOnEventBus(event.name(), "preStateTransitionEvent", vo, oldState, newState); + return true; + } + + @Override + public boolean postStateTransitionEvent(State oldState, Event event, State newState, Snapshot vo, boolean status, Object opaque) { + pubishOnEventBus(event.name(), "postStateTransitionEvent", vo, oldState, newState); + return true; + } + + private void pubishOnEventBus(String event, String status, Snapshot vo, State oldState, State newState) { + + if (_eventBus == null) { + return; // no provider is configured to provide events bus, so just return + } + + String resourceName = getEntityFromClassName(Snapshot.class.getName()); + org.apache.cloudstack.framework.events.Event eventMsg = new org.apache.cloudstack.framework.events.Event( + ManagementServer.Name, + EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(), + event, + resourceName, + vo.getUuid()); + Map eventDescription = new HashMap(); + eventDescription.put("resource", resourceName); + eventDescription.put("id", vo.getUuid()); + eventDescription.put("old-state", oldState.name()); + eventDescription.put("new-state", newState.name()); + eventMsg.setDescription(eventDescription); + try { + _eventBus.publish(eventMsg); + } catch (EventBusException e) { + s_logger.warn("Failed to publish state change event on the the event bus."); + } + } + + private String getEntityFromClassName(String entityClassName) { + int index = entityClassName.lastIndexOf("."); + String entityName = entityClassName; + if (index != -1) { + entityName = entityClassName.substring(index+1); + } + return entityName; + } +} diff --git a/server/src/com/cloud/storage/listener/VolumeStateListener.java b/server/src/com/cloud/storage/listener/VolumeStateListener.java new file mode 100644 index 00000000000..c460016f90a --- /dev/null +++ b/server/src/com/cloud/storage/listener/VolumeStateListener.java @@ -0,0 +1,85 @@ +package com.cloud.storage.listener; + +import com.cloud.event.EventCategory; +import com.cloud.storage.Volume; +import com.cloud.storage.Volume.Event; +import com.cloud.storage.Volume.State; +import com.cloud.server.ManagementServer; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.fsm.StateListener; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.log4j.Logger; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +public class VolumeStateListener implements StateListener { + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + + private static final Logger s_logger = Logger.getLogger(VolumeStateListener.class); + + public VolumeStateListener() { + + } + + @Override + public boolean preStateTransitionEvent(State oldState, Event event, State newState, Volume vo, boolean status, Object opaque) { + pubishOnEventBus(event.name(), "preStateTransitionEvent", vo, oldState, newState); + return true; + } + + @Override + public boolean postStateTransitionEvent(State oldState, Event event, State newState, Volume vo, boolean status, Object opaque) { + pubishOnEventBus(event.name(), "postStateTransitionEvent", vo, oldState, newState); + return true; + } + + private void pubishOnEventBus(String event, String status, Volume vo, State oldState, State newState) { + + if (_eventBus == null) { + return; // no provider is configured to provide events bus, so just return + } + + String resourceName = getEntityFromClassName(Volume.class.getName()); + org.apache.cloudstack.framework.events.Event eventMsg = new org.apache.cloudstack.framework.events.Event( + ManagementServer.Name, + EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(), + event, + resourceName, + vo.getUuid()); + Map eventDescription = new HashMap(); + eventDescription.put("resource", resourceName); + eventDescription.put("id", vo.getUuid()); + eventDescription.put("old-state", oldState.name()); + eventDescription.put("new-state", newState.name()); + eventMsg.setDescription(eventDescription); + try { + _eventBus.publish(eventMsg); + } catch (EventBusException e) { + s_logger.warn("Failed to state change event on the the event bus."); + } + } + + private String getEntityFromClassName(String entityClassName) { + int index = entityClassName.lastIndexOf("."); + String entityName = entityClassName; + if (index != -1) { + entityName = entityClassName.substring(index+1); + } + return entityName; + } +} diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 15d8c53d06f..66eb8e16b21 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -16,37 +16,12 @@ // under the License. package com.cloud.storage.snapshot; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd; -import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd; -import org.apache.log4j.Logger; - import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.BackupSnapshotAnswer; -import com.cloud.agent.api.BackupSnapshotCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.DeleteSnapshotBackupCommand; -import com.cloud.agent.api.DeleteSnapshotsDirCommand; -import com.cloud.agent.api.DownloadSnapshotFromS3Command; -import com.cloud.agent.api.ManageSnapshotAnswer; -import com.cloud.agent.api.ManageSnapshotCommand; -import com.cloud.agent.api.downloadSnapshotFromSwiftCommand; +import com.cloud.agent.api.*; import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.alert.AlertManager; -import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; -import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; import com.cloud.configuration.Config; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; @@ -55,11 +30,7 @@ import com.cloud.dc.DataCenter; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.domain.dao.DomainDao; -import com.cloud.event.ActionEvent; -import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; -import com.cloud.event.EventVO; -import com.cloud.event.UsageEventVO; +import com.cloud.event.*; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.InvalidParameterValueException; @@ -69,44 +40,21 @@ import com.cloud.exception.StorageUnavailableException; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.org.Grouping; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.resource.ResourceManager; import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.storage.Snapshot; -import com.cloud.storage.Snapshot.Status; +import com.cloud.storage.*; import com.cloud.storage.Snapshot.Type; -import com.cloud.storage.SnapshotPolicyVO; -import com.cloud.storage.SnapshotScheduleVO; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolVO; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotPolicyDao; -import com.cloud.storage.dao.SnapshotScheduleDao; -import com.cloud.storage.dao.StoragePoolDao; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.dao.*; +import com.cloud.storage.listener.SnapshotStateListener; import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.swift.SwiftManager; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.DomainManager; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.User; -import com.cloud.user.UserContext; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil.IntervalType; @@ -116,18 +64,24 @@ import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.*; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.fsm.NoTransitionException; +import com.cloud.utils.fsm.StateMachine2; 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.dao.UserVmDao; +import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd; +import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; +import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; +import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.*; @Local(value = { SnapshotManager.class, SnapshotService.class }) public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Manager { @@ -195,6 +149,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private int _deltaSnapshotMax; private int _backupsnapshotwait; + private StateMachine2 _snapshotFsm; + protected SearchBuilder PolicySnapshotSearch; protected SearchBuilder PoliciesForSnapSearch; @@ -259,6 +215,13 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (snapshot == null) { throw new CloudRuntimeException("Can not find snapshot " + snapshotId); } + + try { + stateTransitTo(snapshot, Snapshot.Event.CreateRequested); + } catch (NoTransitionException nte) { + s_logger.debug("Failed to update snapshot state due to " + nte.getMessage()); + } + // Send a ManageSnapshotCommand to the agent String vmName = _storageMgr.getVmNameOnVolume(volume); long volumeId = volume.getId(); @@ -289,14 +252,16 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (preSnapshotPath != null && preSnapshotPath.equals(answer.getSnapshotPath())) { // empty snapshot s_logger.debug("CreateSnapshot: this is empty snapshot "); - snapshot.setPath(preSnapshotPath); - snapshot.setBackupSnapshotId(preSnapshotVO.getBackupSnapshotId()); - snapshot.setSwiftId(preSnapshotVO.getSwiftId()); - - snapshot.setStatus(Snapshot.Status.BackedUp); - snapshot.setPrevSnapshotId(preId); - snapshot.setSecHostId(preSnapshotVO.getSecHostId()); - _snapshotDao.update(snapshotId, snapshot); + try { + snapshot.setPath(preSnapshotPath); + snapshot.setBackupSnapshotId(preSnapshotVO.getBackupSnapshotId()); + snapshot.setSwiftId(preSnapshotVO.getSwiftId()); + snapshot.setPrevSnapshotId(preId); + snapshot.setSecHostId(preSnapshotVO.getSecHostId()); + stateTransitTo(snapshot, Snapshot.Event.OperationNotPerformed); + } catch (NoTransitionException nte) { + s_logger.debug("CreateSnapshot: failed to update state of snapshot due to " + nte.getMessage()); + } } else { long preSnapshotId = 0; @@ -346,6 +311,11 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (answer != null) { s_logger.error(answer.getDetails()); } + try { + stateTransitTo(snapshot, Snapshot.Event.OperationFailed); + } catch (NoTransitionException nte) { + s_logger.debug("Failed to update snapshot state due to " + nte.getMessage()); + } throw new CloudRuntimeException("Creating snapshot for volume " + volumeId + " on primary storage failed."); } @@ -410,7 +380,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } if(userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) { - List activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.Status.Creating, Snapshot.Status.CreatedOnPrimary, Snapshot.Status.BackingUp); + List activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp); if(activeSnapshots.size() > 1) throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later"); } @@ -419,19 +389,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma snapshot = createSnapshotOnPrimary(volume, policyId, snapshotId); if (snapshot != null) { - if (snapshot.getStatus() == Snapshot.Status.CreatedOnPrimary) { + if (snapshot.getState() == Snapshot.State.CreatedOnPrimary) { backedUp = backupSnapshotToSecondaryStorage(snapshot); - } else if (snapshot.getStatus() == Snapshot.Status.BackedUp) { + } else if (snapshot.getState() == Snapshot.State.BackedUp) { // For empty snapshot we set status to BackedUp in createSnapshotOnPrimary backedUp = true; } else { - snapshot.setStatus(Status.Error); - _snapshotDao.update(snapshot.getId(), snapshot); throw new CloudRuntimeException("Failed to create snapshot: " + snapshot + " on primary storage"); } if (!backedUp) { - snapshot.setStatus(Status.Error); - _snapshotDao.update(snapshot.getId(), snapshot); throw new CloudRuntimeException("Created snapshot: " + snapshot + " on primary but failed to backup on secondary"); } } else { @@ -444,23 +410,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma //Check if the snapshot was removed while backingUp. If yes, do not log snapshot create usage event SnapshotVO freshSnapshot = _snapshotDao.findById(snapshot.getId()); if ((freshSnapshot != null) && backedUp) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, - volume.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), + snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, + volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid()); } if( !backedUp ) { - snapshot.setStatus(Status.Error); - _snapshotDao.update(snapshot.getId(), snapshot); } else { _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot); } - } else { - snapshot = _snapshotDao.findById(snapshotId); - if (snapshot != null) { - snapshot.setStatus(Status.Error); - _snapshotDao.update(snapshotId, snapshot); - } } /* @@ -478,9 +436,12 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private SnapshotVO updateDBOnCreate(Long id, String snapshotPath, long preSnapshotId) { SnapshotVO createdSnapshot = _snapshotDao.findByIdIncludingRemoved(id); createdSnapshot.setPath(snapshotPath); - createdSnapshot.setStatus(Snapshot.Status.CreatedOnPrimary); createdSnapshot.setPrevSnapshotId(preSnapshotId); - _snapshotDao.update(id, createdSnapshot); + try { + stateTransitTo(createdSnapshot, Snapshot.Event.OperationSucceeded); + } catch (NoTransitionException nte) { + s_logger.debug("Faile to update state of snapshot due to " + nte.getMessage()); + } return createdSnapshot; } @@ -622,9 +583,11 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma throw new CloudRuntimeException("Can not acquire lock for snapshot: " + ss); } try { - - snapshot.setStatus(Snapshot.Status.BackingUp); - _snapshotDao.update(snapshot.getId(), snapshot); + try { + stateTransitTo(snapshot, Snapshot.Event.BackupToSecondary); + } catch (NoTransitionException nte) { + s_logger.debug("Failed to update the state of snapshot while backing up snapshot"); + } long volumeId = snapshot.getVolumeId(); VolumeVO volume = _volsDao.lockRow(volumeId, true); @@ -705,10 +668,18 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (answer.isFull()) { snapshot.setPrevSnapshotId(0); } - snapshot.setStatus(Snapshot.Status.BackedUp); - _snapshotDao.update(snapshotId, snapshot); + try { + stateTransitTo(snapshot, Snapshot.Event.OperationSucceeded); + } catch (NoTransitionException nte) { + s_logger.debug("Failed to update the state of snapshot while backing up snapshot"); + } } else { + try { + stateTransitTo(snapshot, Snapshot.Event.OperationFailed); + } catch (NoTransitionException nte) { + s_logger.debug("Failed to update the state of snapshot while backing up snapshot"); + } s_logger.warn("Failed to back up snapshot on secondary storage, deleting the record from the DB"); _snapshotDao.remove(snapshotId); } @@ -766,8 +737,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma long oldSnapId = oldestSnapshot.getId(); s_logger.debug("Max snaps: " + policy.getMaxSnaps() + " exceeded for snapshot policy with Id: " + policyId + ". Deleting oldest snapshot: " + oldSnapId); if(deleteSnapshotInternal(oldSnapId)){ - //log Snapshot delete event - EventUtils.saveEvent(User.UID_SYSTEM, oldestSnapshot.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_SNAPSHOT_DELETE, "Successfully deleted oldest snapshot: " + oldSnapId, 0); + //log Snapshot delete event + ActionEventUtils.onCompletedActionEvent(User.UID_SYSTEM, oldestSnapshot.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_SNAPSHOT_DELETE, "Successfully deleted oldest snapshot: " + oldSnapId, 0); } snaps.remove(oldestSnapshot); } @@ -787,7 +758,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _accountMgr.checkAccess(caller, null, true, snapshotCheck); - if( !Status.BackedUp.equals(snapshotCheck.getStatus() ) ) { + if( !Snapshot.State.BackedUp.equals(snapshotCheck.getState() ) ) { throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status"); } @@ -812,9 +783,10 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Transaction txn = Transaction.currentTxn(); txn.start(); _snapshotDao.remove(snapshotId); - if (snapshot.getStatus() == Snapshot.Status.BackedUp) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, 0L); - _usageEventDao.persist(usageEvent); + if (snapshot.getState() == Snapshot.State.BackedUp) { + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), + snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, 0L, + snapshot.getClass().getName(), snapshot.getUuid()); } _resourceLimitMgr.decrementResourceCount(snapshot.getAccountId(), ResourceType.snapshot); txn.commit(); @@ -966,7 +938,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma SearchBuilder sb = _snapshotDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); + sb.and("status", sb.entity().getState(), SearchCriteria.Op.EQ); sb.and("volumeId", sb.entity().getVolumeId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); @@ -1115,9 +1087,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } // Log event after successful deletion - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), volume.getDataCenterId(), snapshot.getId(), snapshot.getName(), null, null, - volume.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), + volume.getDataCenterId(), snapshot.getId(), snapshot.getName(), null, null, + volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid()); } } } @@ -1452,6 +1424,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma s_logger.info("Snapshot Manager is configured."); + _snapshotFsm = Snapshot.State.getStateMachine(); + _snapshotFsm.registerListener(new SnapshotStateListener()); + return true; } @@ -1538,11 +1513,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma @Override public boolean canOperateOnVolume(VolumeVO volume) { - List snapshots = _snapshotDao.listByStatus(volume.getId(), Status.Creating, Status.CreatedOnPrimary, Status.BackingUp); + List snapshots = _snapshotDao.listByStatus(volume.getId(), Snapshot.State.Creating, + Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp); if (snapshots.size() > 0) { return false; } return true; } + protected boolean stateTransitTo(Snapshot snapshot, Snapshot.Event e) throws NoTransitionException { + return _snapshotFsm.transitTo(snapshot, e, null, _snapshotDao); + } } diff --git a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java index d7deb6fa74b..93898938c60 100644 --- a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java @@ -26,6 +26,7 @@ import java.util.TimerTask; import javax.ejb.Local; import javax.naming.ConfigurationException; +import com.cloud.event.ActionEventUtils; import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotCmd; import org.apache.log4j.Logger; @@ -39,7 +40,6 @@ import com.cloud.async.AsyncJobVO; import com.cloud.async.dao.AsyncJobDao; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.SnapshotScheduleVO; @@ -232,8 +232,8 @@ public class SnapshotSchedulerImpl implements SnapshotScheduler { tmpSnapshotScheduleVO = _snapshotScheduleDao.acquireInLockTable(snapshotScheId); - Long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, - EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:"+volumeId,0); + Long eventId = ActionEventUtils.onScheduledActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, + EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:" + volumeId, 0); Map params = new HashMap(); params.put(ApiConstants.VOLUME_ID, "" + volumeId); diff --git a/server/src/com/cloud/template/HyervisorTemplateAdapter.java b/server/src/com/cloud/template/HyervisorTemplateAdapter.java index c80d1de0fbf..81a482b73f5 100755 --- a/server/src/com/cloud/template/HyervisorTemplateAdapter.java +++ b/server/src/com/cloud/template/HyervisorTemplateAdapter.java @@ -16,28 +16,13 @@ // under the License. package com.cloud.template; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; -import java.util.List; - -import javax.ejb.Local; - -import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; -import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; -import org.apache.log4j.Logger; - import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.DeleteTemplateCommand; -import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; -import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.DataCenterVO; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; +import com.cloud.event.UsageEventUtils; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.host.HostVO; @@ -53,6 +38,15 @@ import com.cloud.user.Account; import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import java.net.*; +import java.util.List; @Local(value=TemplateAdapter.class) public class HyervisorTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter { @@ -202,8 +196,7 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem success = false; break; } - UsageEventVO usageEvent = new UsageEventVO(eventType, account.getId(), sZoneId, templateId, null); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(eventType, account.getId(), sZoneId, templateId, null, null, null); templateHostVO.setDestroyed(true); _tmpltHostDao.update(templateHostVO.getId(), templateHostVO); String installPath = templateHostVO.getInstallPath(); diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 1372111eac3..42106b3bdb5 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -16,41 +16,14 @@ // under the License. package com.cloud.template; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutorService; -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.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; -import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; -import org.apache.cloudstack.api.command.user.iso.*; -import org.apache.cloudstack.api.command.user.template.*; -import org.apache.log4j.Logger; - -import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.downloadTemplateFromSwiftToSecondaryStorageCommand; -import com.cloud.agent.api.uploadTemplateToSwiftFromSecondaryStorageCommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.to.SwiftTO; -import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; -import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; +import com.cloud.agent.api.uploadTemplateToSwiftFromSecondaryStorageCommand; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; import com.cloud.configuration.Config; @@ -63,7 +36,7 @@ import com.cloud.dc.dao.DataCenterDao; 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.UsageEventUtils; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.InvalidParameterValueException; @@ -77,51 +50,19 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuruManager; import com.cloud.projects.Project; import com.cloud.projects.ProjectManager; -import com.cloud.storage.LaunchPermissionVO; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage; +import com.cloud.storage.*; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.StoragePoolStatus; -import com.cloud.storage.StoragePoolVO; -import com.cloud.storage.Upload; import com.cloud.storage.Upload.Type; -import com.cloud.storage.UploadVO; -import com.cloud.storage.VMTemplateHostVO; -import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; -import com.cloud.storage.VMTemplateSwiftVO; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.VMTemplateZoneVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.LaunchPermissionDao; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.StoragePoolDao; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.storage.dao.UploadDao; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VMTemplateHostDao; -import com.cloud.storage.dao.VMTemplatePoolDao; -import com.cloud.storage.dao.VMTemplateS3Dao; -import com.cloud.storage.dao.VMTemplateSwiftDao; -import com.cloud.storage.dao.VMTemplateZoneDao; -import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.dao.*; import com.cloud.storage.download.DownloadMonitor; import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.swift.SwiftManager; import com.cloud.storage.upload.UploadMonitor; import com.cloud.template.TemplateAdapter.TemplateAdapterType; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountService; -import com.cloud.user.AccountVO; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.UserContext; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; @@ -132,12 +73,7 @@ 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.GlobalLock; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.*; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; @@ -145,6 +81,21 @@ import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.command.user.iso.*; +import org.apache.cloudstack.api.command.user.template.*; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.net.*; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; @Local(value={TemplateManager.class, TemplateService.class}) @@ -823,8 +774,8 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe _tmpltDao.addTemplateToZone(template, dstZoneId); if(account.getId() != Account.ACCOUNT_ID_SYSTEM){ - UsageEventVO usageEvent = new UsageEventVO(copyEventType, account.getId(), dstZoneId, tmpltId, null, null, null, srcTmpltHost.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(copyEventType, account.getId(), dstZoneId, tmpltId, null, null, null, srcTmpltHost.getSize(), + template.getClass().getName(), template.getUuid()); } return true; } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index b910a03f99b..f60d305ff21 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -36,6 +36,7 @@ import javax.crypto.spec.SecretKeySpec; import javax.ejb.Local; import javax.naming.ConfigurationException; +import com.cloud.event.ActionEventUtils; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker; @@ -64,7 +65,6 @@ import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; -import com.cloud.event.EventUtils; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.ConcurrentOperationException; @@ -1744,7 +1744,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public void logoutUser(Long userId) { UserAccount userAcct = _userAccountDao.findById(userId); if (userAcct != null) { - EventUtils.saveEvent(userId, userAcct.getAccountId(), userAcct.getDomainId(), EventTypes.EVENT_USER_LOGOUT, "user has logged out"); + ActionEventUtils.onActionEvent(userId, userAcct.getAccountId(), userAcct.getDomainId(), EventTypes.EVENT_USER_LOGOUT, "user has logged out"); } // else log some kind of error event? This likely means the user doesn't exist, or has been deleted... } @@ -1875,10 +1875,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.debug("User: " + username + " in domain " + domainId + " has successfully logged in"); } if (NetUtils.isValidIp(loginIpAddress)) { - EventUtils.saveEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, + ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, "user has logged in from IP Address " + loginIpAddress); } else { - EventUtils.saveEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, + ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, "user has logged in. The IP Address cannot be determined"); } return user; diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 3737450674d..969539c0b15 100644 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -54,7 +54,7 @@ import com.cloud.domain.DomainVO; 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.UsageEventUtils; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.*; import com.cloud.ha.HighAvailabilityManager; @@ -245,8 +245,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Inject protected LoadBalancingRulesManager _lbMgr; @Inject - protected UsageEventDao _usageEventDao; - @Inject protected SSHKeyPairDao _sshKeyPairDao; @Inject protected UserVmDetailsDao _vmDetailsDao; @@ -280,6 +278,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager PhysicalNetworkDao _physicalNetworkDao; @Inject VpcManager _vpcMgr; + @Inject + UsageEventDao _usageEventDao; protected ScheduledExecutorService _executor = null; protected int _expungeInterval; @@ -841,7 +841,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } @Override - @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true) + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true) public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) { Account caller = UserContext.current().getCaller(); if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) || (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) @@ -1372,9 +1372,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager offeringId = offering.getId(); } } - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, - volume.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, + volume.getSize(), Volume.class.getName(), volume.getUuid()); } } @@ -1640,8 +1640,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //check permissions _accountMgr.checkAccess(caller, null, true, snapshot); - if (snapshot.getStatus() != Snapshot.Status.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation"); + if (snapshot.getState() != Snapshot.State.BackedUp) { + throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for template creation"); } /* @@ -1888,9 +1888,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager templateHostVO.setPhysicalSize(answer.getphysicalSize()); _templateHostDao.persist(templateHostVO); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), secondaryStorageHost.getDataCenterId(), privateTemplate.getId(), - privateTemplate.getName(), null, privateTemplate.getSourceTemplateId(), templateHostVO.getSize()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), + secondaryStorageHost.getDataCenterId(), privateTemplate.getId(), + privateTemplate.getName(), null, privateTemplate.getSourceTemplateId(), + templateHostVO.getSize(), VirtualMachineTemplate.class.getName(), privateTemplate.getUuid()); txn.commit(); } } finally { @@ -2835,8 +2836,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } UserContext.current().setEventDetails("Vm Id: " + vm.getId()); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), + vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(), + VirtualMachine.class.getName(), vm.getUuid()); _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.user_vm); txn.commit(); @@ -3006,8 +3008,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); long isDefault = (nic.isDefaultNic()) ? 1 : 0; - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), network.getNetworkOfferingId(), null, isDefault); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), + vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), network.getNetworkOfferingId(), + null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); if (network.getTrafficType() == TrafficType.Guest) { originalIp = nic.getIp4Address(); guestNic = nic; @@ -3270,8 +3273,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List volumes = _volsDao.findByInstance(vmId); for (VolumeVO volume : volumes) { if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName()); - _usageEventDao.persist(usageEvent); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), + volume.getUuid()); } } @@ -3721,8 +3725,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Transaction txn = Transaction.currentTxn(); txn.start(); //generate destroy vm event for usage - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), - vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString())); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), + vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), + VirtualMachine.class.getName(), vm.getUuid()); // update resource counts _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.user_vm); @@ -3734,13 +3739,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // OS 2: update volume List volumes = _volsDao.findByInstance(cmd.getVmId()); for (VolumeVO volume : volumes) { - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName())); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid()); _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume); volume.setAccountId(newAccount.getAccountId()); _volsDao.persist(volume); _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume); - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize())); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), + volume.getDataCenterId(), volume.getId(), volume.getName(), + volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), + volume.getUuid()); //snapshots: mark these removed in db List snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId()); for (SnapshotVO snapshot: snapshots){ @@ -3750,8 +3758,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.user_vm); //generate usage events to account for this change - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), - vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString())); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), + vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), + VirtualMachine.class.getName(), vm.getUuid()); txn.commit(); diff --git a/server/src/com/cloud/vm/UserVmStateListener.java b/server/src/com/cloud/vm/UserVmStateListener.java index 4d9bcc563fd..786387ffe03 100644 --- a/server/src/com/cloud/vm/UserVmStateListener.java +++ b/server/src/com/cloud/vm/UserVmStateListener.java @@ -16,24 +16,48 @@ // under the License. package com.cloud.vm; -import java.util.List; - +import com.cloud.event.EventCategory; import com.cloud.event.EventTypes; -import com.cloud.event.UsageEventVO; +import com.cloud.event.UsageEventUtils; import com.cloud.event.dao.UsageEventDao; +import com.cloud.network.Network; import com.cloud.network.NetworkVO; import com.cloud.network.dao.NetworkDao; +import com.cloud.server.ManagementServer; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.fsm.StateListener; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.NicDao; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.log4j.Logger; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class UserVmStateListener implements StateListener { protected UsageEventDao _usageEventDao; protected NetworkDao _networkDao; protected NicDao _nicDao; - + private static final Logger s_logger = Logger.getLogger(UserVmStateListener.class); + + // get the event bus provider if configured + protected static EventBus _eventBus = null; + static { + Adapters eventBusImpls = ComponentLocator.getLocator(ManagementServer.Name).getAdapters(EventBus.class); + if (eventBusImpls != null) { + Enumeration eventBusenum = eventBusImpls.enumeration(); + if (eventBusenum != null && eventBusenum.hasMoreElements()) { + _eventBus = eventBusenum.nextElement(); // configure event bus if configured + } + } + } + public UserVmStateListener(UsageEventDao usageEventDao, NetworkDao networkDao, NicDao nicDao) { this._usageEventDao = usageEventDao; this._networkDao = networkDao; @@ -42,6 +66,7 @@ public class UserVmStateListener implements StateListener nics = _nicDao.listByVmId(vo.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); - usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vo.getAccountId(), vo.getDataCenterIdToDeployIn(), vo.getId(), null, network.getNetworkOfferingId(), null, 0L); - _usageEventDao.persist(usageEvent); + UsageEventUtils.saveUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vo.getAccountId(), vo.getDataCenterIdToDeployIn(), vo.getId(), null, network.getNetworkOfferingId(), null, 0L); } } else if (VirtualMachine.State.isVmDestroyed(oldState, event, newState)) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vo.getAccountId(), vo.getDataCenterIdToDeployIn(), vo.getId(), vo.getHostName(), vo.getServiceOfferingId(), + UsageEventUtils.saveUsageEvent(EventTypes.EVENT_VM_DESTROY, vo.getAccountId(), vo.getDataCenterIdToDeployIn(), vo.getId(), vo.getHostName(), vo.getServiceOfferingId(), vo.getTemplateId(), vo.getHypervisorType().toString()); - _usageEventDao.persist(usageEvent); } return true; } + + private void pubishOnEventBus(String event, String status, VirtualMachine vo, VirtualMachine.State oldState, VirtualMachine.State newState) { + + if (_eventBus == null) { + return; // no provider is configured to provide events bus, so just return + } + + String resourceName = getEntityFromClassName(Network.class.getName()); + org.apache.cloudstack.framework.events.Event eventMsg = new org.apache.cloudstack.framework.events.Event( + ManagementServer.Name, + EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(), + event, + resourceName, + vo.getUuid()); + Map eventDescription = new HashMap(); + eventDescription.put("resource", resourceName); + eventDescription.put("id", vo.getUuid()); + eventDescription.put("old-state", oldState.name()); + eventDescription.put("new-state", newState.name()); + eventMsg.setDescription(eventDescription); + try { + _eventBus.publish(eventMsg); + } catch (EventBusException e) { + s_logger.warn("Failed to publish state change event on the the event bus."); + } + + } + + private String getEntityFromClassName(String entityClassName) { + int index = entityClassName.lastIndexOf("."); + String entityName = entityClassName; + if (index != -1) { + entityName = entityClassName.substring(index+1); + } + return entityName; + } } diff --git a/server/test/com/cloud/snapshot/SnapshotDaoTest.java b/server/test/com/cloud/snapshot/SnapshotDaoTest.java index c412f49b3d4..5dc9b9182ea 100644 --- a/server/test/com/cloud/snapshot/SnapshotDaoTest.java +++ b/server/test/com/cloud/snapshot/SnapshotDaoTest.java @@ -16,24 +16,23 @@ // under the License. package com.cloud.snapshot; -import java.util.List; - import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; import com.cloud.storage.dao.SnapshotDaoImpl; import com.cloud.utils.component.ComponentLocator; - import junit.framework.Assert; import junit.framework.TestCase; +import java.util.List; + public class SnapshotDaoTest extends TestCase { public void testListBy() { SnapshotDaoImpl dao = ComponentLocator.inject(SnapshotDaoImpl.class); - List snapshots = dao.listByInstanceId(3, Snapshot.Status.BackedUp); + List snapshots = dao.listByInstanceId(3, Snapshot.State.BackedUp); for(SnapshotVO snapshot : snapshots) { - Assert.assertTrue(snapshot.getStatus() == Snapshot.Status.BackedUp); + Assert.assertTrue(snapshot.getState() == Snapshot.State.BackedUp); } } } diff --git a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java index 7c9a5823516..f0e4b54115f 100644 --- a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java +++ b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java @@ -16,12 +16,7 @@ // under the License. package com.cloud.vpc.dao; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; - +import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkVO; @@ -31,6 +26,11 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; +import javax.ejb.Local; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + @Local(value = NetworkDao.class) @DB(txn = false) public class MockNetworkDaoImpl extends GenericDaoBase implements NetworkDao{ @@ -342,6 +342,11 @@ public class MockNetworkDaoImpl extends GenericDaoBase implemen return 0; } + @Override + public boolean updateState(Network.State currentState, Network.Event event, Network.State nextState, Network vo, Object data) { + return true; + } + /* (non-Javadoc) * @see com.cloud.network.dao.NetworkDao#listNetworksByAccount(long, long, com.cloud.network.Network.GuestType, boolean) */ diff --git a/tools/whisker/LICENSE b/tools/whisker/LICENSE index 7efac5c566a..025cb33136b 100644 --- a/tools/whisker/LICENSE +++ b/tools/whisker/LICENSE @@ -748,7 +748,7 @@ Within the deps/awsapi-lib directory The Covered Software is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ + computer software" (as that term is defined at 48 C.F.R. � 252.227-7014(a)(1)) and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 @@ -1138,7 +1138,7 @@ Within the deps/awsapi-lib directory The Covered Software is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ + computer software" (as that term is defined at 48 C.F.R. � 252.227-7014(a)(1)) and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 @@ -1526,7 +1526,7 @@ Within the deps/awsapi-lib directory The Covered Software is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ + computer software" (as that term is defined at 48 C.F.R. � 252.227-7014(a)(1)) and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 @@ -1867,7 +1867,9 @@ Within the deps/awsapi-lib directory slf4j-api-1.5.11.jar from https://github.com/qos-ch/slf4j slf4j-jdk14-1.5.11.jar from https://github.com/qos-ch/slf4j - licensed under the Mozilla Public License, Version 1.0 http://www.mozilla.org/MPL/1.1/ (as follows) + + licensed under the Mozilla Public License, Version 1.1 http://www.mozilla.org/MPL/1.1/ (as follows) + MOZILLA PUBLIC LICENSE @@ -2344,6 +2346,486 @@ Within the deps/awsapi-lib directory from Shigeru Chiba http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/ javassist-3.9.0.GA.jar from http://sourceforge.net/projects/jboss/files/Javassist/ + + licensed under the Mozilla Public License, Version 1.1 http://www.mozilla.org/MPL/1.1/ (as follows) + + Copyright (c) 2007-2012 VMware, Inc. All Rights Reserved. + + MOZILLA PUBLIC LICENSE + Version 1.1 + + --------------- + + 1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the + Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to + the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Code, prior Modifications used by a Contributor, and the Modifications + made by that particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the + combination of the Original Code and Modifications, in each case + including portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally + accepted in the software development community for the electronic + transfer of data. + + 1.5. "Executable" means Covered Code in any form other than Source + Code. + + 1.6. "Initial Developer" means the individual or entity identified + as the Initial Developer in the Source Code notice required by Exhibit + A. + + 1.7. "Larger Work" means a work which combines Covered Code or + portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "Licensable" means having the right to grant, to the maximum + extent possible, whether at the time of the initial grant or + subsequently acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means any addition to or deletion from the + substance or structure of either the Original Code or any previous + Modifications. When Covered Code is released as a series of files, a + Modification is: + A. Any addition to or deletion from the contents of a file + containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or + previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code + which is described in the Source Code notice required by Exhibit A as + Original Code, and which, at the time of its release under this + License is not already Covered Code governed by this License. + + 1.10.1. "Patent Claims" means any patent claim(s), now owned or + hereafter acquired, including without limitation, method, process, + and apparatus claims, in any patent Licensable by grantor. + + 1.11. "Source Code" means the preferred form of the Covered Code for + making modifications to it, including all modules it contains, plus + any associated interface definition files, scripts used to control + compilation and installation of an Executable, or source code + differential comparisons against either the Original Code or another + well known, available Covered Code of the Contributor's choice. The + Source Code can be in a compressed or archival form, provided the + appropriate decompression or de-archiving software is widely available + for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License or a future version of this License issued under Section 6.1. + For legal entities, "You" includes any entity which controls, is + controlled by, or is under common control with You. For purposes of + this definition, "control" means (a) the power, direct or indirect, + to cause the direction or management of such entity, whether by + contract or otherwise, or (b) ownership of more than fifty percent + (50%) of the outstanding shares or beneficial ownership of such + entity. + + 2. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, + non-exclusive license, subject to third party intellectual property + claims: + (a) under intellectual property rights (other than patent or + trademark) Licensable by Initial Developer to use, reproduce, + modify, display, perform, sublicense and distribute the Original + Code (or portions thereof) with or without Modifications, and/or + as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or + selling of Original Code, to make, have made, use, practice, + sell, and offer for sale, and/or otherwise dispose of the + Original Code (or portions thereof). + + (c) the licenses granted in this Section 2.1(a) and (b) are + effective on the date Initial Developer first distributes + Original Code under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is + granted: 1) for code that You delete from the Original Code; 2) + separate from the Original Code; or 3) for infringements caused + by: i) the modification of the Original Code or ii) the + combination of the Original Code with other software or devices. + + 2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor + hereby grants You a world-wide, royalty-free, non-exclusive license + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Contributor, to use, reproduce, modify, + display, perform, sublicense and distribute the Modifications + created by such Contributor (or portions thereof) either on an + unmodified basis, with other Modifications, as Covered Code + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or + selling of Modifications made by that Contributor either alone + and/or in combination with its Contributor Version (or portions + of such combination), to make, use, sell, offer for sale, have + made, and/or otherwise dispose of: 1) Modifications made by that + Contributor (or portions thereof); and 2) the combination of + Modifications made by that Contributor with its Contributor + Version (or portions of such combination). + + (c) the licenses granted in Sections 2.2(a) and 2.2(b) are + effective on the date Contributor first makes Commercial Use of + the Covered Code. + + (d) Notwithstanding Section 2.2(b) above, no patent license is + granted: 1) for any code that Contributor has deleted from the + Contributor Version; 2) separate from the Contributor Version; + 3) for infringements caused by: i) third party modifications of + Contributor Version or ii) the combination of Modifications made + by that Contributor with other software (except as part of the + Contributor Version) or other devices; or 4) under Patent Claims + infringed by Covered Code in the absence of Modifications made by + that Contributor. + + 3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are + governed by the terms of this License, including without limitation + Section 2.2. The Source Code version of Covered Code may be + distributed only under the terms of this License or a future version + of this License released under Section 6.1, and You must include a + copy of this License with every copy of the Source Code You + distribute. You may not offer or impose any terms on any Source Code + version that alters or restricts the applicable version of this + License or the recipients' rights hereunder. However, You may include + an additional document offering the additional rights described in + Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be + made available in Source Code form under the terms of this License + either on the same media as an Executable version or via an accepted + Electronic Distribution Mechanism to anyone to whom you made an + Executable version available; and if made available via Electronic + Distribution Mechanism, must remain available for at least twelve (12) + months after the date it initially became available, or at least six + (6) months after a subsequent version of that particular Modification + has been made available to such recipients. You are responsible for + ensuring that the Source Code version remains available even if the + Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a + file documenting the changes You made to create that Covered Code and + the date of any change. You must include a prominent statement that + the Modification is derived, directly or indirectly, from Original + Code provided by the Initial Developer and including the name of the + Initial Developer in (a) the Source Code, and (b) in any notice in an + Executable version or related documentation in which You describe the + origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's + intellectual property rights is required to exercise the rights + granted by such Contributor under Sections 2.1 or 2.2, + Contributor must include a text file with the Source Code + distribution titled "LEGAL" which describes the claim and the + party making the claim in sufficient detail that a recipient will + know whom to contact. If Contributor obtains such knowledge after + the Modification is made available as described in Section 3.2, + Contributor shall promptly modify the LEGAL file in all copies + Contributor makes available thereafter and shall take other steps + (such as notifying appropriate mailing lists or newsgroups) + reasonably calculated to inform those who received the Covered + Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming + interface and Contributor has knowledge of patent licenses which + are reasonably necessary to implement that API, Contributor must + also include this information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to + Section 3.4(a) above, Contributor believes that Contributor's + Modifications are Contributor's original creation(s) and/or + Contributor has sufficient rights to grant the rights conveyed by + this License. + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source + Code. If it is not possible to put such notice in a particular Source + Code file due to its structure, then You must include such notice in a + location (such as a relevant directory) where a user would be likely + to look for such a notice. If You created one or more Modification(s) + You may add your name as a Contributor to the notice described in + Exhibit A. You must also duplicate this License in any documentation + for the Source Code where You describe recipients' rights or ownership + rights relating to Covered Code. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Code. However, You + may do so only on Your own behalf, and not on behalf of the Initial + Developer or any Contributor. You must make it absolutely clear than + any such warranty, support, indemnity or liability obligation is + offered by You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred by the + Initial Developer or such Contributor as a result of warranty, + support, indemnity or liability terms You offer. + + 3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the + requirements of Section 3.1-3.5 have been met for that Covered Code, + and if You include a notice stating that the Source Code version of + the Covered Code is available under the terms of this License, + including a description of how and where You have fulfilled the + obligations of Section 3.2. The notice must be conspicuously included + in any notice in an Executable version, related documentation or + collateral in which You describe recipients' rights relating to the + Covered Code. You may distribute the Executable version of Covered + Code or ownership rights under a license of Your choice, which may + contain terms different from this License, provided that You are in + compliance with the terms of this License and that the license for the + Executable version does not attempt to limit or alter the recipient's + rights in the Source Code version from the rights set forth in this + License. If You distribute the Executable version under a different + license You must make it absolutely clear that any terms which differ + from this License are offered by You alone, not by the Initial + Developer or any Contributor. You hereby agree to indemnify the + Initial Developer and every Contributor for any liability incurred by + the Initial Developer or such Contributor as a result of any such + terms You offer. + + 3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code + not governed by the terms of this License and distribute the Larger + Work as a single product. In such a case, You must make sure the + requirements of this License are fulfilled for the Covered Code. + + 4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this + License with respect to some or all of the Covered Code due to + statute, judicial order, or regulation then You must: (a) comply with + the terms of this License to the maximum extent possible; and (b) + describe the limitations and the code they affect. Such description + must be included in the LEGAL file described in Section 3.4 and must + be included with all distributions of the Source Code. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + + 5. Application of this License. + + This License applies to code to which the Initial Developer has + attached the notice in Exhibit A and to related Covered Code. + + 6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised + and/or new versions of the License from time to time. Each version + will be given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the + License, You may always continue to use it under the terms of that + version. You may also choose to use such Covered Code under the terms + of any subsequent version of the License published by Netscape. No one + other than Netscape has the right to modify the terms applicable to + Covered Code created under this License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may + only do in order to apply it to code which is not already Covered Code + governed by this License), You must (a) rename Your license so that + the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", + "MPL", "NPL" or any confusingly similar phrase do not appear in your + license (except to note that your license differs from this License) + and (b) otherwise make it clear that Your version of the license + contains terms which differ from the Mozilla Public License and + Netscape Public License. (Filling in the name of the Initial + Developer, Original Code or Contributor in the notice described in + Exhibit A shall not of themselves be deemed to be modifications of + this License.) + + 7. DISCLAIMER OF WARRANTY. + + COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF + DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. + THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE + IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, + YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE + COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER + OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + + 8. TERMINATION. + + 8.1. This License and the rights granted hereunder will terminate + automatically if You fail to comply with terms herein and fail to cure + such breach within 30 days of becoming aware of the breach. All + sublicenses to the Covered Code which are properly granted shall + survive any termination of this License. Provisions which, by their + nature, must remain in effect beyond the termination of this License + shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement + claim (excluding declatory judgment actions) against Initial Developer + or a Contributor (the Initial Developer or Contributor against whom + You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly + infringes any patent, then any and all rights granted by such + Participant to You under Sections 2.1 and/or 2.2 of this License + shall, upon 60 days notice from Participant terminate prospectively, + unless if within 60 days after receipt of notice You either: (i) + agree in writing to pay Participant a mutually agreeable reasonable + royalty for Your past and future use of Modifications made by such + Participant, or (ii) withdraw Your litigation claim with respect to + the Contributor Version against such Participant. If within 60 days + of notice, a reasonable royalty and payment arrangement are not + mutually agreed upon in writing by the parties or the litigation claim + is not withdrawn, the rights granted by Participant to You under + Sections 2.1 and/or 2.2 automatically terminate at the expiration of + the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's + Contributor Version, directly or indirectly infringes any patent, then + any rights granted to You by such Participant under Sections 2.1(b) + and 2.2(b) are revoked effective as of the date You first made, used, + sold, distributed, or had made, Modifications made by that + Participant. + + 8.3. If You assert a patent infringement claim against Participant + alleging that such Participant's Contributor Version directly or + indirectly infringes any patent where such claim is resolved (such as + by license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, + all end user license agreements (excluding distributors and resellers) + which have been validly granted by You or any distributor hereunder + prior to termination shall survive termination. + + 9. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL + DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, + OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR + ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY + CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, + WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY + RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW + PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE + EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO + THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + + 10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in + 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" and "commercial computer software documentation," as such + terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 + C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), + all U.S. Government End Users acquire Covered Code with only those + rights set forth herein. + + 11. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. This License shall be governed by + California law provisions (except to the extent applicable law, if + any, provides otherwise), excluding its conflict-of-law provisions. + With respect to disputes in which at least one party is a citizen of, + or an entity chartered or registered to do business in the United + States of America, any litigation relating to this License shall be + subject to the jurisdiction of the Federal Courts of the Northern + District of California, with venue lying in Santa Clara County, + California, with the losing party responsible for costs, including + without limitation, court costs and reasonable attorneys' fees and + expenses. The application of the United Nations Convention on + Contracts for the International Sale of Goods is expressly excluded. + Any law or regulation which provides that the language of a contract + shall be construed against the drafter shall not apply to this + License. + + 12. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or indirectly, + out of its utilization of rights under this License and You agree to + work with Initial Developer and Contributors to distribute such + responsibility on an equitable basis. Nothing herein is intended or + shall be deemed to constitute any admission of liability. + + 13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as + "Multiple-Licensed". "Multiple-Licensed" means that the Initial + Developer permits you to utilize portions of the Covered Code under + Your choice of the NPL or the alternative licenses, if any, specified + by the Initial Developer in the file described in Exhibit A. + + EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License + Version 1.1 (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.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + License for the specific language governing rights and limitations + under the License. + + The Original Code is RabbitMQ. + + The Initial Developer of the Original Code is VMware, Ltd.. + Portions created by VMware, Ltd. are Copyright (C) + 2007-2012 VMware, Inc.. All Rights Reserved. + + Contributor(s): . + + Alternatively, the contents of this file may be used under the terms + of the GNU General Public License Version 2 license (the "[GPL] License"), in which case the + provisions of [GPL] License are applicable instead of those + above. If you wish to allow use of your version of this file only + under the terms of the [GPL] License and not to allow others to use + your version of this file under the MPL, indicate your decision by + deleting the provisions above and replace them with the notice and + other provisions required by the [GPL] License. If you do not delete + the provisions above, a recipient may use your version of this file + under either the MPL or the [GPL] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of + the notices in the Source Code files of the Original Code. You should + use the text of this Exhibit A rather than the text found in the + Original Code Source Code for Your Modifications.] + + + from VMware, Inc http://www.vmware.com/ + rabbitmq-client.jar from http://www.rabbitmq.com/java-client.html + + Within the patches/systemvm/debian/config/etc directory placed in the public domain by Adiscon GmbH http://www.adiscon.com/ @@ -2980,7 +3462,7 @@ Within the target/jar directory The Covered Software is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ + computer software" (as that term is defined at 48 C.F.R. � 252.227-7014(a)(1)) and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 @@ -3369,7 +3851,7 @@ Within the target/jar directory The Covered Software is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ + computer software" (as that term is defined at 48 C.F.R. � 252.227-7014(a)(1)) and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 @@ -3895,7 +4377,7 @@ Within the target/jar directory licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - Copyright (C) 2008 Tóth István + Copyright (C) 2008 T�th Istv�n 2008-2012 Daniel Veillard 2009-2011 Bryan Kearney @@ -4026,7 +4508,7 @@ Within the ui/lib directory licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - Copyright (c) 2006 - 2011 Jörn Zaefferer + Copyright (c) 2006 - 2011 J�rn Zaefferer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -4221,7 +4703,7 @@ Within the ui/lib/jquery-ui directory Within the ui/lib/qunit directory licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - Copyright (c) 2012 John Resig, Jörn Zaefferer + Copyright (c) 2012 John Resig, J�rn Zaefferer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/tools/whisker/descriptor-for-packaging.xml b/tools/whisker/descriptor-for-packaging.xml index 0144dbc055b..29a8284686b 100644 --- a/tools/whisker/descriptor-for-packaging.xml +++ b/tools/whisker/descriptor-for-packaging.xml @@ -2423,6 +2423,10 @@ Innovation Centre, 2006 (http://www.it-innovation.soton.ac.uk). id='adiscon.com' name='Adiscon GmbH' url='http://www.adiscon.com/' /> + Copyright (c) 2013 The Apache Software Foundation @@ -2948,5 +2952,19 @@ Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + + Copyright (c) 2007-2012 VMware, Inc. All Rights Reserved. + + PROJECTRabbitMQ + INITIAL_DEVELOPERVMware, Ltd. + INITIAL_DEVELOPER_COPYRIGHT2007-2012 VMware, Inc. + CONTRIBUTORS + ALT_LIC_NAMEGNU General Public License Version 2 + ALT_LIC_SHORTGPL + + + + + From c0b18c76f01c2143abf3909bf2532912a96fce0b Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 31 Jan 2013 17:26:46 -0800 Subject: [PATCH 22/24] IPv6: Add missing license header --- .../cloud/network/dao/UserIpv6AddressDao.java | 16 ++++++++++++++++ .../network/dao/UserIpv6AddressDaoImpl.java | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/server/src/com/cloud/network/dao/UserIpv6AddressDao.java b/server/src/com/cloud/network/dao/UserIpv6AddressDao.java index 0e245efcde1..81e0da83764 100644 --- a/server/src/com/cloud/network/dao/UserIpv6AddressDao.java +++ b/server/src/com/cloud/network/dao/UserIpv6AddressDao.java @@ -1,3 +1,19 @@ +// 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.dao; import java.util.List; diff --git a/server/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java b/server/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java index 6989c40d289..c77e72dd594 100644 --- a/server/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java +++ b/server/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java @@ -1,3 +1,19 @@ +// 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.dao; import java.util.List; From 33b87d898596098c70dfe0f017351aa1b904fefe Mon Sep 17 00:00:00 2001 From: Kishan Kavala Date: Fri, 1 Feb 2013 07:54:02 +0530 Subject: [PATCH 23/24] CLOUDSTACK-686: Modified unique constraint to include physical_network_id --- setup/db/create-schema.sql | 2 +- setup/db/db/schema-40to410.sql | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 4e41f49db3b..7760f5d0c7b 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -670,7 +670,7 @@ CREATE TABLE `cloud`.`op_dc_vnet_alloc` ( PRIMARY KEY (`id`), UNIQUE `i_op_dc_vnet_alloc__vnet__data_center_id__account_id`(`vnet`, `data_center_id`, `account_id`), INDEX `i_op_dc_vnet_alloc__dc_taken`(`data_center_id`, `taken`), - UNIQUE `i_op_dc_vnet_alloc__vnet__data_center_id`(`vnet`, `data_center_id`), + UNIQUE `i_op_dc_vnet_alloc__vnet__data_center_id`(`vnet`, `physical_network_id`, `data_center_id`), CONSTRAINT `fk_op_dc_vnet_alloc__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_op_dc_vnet_alloc__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index ed4946e54dd..304e12c1eda 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -1264,3 +1264,7 @@ CREATE VIEW `cloud`.`data_center_view` AS `cloud`.`domain` ON data_center.domain_id = domain.id; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'direct.agent.pool.size', '500', 'Default size for DirectAgentPool'); + +ALTER TABLE `cloud`.`op_dc_vnet_alloc` DROP INDEX i_op_dc_vnet_alloc__vnet__data_center_id; + +ALTER TABLE `cloud`.`op_dc_vnet_alloc` ADD CONSTRAINT UNIQUE `i_op_dc_vnet_alloc__vnet__data_center_id`(`vnet`, `physical_network_id`, `data_center_id`); From 1a348c85fd8f417a91474272fb83bc74b0515461 Mon Sep 17 00:00:00 2001 From: Murali Reddy Date: Fri, 1 Feb 2013 11:41:30 +0530 Subject: [PATCH 24/24] adding apache license heders to the files that are faling RAT check --- .../framework/events/EventSubscriber.java | 34 +++++++++---------- .../src/com/cloud/event/UsageEventUtils.java | 17 ++++++++++ .../cloud/network/NetworkStateListener.java | 17 ++++++++++ .../listener/SnapshotStateListener.java | 17 ++++++++++ .../storage/listener/VolumeStateListener.java | 17 ++++++++++ 5 files changed, 84 insertions(+), 18 deletions(-) diff --git a/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java b/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java index b1c30c21587..511ebff17d2 100644 --- a/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java +++ b/framework/events/src/org/apache/cloudstack/framework/events/EventSubscriber.java @@ -1,21 +1,19 @@ -/* - * 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/LICENSE2.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. - */ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package org.apache.cloudstack.framework.events; diff --git a/server/src/com/cloud/event/UsageEventUtils.java b/server/src/com/cloud/event/UsageEventUtils.java index 904525ea2f0..0e6edb9e0e8 100644 --- a/server/src/com/cloud/event/UsageEventUtils.java +++ b/server/src/com/cloud/event/UsageEventUtils.java @@ -1,3 +1,20 @@ +// 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.event; import com.cloud.dc.DataCenterVO; diff --git a/server/src/com/cloud/network/NetworkStateListener.java b/server/src/com/cloud/network/NetworkStateListener.java index 130063348eb..a3792860d82 100644 --- a/server/src/com/cloud/network/NetworkStateListener.java +++ b/server/src/com/cloud/network/NetworkStateListener.java @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + package com.cloud.network; import com.cloud.event.EventCategory; diff --git a/server/src/com/cloud/storage/listener/SnapshotStateListener.java b/server/src/com/cloud/storage/listener/SnapshotStateListener.java index 2b19887e83a..d0ca3894943 100644 --- a/server/src/com/cloud/storage/listener/SnapshotStateListener.java +++ b/server/src/com/cloud/storage/listener/SnapshotStateListener.java @@ -1,3 +1,20 @@ +// 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.listener; import com.cloud.event.EventCategory; diff --git a/server/src/com/cloud/storage/listener/VolumeStateListener.java b/server/src/com/cloud/storage/listener/VolumeStateListener.java index c460016f90a..177ccf2369a 100644 --- a/server/src/com/cloud/storage/listener/VolumeStateListener.java +++ b/server/src/com/cloud/storage/listener/VolumeStateListener.java @@ -1,3 +1,20 @@ +// 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.listener; import com.cloud.event.EventCategory;