From 17afeade009f7a2d881d8b68fe14f9d2b94adc91 Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Mon, 15 Nov 2010 08:59:35 -0800 Subject: [PATCH] better componentslocator --- .../exception/AgentUnavailableException.java | 2 +- .../cloud/network/element/NetworkElement.java | 4 + client/tomcatconf/commands.properties.in | 2 +- .../network/BasicVirtualNetworkAllocator.java | 76 ---- .../cloud/network/HAProxyConfigurator.java | 13 - .../network/VirtualNetworkAllocator.java | 51 --- .../com/cloud/api/commands/DestroyVm2Cmd.java | 97 +++++ .../DefaultComponentLibrary.java | 368 ++++++++++++++++++ .../consoleproxy/ConsoleProxyManagerImpl.java | 8 +- .../network/element/DomainRouterElement.java | 10 + server/src/com/cloud/vm/MauriceMoss.java | 35 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 34 ++ server/src/com/cloud/vm/UserVmService.java | 10 + server/src/com/cloud/vm/VmManager.java | 3 +- .../utils/component/ComponentLibrary.java | 30 ++ .../utils/component/ComponentLocator.java | 226 ++++++----- 16 files changed, 722 insertions(+), 247 deletions(-) delete mode 100644 core/src/com/cloud/network/BasicVirtualNetworkAllocator.java delete mode 100644 core/src/com/cloud/network/VirtualNetworkAllocator.java create mode 100644 server/src/com/cloud/api/commands/DestroyVm2Cmd.java create mode 100644 server/src/com/cloud/configuration/DefaultComponentLibrary.java create mode 100644 utils/src/com/cloud/utils/component/ComponentLibrary.java diff --git a/api/src/com/cloud/exception/AgentUnavailableException.java b/api/src/com/cloud/exception/AgentUnavailableException.java index 2e6632c58a3..adf52f13a48 100644 --- a/api/src/com/cloud/exception/AgentUnavailableException.java +++ b/api/src/com/cloud/exception/AgentUnavailableException.java @@ -24,7 +24,7 @@ import com.cloud.utils.SerialVersionUID; * command. * */ -public class AgentUnavailableException extends Exception { +public class AgentUnavailableException extends ResourceUnavailableException { private static final long serialVersionUID = SerialVersionUID.AgentUnavailableException; diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index 28d69975194..66b2e474bd7 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -33,4 +33,8 @@ public interface NetworkElement extends Adapter { boolean release(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; boolean shutdown(NetworkConfiguration config, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; + + boolean addRule(); + + boolean revokeRule(); } diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index 7d90f6da4e2..5bfcfad7079 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -128,7 +128,7 @@ changeServiceForRouter=com.cloud.api.commands.UpgradeRouterCmd;3 listRouters=com.cloud.api.commands.ListRoutersCmd;7 #### system vm commands -startSystemVm=com.cloud.api.commands.StartSystemVMCmd;1 +startSystemVm=com.cloud.api.commands.StartSystemVmCmd;1 rebootSystemVm=com.cloud.api.commands.RebootSystemVmCmd;1 stopSystemVm=com.cloud.api.commands.StopSystemVmCmd;1 listSystemVms=com.cloud.api.commands.ListSystemVMsCmd;1 diff --git a/core/src/com/cloud/network/BasicVirtualNetworkAllocator.java b/core/src/com/cloud/network/BasicVirtualNetworkAllocator.java deleted file mode 100644 index 831708c65e2..00000000000 --- a/core/src/com/cloud/network/BasicVirtualNetworkAllocator.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. - * - * This software is licensed under the GNU General Public License v3 or later. - * - * It is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ -package com.cloud.network; - -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.service.ServiceOfferingVO; -import com.cloud.user.AccountVO; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.vm.VMInstanceVO; - -@Local(value=VirtualNetworkAllocator.class) -public class BasicVirtualNetworkAllocator implements VirtualNetworkAllocator { - DataCenterDao _dcDao; - String _name; - - public BasicVirtualNetworkAllocator() { - } - - @Override - public String allocateTag(AccountVO account, HostVO host, VMInstanceVO vm, ServiceOfferingVO so) { - return _dcDao.allocateVnet(host.getDataCenterId(), account.getId(), null); - } - - @Override - public void releaseTag(String tag, HostVO host, AccountVO account, VMInstanceVO vm) { - _dcDao.releaseVnet(tag, host.getDataCenterId(), account.getId(), null); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - _dcDao = locator.getDao(DataCenterDao.class); - if (_dcDao == null) { - throw new ConfigurationException("Unable to get DataCenterDao"); - } - _name = name; - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - -} diff --git a/core/src/com/cloud/network/HAProxyConfigurator.java b/core/src/com/cloud/network/HAProxyConfigurator.java index 1ff5b9f4596..0d93af63e21 100644 --- a/core/src/com/cloud/network/HAProxyConfigurator.java +++ b/core/src/com/cloud/network/HAProxyConfigurator.java @@ -19,7 +19,6 @@ package com.cloud.network; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -145,18 +144,6 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { return new String("\t "); } - public static void main(String [] args) { -/* FirewallRulesDao dao = new FirewallRulesDaoImpl(); - List rules = dao.listIPForwarding(); - - HAProxyConfigurator hapc = new HAProxyConfigurator(); - String [] result = hapc.generateConfiguration(rules); - for (int i=0; i < result.length; i++) { - System.out.println(result[i]); - }*/ - - } - @Override public String[][] generateFwRules(List fwRules) { String [][] result = new String [2][]; diff --git a/core/src/com/cloud/network/VirtualNetworkAllocator.java b/core/src/com/cloud/network/VirtualNetworkAllocator.java deleted file mode 100644 index c57bccf5dcb..00000000000 --- a/core/src/com/cloud/network/VirtualNetworkAllocator.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. - * - * This software is licensed under the GNU General Public License v3 or later. - * - * It is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ -package com.cloud.network; - -import com.cloud.host.HostVO; -import com.cloud.service.ServiceOfferingVO; -import com.cloud.user.AccountVO; -import com.cloud.utils.component.Adapter; -import com.cloud.vm.VMInstanceVO; - -public interface VirtualNetworkAllocator extends Adapter { - - /** - * Allocate an virtual network tag - * - * @param account account that this network belongs to. - * @param host host being deployed to. - * @param dc datacenter being deployed to. - * @param vm vm that is being deployed. - * @param so service offering for that vm. - * @return tag - */ - String allocateTag(AccountVO account, HostVO host, VMInstanceVO vm, ServiceOfferingVO so); - - - /** - * Release the virtual network tag. - * - * @param tag tag retrieved in allocateTag - * @param host host to release this tag in. - * @param account account to release this tag in. - * @param vm vm that is releasing this tag. - */ - void releaseTag(String tag, HostVO host, AccountVO account, VMInstanceVO vm); - -} diff --git a/server/src/com/cloud/api/commands/DestroyVm2Cmd.java b/server/src/com/cloud/api/commands/DestroyVm2Cmd.java new file mode 100644 index 00000000000..d0e066bd3a6 --- /dev/null +++ b/server/src/com/cloud/api/commands/DestroyVm2Cmd.java @@ -0,0 +1,97 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.UserVmResponse; +import com.cloud.event.EventTypes; +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.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; + +@Implementation(description="Destroys a virtual machine. Once destroyed, only the administrator can recover it.") +public class DestroyVm2Cmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DestroyVm2Cmd.class.getName()); + + private static final String s_name = "destroyvirtualmachineresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getName() { + return s_name; + } + + @Override + public long getAccountId() { + UserVm vm = ApiDBUtils.findUserVmById(getId()); + if (vm != null) { + return vm.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_VM_DESTROY; + } + + @Override + public String getEventDescription() { + return "destroying vm: " + getId(); + } + + @Override + public void execute() throws ServerApiException, InvalidParameterValueException, PermissionDeniedException, InsufficientAddressCapacityException, InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException{ + UserVm result = _userVmService.destroyVm(this); + UserVmResponse response = ApiResponseHelper.createUserVmResponse(result); + response.setResponseName("virtualmachine"); + this.setResponseObject(response); + } +} diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java new file mode 100644 index 00000000000..54dc4f3f61a --- /dev/null +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -0,0 +1,368 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.configuration; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.cloud.agent.manager.AgentManagerImpl; +import com.cloud.agent.manager.allocator.HostAllocator; +import com.cloud.agent.manager.allocator.PodAllocator; +import com.cloud.agent.manager.allocator.impl.RecreateHostAllocator; +import com.cloud.agent.manager.allocator.impl.UserConcentratedAllocator; +import com.cloud.alert.AlertManagerImpl; +import com.cloud.alert.dao.AlertDaoImpl; +import com.cloud.async.AsyncJobExecutorContextImpl; +import com.cloud.async.AsyncJobManagerImpl; +import com.cloud.async.SyncQueueManagerImpl; +import com.cloud.async.dao.AsyncJobDaoImpl; +import com.cloud.async.dao.SyncQueueDaoImpl; +import com.cloud.async.dao.SyncQueueItemDaoImpl; +import com.cloud.capacity.dao.CapacityDaoImpl; +import com.cloud.certificate.dao.CertificateDaoImpl; +import com.cloud.cluster.DummyClusterManagerImpl; +import com.cloud.cluster.dao.ManagementServerHostDaoImpl; +import com.cloud.configuration.dao.ConfigurationDaoImpl; +import com.cloud.configuration.dao.ResourceCountDaoImpl; +import com.cloud.configuration.dao.ResourceLimitDaoImpl; +import com.cloud.consoleproxy.AgentBasedStandaloneConsoleProxyManager; +import com.cloud.consoleproxy.ConsoleProxyAllocator; +import com.cloud.consoleproxy.ConsoleProxyBalanceAllocator; +import com.cloud.dc.dao.AccountVlanMapDaoImpl; +import com.cloud.dc.dao.ClusterDaoImpl; +import com.cloud.dc.dao.DataCenterDaoImpl; +import com.cloud.dc.dao.DataCenterIpAddressDaoImpl; +import com.cloud.dc.dao.HostPodDaoImpl; +import com.cloud.dc.dao.PodVlanMapDaoImpl; +import com.cloud.dc.dao.VlanDaoImpl; +import com.cloud.deploy.SimplePlanner; +import com.cloud.domain.dao.DomainDaoImpl; +import com.cloud.event.dao.EventDaoImpl; +import com.cloud.ha.CheckOnAgentInvestigator; +import com.cloud.ha.HighAvailabilityManagerImpl; +import com.cloud.ha.InvestigatorImpl; +import com.cloud.ha.StorageFence; +import com.cloud.ha.XenServerInvestigator; +import com.cloud.ha.dao.HighAvailabilityDaoImpl; +import com.cloud.host.dao.DetailsDaoImpl; +import com.cloud.host.dao.HostDaoImpl; +import com.cloud.hypervisor.kvm.discoverer.KvmServerDiscoverer; +import com.cloud.hypervisor.xen.discoverer.XcpServerDiscoverer; +import com.cloud.maid.StackMaidManagerImpl; +import com.cloud.maid.dao.StackMaidDaoImpl; +import com.cloud.maint.UpgradeManagerImpl; +import com.cloud.maint.dao.AgentUpgradeDaoImpl; +import com.cloud.network.ExteralIpAddressAllocator; +import com.cloud.network.NetworkManagerImpl; +import com.cloud.network.configuration.ControlNetworkGuru; +import com.cloud.network.configuration.GuestNetworkGuru; +import com.cloud.network.configuration.PodBasedNetworkGuru; +import com.cloud.network.configuration.PublicNetworkGuru; +import com.cloud.network.dao.FirewallRulesDaoImpl; +import com.cloud.network.dao.IPAddressDaoImpl; +import com.cloud.network.dao.LoadBalancerDaoImpl; +import com.cloud.network.dao.LoadBalancerVMMapDaoImpl; +import com.cloud.network.dao.NetworkConfigurationDaoImpl; +import com.cloud.network.dao.NetworkRuleConfigDaoImpl; +import com.cloud.network.dao.RemoteAccessVpnDaoImpl; +import com.cloud.network.dao.VpnUserDaoImpl; +import com.cloud.network.router.DomainRouterManagerImpl; +import com.cloud.network.security.NetworkGroupManagerImpl; +import com.cloud.network.security.dao.IngressRuleDaoImpl; +import com.cloud.network.security.dao.NetworkGroupDaoImpl; +import com.cloud.network.security.dao.NetworkGroupRulesDaoImpl; +import com.cloud.network.security.dao.NetworkGroupVMMapDaoImpl; +import com.cloud.network.security.dao.NetworkGroupWorkDaoImpl; +import com.cloud.network.security.dao.VmRulesetLogDaoImpl; +import com.cloud.offerings.dao.NetworkOfferingDaoImpl; +import com.cloud.server.auth.MD5UserAuthenticator; +import com.cloud.service.dao.ServiceOfferingDaoImpl; +import com.cloud.storage.StorageManagerImpl; +import com.cloud.storage.allocator.FirstFitStoragePoolAllocator; +import com.cloud.storage.allocator.GarbageCollectingStoragePoolAllocator; +import com.cloud.storage.allocator.LocalStoragePoolAllocator; +import com.cloud.storage.allocator.StoragePoolAllocator; +import com.cloud.storage.dao.DiskOfferingDaoImpl; +import com.cloud.storage.dao.DiskTemplateDaoImpl; +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.SnapshotPolicyDaoImpl; +import com.cloud.storage.dao.SnapshotScheduleDaoImpl; +import com.cloud.storage.dao.StoragePoolDaoImpl; +import com.cloud.storage.dao.StoragePoolHostDaoImpl; +import com.cloud.storage.dao.UploadDaoImpl; +import com.cloud.storage.dao.VMTemplateDaoImpl; +import com.cloud.storage.dao.VMTemplateHostDaoImpl; +import com.cloud.storage.dao.VMTemplatePoolDaoImpl; +import com.cloud.storage.dao.VMTemplateZoneDaoImpl; +import com.cloud.storage.dao.VolumeDaoImpl; +import com.cloud.storage.download.DownloadMonitorImpl; +import com.cloud.storage.preallocatedlun.dao.PreallocatedLunDaoImpl; +import com.cloud.storage.secondary.SecondaryStorageDiscoverer; +import com.cloud.storage.secondary.SecondaryStorageManagerImpl; +import com.cloud.storage.secondary.SecondaryStorageVmDefaultAllocator; +import com.cloud.storage.snapshot.SnapshotManagerImpl; +import com.cloud.storage.snapshot.SnapshotSchedulerImpl; +import com.cloud.storage.upload.UploadMonitorImpl; +import com.cloud.template.TemplateManagerImpl; +import com.cloud.user.AccountManagerImpl; +import com.cloud.user.dao.AccountDaoImpl; +import com.cloud.user.dao.UserAccountDaoImpl; +import com.cloud.user.dao.UserDaoImpl; +import com.cloud.user.dao.UserStatisticsDaoImpl; +import com.cloud.utils.Pair; +import com.cloud.utils.component.Adapter; +import com.cloud.utils.component.ComponentLibrary; +import com.cloud.utils.component.ComponentLocator.ComponentInfo; +import com.cloud.utils.component.Manager; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.MauriceMoss; +import com.cloud.vm.UserVmManagerImpl; +import com.cloud.vm.dao.ConsoleProxyDaoImpl; +import com.cloud.vm.dao.DomainRouterDaoImpl; +import com.cloud.vm.dao.InstanceGroupDaoImpl; +import com.cloud.vm.dao.InstanceGroupVMMapDaoImpl; +import com.cloud.vm.dao.NicDaoImpl; +import com.cloud.vm.dao.SecondaryStorageVmDaoImpl; +import com.cloud.vm.dao.UserVmDaoImpl; +import com.cloud.vm.dao.VMInstanceDaoImpl; + +public class DefaultComponentLibrary implements ComponentLibrary { + + protected final Map>> _daos = new LinkedHashMap>>(); + + protected void addDao(String name, Class> clazz) { + addDao(name, clazz, null, true); + } + + protected void addDao(String name, Class> clazz, List> params, + boolean singleton) { + ComponentInfo> ComponentInfo = new ComponentInfo>(name, clazz, params, singleton); + for (String key : ComponentInfo.getKeys()) { + _daos.put(key, ComponentInfo); + } + } + + protected void addDaos() { + addDao("StackMaidDao", StackMaidDaoImpl.class); + addDao("VMTemplateZoneDao", VMTemplateZoneDaoImpl.class); + addDao("DomainRouterDao", DomainRouterDaoImpl.class); + addDao("HostDao", HostDaoImpl.class); + addDao("VMInstanceDao", VMInstanceDaoImpl.class); + addDao("UserVmDao", UserVmDaoImpl.class); + addDao("ServiceOfferingDao", ServiceOfferingDaoImpl.class); + addDao("DiskOfferingDao", DiskOfferingDaoImpl.class); + addDao("DataCenterDao", DataCenterDaoImpl.class); + addDao("HostPodDao", HostPodDaoImpl.class); + addDao("IPAddressDao", IPAddressDaoImpl.class); + addDao("VlanDao", VlanDaoImpl.class); + addDao("PodVlanMapDao", PodVlanMapDaoImpl.class); + addDao("AccountVlanMapDao", AccountVlanMapDaoImpl.class); + addDao("VolumeDao", VolumeDaoImpl.class); + addDao("EventDao", EventDaoImpl.class); + addDao("UserDao", UserDaoImpl.class); + addDao("UserStatisticsDao", UserStatisticsDaoImpl.class); + addDao("DiskTemplateDao", DiskTemplateDaoImpl.class); + addDao("FirewallRulesDao", FirewallRulesDaoImpl.class); + addDao("LoadBalancerDao", LoadBalancerDaoImpl.class); + addDao("NetworkRuleConfigDao", NetworkRuleConfigDaoImpl.class); + addDao("LoadBalancerVMMapDao", LoadBalancerVMMapDaoImpl.class); + addDao("DataCenterIpAddressDao", DataCenterIpAddressDaoImpl.class); + addDao("NetworkGroupDao", NetworkGroupDaoImpl.class); + addDao("IngressRuleDao", IngressRuleDaoImpl.class); + addDao("NetworkGroupVMMapDao", NetworkGroupVMMapDaoImpl.class); + addDao("NetworkGroupRulesDao", NetworkGroupRulesDaoImpl.class); + addDao("NetworkGroupWorkDao", NetworkGroupWorkDaoImpl.class); + addDao("VmRulesetLogDao", VmRulesetLogDaoImpl.class); + addDao("AlertDao", AlertDaoImpl.class); + addDao("CapacityDao", CapacityDaoImpl.class); + addDao("DomainDao", DomainDaoImpl.class); + addDao("AccountDao", AccountDaoImpl.class); + addDao("ResourceLimitDao", ResourceLimitDaoImpl.class); + addDao("ResourceCountDao", ResourceCountDaoImpl.class); + addDao("UserAccountDao", UserAccountDaoImpl.class); + addDao("VMTemplateHostDao", VMTemplateHostDaoImpl.class); + addDao("UploadDao", UploadDaoImpl.class); + addDao("VMTemplatePoolDao", VMTemplatePoolDaoImpl.class); + addDao("LaunchPermissionDao", LaunchPermissionDaoImpl.class); + addDao("ConfigurationDao", ConfigurationDaoImpl.class); + addDao("VMTemplateDao", VMTemplateDaoImpl.class); + addDao("HighAvailabilityDao", HighAvailabilityDaoImpl.class); + addDao("ConsoleProxyDao", ConsoleProxyDaoImpl.class); + addDao("SecondaryStorageVmDao", SecondaryStorageVmDaoImpl.class); + addDao("ManagementServerHostDao", ManagementServerHostDaoImpl.class); + addDao("AgentUpgradeDao", AgentUpgradeDaoImpl.class); + addDao("SnapshotDao", SnapshotDaoImpl.class); + addDao("AsyncJobDao", AsyncJobDaoImpl.class); + addDao("SyncQueueDao", SyncQueueDaoImpl.class); + addDao("SyncQueueItemDao", SyncQueueItemDaoImpl.class); + addDao("GuestOSDao", GuestOSDaoImpl.class); + addDao("GuestOSCategoryDao", GuestOSCategoryDaoImpl.class); + addDao("StoragePoolDao", StoragePoolDaoImpl.class); + addDao("StoragePoolHostDao", StoragePoolHostDaoImpl.class); + addDao("DetailsDao", DetailsDaoImpl.class); + addDao("SnapshotPolicyDao", SnapshotPolicyDaoImpl.class); + addDao("SnapshotScheduleDao", SnapshotScheduleDaoImpl.class); + addDao("PreallocatedLunDao", PreallocatedLunDaoImpl.class); + addDao("ClusterDao", ClusterDaoImpl.class); + addDao("CertificateDao", CertificateDaoImpl.class); + addDao("NetworkConfigurationDao", NetworkConfigurationDaoImpl.class); + addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); + addDao("NicDao", NicDaoImpl.class); + addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); + addDao("InstanceGroupVMMapDao", InstanceGroupVMMapDaoImpl.class); + addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); + addDao("VpnUserDao", VpnUserDaoImpl.class); + } + + Map> _managers = new HashMap>(); + Map>> _adapters = new HashMap>>(); + + @Override + public synchronized Map>> getDaos() { + if (_daos.size() == 0) { + addDaos(); + } + return _daos; + } + + protected void addManager(String name, Class clazz, List> params, boolean singleton) { + ComponentInfo ComponentInfo = new ComponentInfo(name, clazz, params, singleton); + for (String key : ComponentInfo.getKeys()) { + _managers.put(key, ComponentInfo); + } + } + + protected void addManager(String name, Class clazz) { + addManager(name, clazz, null, true); + } + + protected void addManagers() { + addManager("StackMaidManager", StackMaidManagerImpl.class); + addManager("agent manager", AgentManagerImpl.class); + addManager("account manager", AccountManagerImpl.class); + addManager("configuration manager", ConfigurationManagerImpl.class); + addManager("network manager", NetworkManagerImpl.class); + addManager("download manager", DownloadMonitorImpl.class); + addManager("upload manager", UploadMonitorImpl.class); + addManager("console proxy manager", AgentBasedStandaloneConsoleProxyManager.class); + addManager("secondary storage vm manager", SecondaryStorageManagerImpl.class); + addManager("vm manager", UserVmManagerImpl.class); + addManager("upgrade manager", UpgradeManagerImpl.class); + addManager("StorageManager", StorageManagerImpl.class); + addManager("Cluster Manager", DummyClusterManagerImpl.class); + addManager("SyncQueueManager", SyncQueueManagerImpl.class); + addManager("AsyncJobManager", AsyncJobManagerImpl.class); + addManager("AsyncJobExecutorContext", AsyncJobExecutorContextImpl.class); + addManager("HA Manager", HighAvailabilityManagerImpl.class); + addManager("Alert Manager", AlertManagerImpl.class); + addManager("Template Manager", TemplateManagerImpl.class); + addManager("Snapshot Manager", SnapshotManagerImpl.class); + addManager("SnapshotScheduler", SnapshotSchedulerImpl.class); + addManager("NetworkGroupManager", NetworkGroupManagerImpl.class); + addManager("VmManager", MauriceMoss.class); + addManager("DomainRouterManager", DomainRouterManagerImpl.class); + } + + protected void addAdapterChain(Class interphace, List>> adapters) { + ArrayList> lst = new ArrayList>(adapters.size()); + for (Pair> adapter : adapters) { + @SuppressWarnings("unchecked") + Class clazz = (Class)adapter.second(); + lst.add(new ComponentInfo(adapter.first(), clazz)); + } + _adapters.put(interphace.getName(), lst); + } + + @Override + public synchronized Map> getManagers() { + if (_managers.size() == 0) { + addManagers(); + } + return _managers; + } + + public void addAllAdapters() { + + List>> hostAllocators = new ArrayList>>(); + hostAllocators.add(new Pair>("FirstFitRouting", RecreateHostAllocator.class)); + //addAdapter("FirstFit", FirstFitAllocator.class); + addAdapterChain(HostAllocator.class, hostAllocators); + + + List>> poolAllocators = new ArrayList>>(); + poolAllocators.add(new Pair>("LocalStorage", LocalStoragePoolAllocator.class)); + poolAllocators.add(new Pair>("Storage", FirstFitStoragePoolAllocator.class)); + poolAllocators.add(new Pair>("GarbageCollecting", GarbageCollectingStoragePoolAllocator.class)); + addAdapterChain(StoragePoolAllocator.class, poolAllocators); + + List>> podAllocators = new ArrayList>>(); + podAllocators.add(new Pair>("User First", UserConcentratedAllocator.class)); + addAdapterChain(PodAllocator.class, podAllocators); + + List>> proxyAllocators = new ArrayList>>(); + proxyAllocators.add(new Pair>("Balance", ConsoleProxyBalanceAllocator.class)); + addAdapterChain(ConsoleProxyAllocator.class, proxyAllocators); + + // NetworkGuru + addAdapterChain("GuestNetworkGuru", GuestNetworkGuru.class); + addAdapterChain("PublicNetworkGuru", PublicNetworkGuru.class); + addAdapterChain("PodBasedNetworkGuru", PodBasedNetworkGuru.class); + addAdapterChain("ControlNetworkGuru", ControlNetworkGuru.class); + + // Secondary Storage Vm Allocator + addAdapterChain("Balance", SecondaryStorageVmDefaultAllocator.class); + + // Ip Address Allocator + addAdapterChain("Basic", ExteralIpAddressAllocator.class); + + + // User Authenticator + addAdapterChain("MD5", MD5UserAuthenticator.class); + + // HA Investigator + addAdapterChain("SimpleInvestigator", CheckOnAgentInvestigator.class); + addAdapterChain("XenServerInvestigator", XenServerInvestigator.class); + addAdapterChain("PingInvestigator", InvestigatorImpl.class); + + // HA Fence Builder + addAdapterChain("StorageFenceBuilder", StorageFence.class); + + // Discoverer + addAdapterChain("XCP Agent", XcpServerDiscoverer.class); + addAdapterChain("SecondaryStorage", SecondaryStorageDiscoverer.class); + addAdapterChain("KVM Agent", KvmServerDiscoverer.class); + + // Deployment Planner + addAdapterChain("Simple", SimplePlanner.class); + } + + @Override + public synchronized Map>> getAdapters() { + if (_adapters.size() == 0) { + addAdapters(); + } + return _adapters; + } +} diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index 9031386bfbd..0059424e9ef 100644 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -531,7 +531,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach @Override public ConsoleProxyVO startProxy(long proxyVmId, long startEventId) { try { - return start(proxyVmId, startEventId); + return start2(proxyVmId, startEventId); } catch (StorageUnavailableException e) { s_logger.warn("Exception while trying to start console proxy", e); return null; @@ -881,7 +881,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach if (s_logger.isDebugEnabled()) s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId); - Map context = createProxyInstance(dataCenterId); + Map context = createProxyInstance2(dataCenterId); long proxyVmId = (Long) context.get("proxyVmId"); if (proxyVmId == 0) { @@ -921,7 +921,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach if (s_logger.isDebugEnabled()) s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId); - Map context = createProxyInstance(dataCenterId); + Map context = createProxyInstance2(dataCenterId); long proxyVmId = (Long) context.get("proxyVmId"); if (proxyVmId == 0) { @@ -1468,7 +1468,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach try { if (proxyLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) { try { - readyProxy = start(readyProxy.getId(), 0); + readyProxy = start2(readyProxy.getId(), 0); } finally { proxyLock.unlock(); } diff --git a/server/src/com/cloud/network/element/DomainRouterElement.java b/server/src/com/cloud/network/element/DomainRouterElement.java index 241927344e8..86d34ff11d3 100644 --- a/server/src/com/cloud/network/element/DomainRouterElement.java +++ b/server/src/com/cloud/network/element/DomainRouterElement.java @@ -113,6 +113,16 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement { } return _routerMgr.stopRouter(router.getId(), 1); } + + @Override + public boolean addRule() { + return false; + } + + @Override + public boolean revokeRule() { + return false; + } protected DomainRouterElement() { super(); diff --git a/server/src/com/cloud/vm/MauriceMoss.java b/server/src/com/cloud/vm/MauriceMoss.java index 63ab534975e..38c8503f868 100644 --- a/server/src/com/cloud/vm/MauriceMoss.java +++ b/server/src/com/cloud/vm/MauriceMoss.java @@ -205,10 +205,41 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { return allocate(vm, template, serviceOffering, new Pair(serviceOffering, null), null, networks, null, plan, owner); } + @SuppressWarnings("unchecked") + private VirtualMachineGuru getVmGuru(T vm) { + return (VirtualMachineGuru)_vmGurus.get(vm); + } + @Override - public void destroy() { - // TODO Auto-generated method stub + public boolean destroy(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { + if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unable to find vm or vm is destroyed: " + vm); + } + return true; + } + if (s_logger.isDebugEnabled()) { + s_logger.debug("Destroying vm " + vm); + } + + if (!stop(vm, caller, account)) { + s_logger.error("Unable to stop vm so we can't destroy it: " + vm); + return false; + } + + VirtualMachineGuru guru = getVmGuru(vm); + vm = guru.findById(vm.getId()); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Destroying vm " + vm); + } + if (!_vmDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { + s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString()); + return false; + } + + return true; } @Override diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index c3997fa6486..3405bf5755f 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -71,6 +71,7 @@ import com.cloud.api.commands.CreateVMGroupCmd; import com.cloud.api.commands.DeleteVMGroupCmd; import com.cloud.api.commands.DeployVm2Cmd; import com.cloud.api.commands.DestroyVMCmd; +import com.cloud.api.commands.DestroyVm2Cmd; import com.cloud.api.commands.DetachVolumeCmd; import com.cloud.api.commands.RebootVMCmd; import com.cloud.api.commands.RecoverVMCmd; @@ -3880,4 +3881,37 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM return _itMgr.start(vm, null, user, account); } + @Override + public UserVm destroyVm(DestroyVm2Cmd cmd) throws ResourceUnavailableException, ConcurrentOperationException { + Account account = UserContext.current().getAccount(); + Long userId = UserContext.current().getUserId(); + Long vmId = cmd.getId(); + + //Verify input parameters + UserVmVO vm = _vmDao.findById(vmId.longValue()); + if (vm == null) { + throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR, "unable to find a virtual machine with id " + vmId); + } + + userId = accountAndUserValidation(vmId, account, userId, vm); + User caller = _userDao.findById(userId); + + EventUtils.saveScheduledEvent(userId, vm.getAccountId(), EventTypes.EVENT_VM_DESTROY, "Destroying Vm with Id: "+vmId); + + boolean status; + try { + status = _itMgr.destroy(vm, caller, account); + } catch (OperationTimedoutException e) { + throw new ResourceUnavailableException("Resource not available to complete the command", e); + } + + if (status) { + EventUtils.saveEvent(userId, vm.getAccountId(), EventTypes.EVENT_VM_DESTROY, "Successfully destroyed vm with id:"+vmId); + return _vmDao.findById(vmId); + } else { + EventUtils.saveEvent(userId, vm.getAccountId(), EventTypes.EVENT_VM_DESTROY, "Failed to destroy vm with id:"+vmId); + throw new CloudRuntimeException("Failed to destroy vm with id " + vmId); + } + } + } diff --git a/server/src/com/cloud/vm/UserVmService.java b/server/src/com/cloud/vm/UserVmService.java index ee790b1a281..7495fc2cbd8 100755 --- a/server/src/com/cloud/vm/UserVmService.java +++ b/server/src/com/cloud/vm/UserVmService.java @@ -23,6 +23,7 @@ import com.cloud.api.commands.CreateVMGroupCmd; import com.cloud.api.commands.DeleteVMGroupCmd; import com.cloud.api.commands.DeployVm2Cmd; import com.cloud.api.commands.DestroyVMCmd; +import com.cloud.api.commands.DestroyVm2Cmd; import com.cloud.api.commands.DetachVolumeCmd; import com.cloud.api.commands.RebootVMCmd; import com.cloud.api.commands.RecoverVMCmd; @@ -56,6 +57,15 @@ public interface UserVmService { */ UserVm destroyVm(DestroyVMCmd cmd); + /** + * Destroys one virtual machine + * @param userId the id of the user performing the action + * @param vmId the id of the virtual machine. + * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + */ + UserVm destroyVm(DestroyVm2Cmd cmd) throws ResourceUnavailableException, ConcurrentOperationException; + /** * Resets the password of a virtual machine. * @param cmd - the command specifying vmId, password diff --git a/server/src/com/cloud/vm/VmManager.java b/server/src/com/cloud/vm/VmManager.java index 63771dd4349..46a2bdebd9d 100644 --- a/server/src/com/cloud/vm/VmManager.java +++ b/server/src/com/cloud/vm/VmManager.java @@ -71,7 +71,8 @@ public interface VmManager extends Manager { boolean stop(T vm, User caller, Account account) throws AgentUnavailableException, ConcurrentOperationException, OperationTimedoutException; - void destroy(); + boolean destroy(T vm, User caller, Account account) throws ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException; +; void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru); diff --git a/utils/src/com/cloud/utils/component/ComponentLibrary.java b/utils/src/com/cloud/utils/component/ComponentLibrary.java new file mode 100644 index 00000000000..d1b914a21f2 --- /dev/null +++ b/utils/src/com/cloud/utils/component/ComponentLibrary.java @@ -0,0 +1,30 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.utils.component; + +import java.util.List; +import java.util.Map; + +import com.cloud.utils.component.ComponentLocator.ComponentInfo; +import com.cloud.utils.db.GenericDao; + +public interface ComponentLibrary { + Map>> getDaos(); + Map> getManagers(); + Map>> getAdapters(); +} diff --git a/utils/src/com/cloud/utils/component/ComponentLocator.java b/utils/src/com/cloud/utils/component/ComponentLocator.java index ce4c9fc10c4..5ad8b8d630d 100755 --- a/utils/src/com/cloud/utils/component/ComponentLocator.java +++ b/utils/src/com/cloud/utils/component/ComponentLocator.java @@ -19,6 +19,7 @@ package com.cloud.utils.component; import java.io.File; import java.io.IOException; +import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; @@ -55,6 +56,7 @@ import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; +import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.db.DatabaseCallback; import com.cloud.utils.db.DatabaseCallbackFilter; @@ -74,22 +76,19 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { protected static final Logger s_logger = Logger.getLogger(ComponentLocator.class); protected static HashMap s_singletons = new HashMap(111); - - protected HashMap> _adapterMap; - protected HashMap> _managerMap; - protected LinkedHashMap>> _daoMap; - protected static HashMap _componentMap = new HashMap(); - protected static HashMap _implementationClassMap = new HashMap(); - protected ComponentLocator _parentLocator; - protected String _serverName; private static boolean s_doOnce = false; - protected static final Callback[] s_callbacks = new Callback[] { NoOp.INSTANCE, new DatabaseCallback() }; protected static final CallbackFilter s_callbackFilter = new DatabaseCallbackFilter(); - protected static final HashMap, InjectInfo> s_factories = new HashMap, InjectInfo>(); - protected static HashMap s_locatorMap = new HashMap(); + protected static HashMap _componentMap = new HashMap(); + protected static HashMap _implementationClassMap = new HashMap(); + + protected HashMap> _adapterMap; + protected HashMap> _managerMap; + protected LinkedHashMap>> _daoMap; + protected ComponentLocator _parentLocator; + protected String _serverName; public ComponentLocator(String server) { _parentLocator = null; @@ -114,9 +113,9 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { } } - Iterator> itManagers = _managerMap.values().iterator(); + Iterator> itManagers = _managerMap.values().iterator(); while (itManagers.hasNext()) { - Info manager = itManagers.next(); + ComponentInfo manager = itManagers.next(); itManagers.remove(); manager.instance.stop(); } @@ -130,9 +129,9 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { if (file == null) { s_logger.warn("Unable to find the config file automatically. Now checking properties files."); _parentLocator = null; - _managerMap = new HashMap>(); + _managerMap = new HashMap>(); _adapterMap = new HashMap>(); - _daoMap = new LinkedHashMap>>(); + _daoMap = new LinkedHashMap>>(); _parentLocator = null; return; } @@ -144,8 +143,19 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { _parentLocator = getLocatorInternal(handler.parent, false, filename, log4jFile); } - _managerMap = handler.managers; - _daoMap = handler.daos; + _daoMap = new LinkedHashMap>>(); + _managerMap = new LinkedHashMap>(); + _adapterMap = new HashMap>(); + if (handler.library != null) { + Class clazz = Class.forName(handler.library); + ComponentLibrary library = (ComponentLibrary)clazz.newInstance(); + _managerMap.putAll(library.getManagers()); + _daoMap.putAll(library.getDaos()); + createAdaptersMap(library.getAdapters()); + } + + _managerMap.putAll(handler.managers); + _daoMap.putAll(handler.daos); startDaos(); // daos should not be using managers and adapters. createAdaptersMap(handler.adapters); @@ -178,10 +188,10 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { * here. */ protected void startDaos() { - Set>>> entries = _daoMap.entrySet(); + Set>>> entries = _daoMap.entrySet(); - for (Map.Entry>> entry : entries) { - Info> info = entry.getValue(); + for (Map.Entry>> entry : entries) { + ComponentInfo> info = entry.getValue(); s_logger.info("Starting DAO: " + info.name); try { info.instance = (GenericDao)createInstance(info.clazz, true, info.singleton); @@ -272,8 +282,8 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { } - protected Info> getDao(String name) { - Info> info = _daoMap.get(name); + protected ComponentInfo> getDao(String name) { + ComponentInfo> info = _daoMap.get(name); if (info != null) { return info; } @@ -326,15 +336,15 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { return null; } - public T getDao(Class clazz) { - Info> info = getDao(clazz.getName()); + public > T getDao(Class clazz) { + ComponentInfo> info = getDao(clazz.getName()); return info != null ? (T)info.instance : null; } protected void instantiateManagers() { - Set>> entries = _managerMap.entrySet(); - for (Map.Entry> entry : entries) { - Info info = entry.getValue(); + Set>> entries = _managerMap.entrySet(); + for (Map.Entry> entry : entries) { + ComponentInfo info = entry.getValue(); if (info.instance == null) { s_logger.info("Instantiating Manager: " + info.name); info.instance = (Manager)createInstance(info.clazz, false, info.singleton); @@ -343,14 +353,14 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { } protected void configureManagers() { - Set>> entries = _managerMap.entrySet(); - for (Map.Entry> entry : entries) { - Info info = entry.getValue(); + Set>> entries = _managerMap.entrySet(); + for (Map.Entry> entry : entries) { + ComponentInfo info = entry.getValue(); s_logger.info("Injecting Manager: " + info.name); inject(info.clazz, info.instance); } - for (Map.Entry> entry : entries) { - Info info = entry.getValue(); + for (Map.Entry> entry : entries) { + ComponentInfo info = entry.getValue(); s_logger.info("Configuring Manager: " + info.name); try { info.instance.configure(info.name, info.params); @@ -376,7 +386,7 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { if (Manager.class.isAssignableFrom(fc)) { instance = locator.getManager(fc); } else if (GenericDao.class.isAssignableFrom(fc)) { - instance = locator.getDao(fc); + instance = locator.getDao((Class>)fc); } else if (Adapters.class.isAssignableFrom(fc)) { instance = locator.getAdapters(inject.adapter()); } else { @@ -401,9 +411,9 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { } protected void startManagers() { - Set>> entries = _managerMap.entrySet(); - for (Map.Entry> entry : entries) { - Info info = entry.getValue(); + Set>> entries = _managerMap.entrySet(); + for (Map.Entry> entry : entries) { + ComponentInfo info = entry.getValue(); s_logger.info("Starting Manager: " + info.name); if (!info.instance.start()) { throw new CloudRuntimeException("Incorrect Configuration: " + info.name); @@ -430,8 +440,8 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { s_logger.info("Registered MBean: " + mbean.getName()); } - protected Info getManager(String name) { - Info mgr = _managerMap.get(name); + protected ComponentInfo getManager(String name) { + ComponentInfo mgr = _managerMap.get(name); if (mgr != null) { return mgr; } @@ -449,7 +459,7 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { } public T getManager(Class clazz) { - Info info = getManager(clazz.getName()); + ComponentInfo info = getManager(clazz.getName()); if (info == null) { return null; } @@ -459,12 +469,12 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { return (T)info.instance; } - protected void instantiateAdapters(Map>> map) { - Set>>> entries = map.entrySet(); - for (Map.Entry>> entry : entries) { + protected void instantiateAdapters(Map>> map) { + Set>>> entries = map.entrySet(); + for (Map.Entry>> entry : entries) { Adapters adapters = (Adapters)_adapterMap.get(entry.getKey()); List lst = new ArrayList(); - for (Info info : entry.getValue()) { + for (ComponentInfo info : entry.getValue()) { s_logger.info("Instantiating Adapter: " + info.name); info.instance = (Adapter)createInstance(info.clazz, true, info.singleton); try { @@ -486,10 +496,9 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { } } - protected void createAdaptersMap(Map>> map) { - _adapterMap = new HashMap>(map.size()); - Set>>> entries = map.entrySet(); - for (Map.Entry>> entry : entries) { + protected void createAdaptersMap(Map>> map) { + Set>>> entries = map.entrySet(); + for (Map.Entry>> entry : entries) { List lst = new ArrayList(entry.getValue().size()); _adapterMap.put(entry.getKey(), new Adapters(entry.getKey(), lst)); } @@ -550,7 +559,7 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { @Override public Collection getManagers() { Collection names = _parentLocator != null ? _parentLocator.getManagers() : new HashSet(); - for (Map.Entry> entry : _managerMap.entrySet()) { + for (Map.Entry> entry : _managerMap.entrySet()) { names.add(entry.getValue().name); } return names; @@ -559,7 +568,7 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { @Override public Collection getDaos() { Collection names = _parentLocator != null ? _parentLocator.getDaos() : new HashSet(); - for (Map.Entry>> entry : _daoMap.entrySet()) { + for (Map.Entry>> entry : _daoMap.entrySet()) { names.add(entry.getValue().name); } return names; @@ -637,13 +646,65 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { return s_tl.get(); } - protected class Info { + public static class ComponentInfo { Class clazz; HashMap params = new HashMap(); String name; List keys = new ArrayList(); T instance; boolean singleton = true; + + protected ComponentInfo() { + } + + public List getKeys() { + return keys; + } + + public String getName() { + return name; + } + + public ComponentInfo(String name, Class clazz) { + this(name, clazz, new ArrayList>(0)); + } + + public ComponentInfo(String name, Class clazz, List> params) { + this(name, clazz, params, true); + } + + public ComponentInfo(String name, Class clazz, List> params, boolean singleton) { + this.name = name; + this.clazz = clazz; + this.singleton = singleton; + for (Pair param : params) { + this.params.put(param.first(), param.second()); + } + fillInfo(); + } + + protected void fillInfo() { + String clazzName = clazz.getName(); + + Local local = clazz.getAnnotation(Local.class); + if (local == null) { + throw new CloudRuntimeException("Unable to find Local annotation for class " + clazzName); + } + + // Verify that all interfaces specified in the Local annotation is implemented by the class. + Class[] classes = local.value(); + for (int i = 0; i < classes.length; i++) { + if (!classes[i].isInterface()) { + throw new CloudRuntimeException(classes[i].getName() + " is not an interface"); + } + if (classes[i].isAssignableFrom(clazz)) { + keys.add(classes[i].getName()); + s_logger.info("Found component: " + classes[i].getName() + " in " + clazzName + " - " + name); + } else { + throw new CloudRuntimeException(classes[i].getName() + " is not implemented by " + clazzName); + } + } + } } /** @@ -651,29 +712,30 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { * It builds a hash map of lists of adapters and a hash map of managers. **/ protected class XmlHandler extends DefaultHandler { - public HashMap>> adapters; - public HashMap> managers; - public LinkedHashMap>> daos; + public HashMap>> adapters; + public HashMap> managers; + public LinkedHashMap>> daos; public String parent; + public String library; - List> lst; + List> lst; String paramName; StringBuilder value; String serverName; boolean parse; - Info currentInfo; + ComponentInfo currentInfo; public XmlHandler(String serverName) { this.serverName = serverName; parse = false; - adapters = new HashMap>>(); - managers = new HashMap>(); - daos = new LinkedHashMap>>(); + adapters = new HashMap>>(); + managers = new HashMap>(); + daos = new LinkedHashMap>>(); value = null; parent = null; } - protected void fillInfo(Attributes atts, Class interphace, Info info) { + protected void fillInfo(Attributes atts, Class interphace, ComponentInfo info) { String clazzName = getAttribute(atts, "class"); if (clazzName == null) { throw new CloudRuntimeException("Missing class attribute for " + interphace.getName()); @@ -696,43 +758,9 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { throw new CloudRuntimeException("Class " + info.clazz.toString() + " does not implment " + interphace); } - Local local = info.clazz.getAnnotation(Local.class); - if (local == null) { - throw new CloudRuntimeException("Unable to find Local annotation for class " + clazzName); - } - - Class[] classes = local.value(); - for (int i = 0; i < classes.length; i++) { - if (!classes[i].isInterface()) { - throw new CloudRuntimeException(classes[i].getName() + " is not an interface"); - } - if (classes[i].isAssignableFrom(info.clazz)) { - info.keys.add(classes[i].getName()); - s_logger.info("Found component: " + classes[i].getName() + " in " + clazzName + " - " + info.name); - } else { - throw new CloudRuntimeException(classes[i].getName() + " is not implemented by " + info.clazz.getName()); - } - } - - if (info.keys.size() != classes.length) { - throw new CloudRuntimeException("Class " + clazzName + " does not implement " + interphace.getName()); - } + info.fillInfo(); } - protected boolean findInterfaceInHierarchy(Class[] interphaces, Class interphace) { - if (interphaces == null) { - return false; - } - - for (int j = 0; j < interphaces.length; j++) { - if (interphaces[j] == interphace || findInterfaceInHierarchy(interphaces[j].getInterfaces(), interphace)) { - return true; - } - } - - return false; - } - @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { @@ -745,21 +773,23 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { if (implementationClass != null) { _implementationClassMap.put(_serverName, implementationClass); } + + library = getAttribute(atts, "library"); } } else if (qName.equals("adapters")) { - lst = new ArrayList>(); + lst = new ArrayList>(); String key = getAttribute(atts, "key"); if (key == null) { throw new CloudRuntimeException("Missing key attribute for adapters"); } adapters.put(key, lst); } else if (qName.equals("adapter")) { - Info info = new Info(); + ComponentInfo info = new ComponentInfo(); fillInfo(atts, Adapter.class, info); lst.add(info); currentInfo = info; } else if (qName.equals("manager")) { - Info info = new Info(); + ComponentInfo info = new ComponentInfo(); fillInfo(atts, Manager.class, info); s_logger.info("Adding Manager: " + info.name); for (String key : info.keys) { @@ -771,7 +801,7 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean { paramName = getAttribute(atts, "name"); value = new StringBuilder(); } else if (qName.equals("dao")) { - Info> info = new Info>(); + ComponentInfo> info = new ComponentInfo>(); fillInfo(atts, GenericDao.class, info); for (String key : info.keys) { daos.put(key, info);