From 59436be4eeb2c3b10e2ce3e4e73cfc2ec8cc0ade Mon Sep 17 00:00:00 2001 From: David Nalley Date: Sat, 7 Apr 2012 20:13:10 -0400 Subject: [PATCH] fixing line endings in server --- server/conf/migration-components.xml | 56 +- .../manager/ClusteredAgentManagerImpl.java | 2114 +++--- .../agent/manager/ConnectedAgentAttache.java | 106 +- .../impl/FirstFitRoutingAllocator.java | 38 +- .../src/com/cloud/alert/AlertManagerImpl.java | 650 +- .../cloud/alert/ConsoleProxyAlertAdapter.java | 428 +- .../alert/SecondaryStorageVmAlertAdapter.java | 394 +- server/src/com/cloud/alert/dao/AlertDao.java | 12 +- .../src/com/cloud/alert/dao/AlertDaoImpl.java | 46 +- server/src/com/cloud/api/ApiGsonHelper.java | 26 +- .../src/com/cloud/api/ApiResponseHelper.java | 6680 ++++++++--------- .../com/cloud/api/ApiSerializerHelper.java | 130 +- .../com/cloud/api/IdentityTypeAdapter.java | 130 +- .../com/cloud/api/SerializationContext.java | 54 +- .../api/commands/GenerateUsageRecordsCmd.java | 152 +- .../api/commands/GetUsageRecordsCmd.java | 384 +- .../SecurityGroupRuleResultObject.java | 186 +- .../src/com/cloud/async/AsyncJobExecutor.java | 44 +- .../cloud/async/AsyncJobExecutorContext.java | 32 +- .../async/AsyncJobExecutorContextImpl.java | 332 +- .../src/com/cloud/async/AsyncJobManager.java | 36 +- .../com/cloud/async/AsyncJobManagerImpl.java | 538 +- .../src/com/cloud/async/AsyncJobResult.java | 180 +- .../com/cloud/async/BaseAsyncJobExecutor.java | 104 +- .../src/com/cloud/async/SyncQueueManager.java | 20 +- .../com/cloud/async/SyncQueueManagerImpl.java | 406 +- .../src/com/cloud/async/dao/AsyncJobDao.java | 10 +- .../com/cloud/async/dao/AsyncJobDaoImpl.java | 70 +- .../src/com/cloud/async/dao/SyncQueueDao.java | 12 +- .../com/cloud/async/dao/SyncQueueDaoImpl.java | 72 +- .../com/cloud/async/dao/SyncQueueItemDao.java | 16 +- .../cloud/async/dao/SyncQueueItemDaoImpl.java | 144 +- .../executor/ExtractJobResultObject.java | 334 +- .../com/cloud/capacity/dao/CapacityDao.java | 10 +- .../cloud/capacity/dao/CapacityDaoImpl.java | 64 +- .../com/cloud/cluster/CheckPointManager.java | 72 +- .../cloud/cluster/CheckPointManagerImpl.java | 400 +- .../src/com/cloud/cluster/CheckPointVO.java | 208 +- .../src/com/cloud/cluster/ClusterManager.java | 54 +- .../cloud/cluster/ClusterManagerListener.java | 14 +- .../cluster/ClusterNodeJoinEventArgs.java | 52 +- .../cluster/ClusterNodeLeftEventArgs.java | 52 +- .../src/com/cloud/cluster/ClusterService.java | 8 +- .../cloud/cluster/ClusterServiceAdapter.java | 24 +- .../cluster/ClusterServiceServletAdapter.java | 178 +- .../ClusterServiceServletContainer.java | 270 +- .../ClusterServiceServletHttpHandler.java | 208 +- .../cluster/ClusterServiceServletImpl.java | 118 +- .../cluster/DummyClusterManagerImpl.java | 174 +- .../cloud/cluster/ManagementServerHostVO.java | 238 +- .../cloud/cluster/RemoteMethodConstants.java | 10 +- server/src/com/cloud/cluster/StackMaid.java | 274 +- .../cluster/dao/ManagementServerHostDao.java | 18 +- .../dao/ManagementServerHostDaoImpl.java | 136 +- .../com/cloud/cluster/dao/StackMaidDao.java | 54 +- .../cloud/cluster/dao/StackMaidDaoImpl.java | 322 +- .../configuration/dao/ConfigurationDao.java | 60 +- .../dao/ConfigurationDaoImpl.java | 148 +- .../AgentBasedConsoleProxyManager.java | 2 +- .../ConsoleProxyAlertEventArgs.java | 106 +- .../ConsoleProxyBalanceAllocator.java | 106 +- server/src/com/cloud/dc/DataCenterVO.java | 196 +- server/src/com/cloud/dc/HostPodVO.java | 168 +- .../cloud/dc/StorageNetworkIpAddressVO.java | 204 +- .../com/cloud/dc/StorageNetworkIpRangeVO.java | 322 +- server/src/com/cloud/dc/dao/HostPodDao.java | 20 +- .../src/com/cloud/dc/dao/HostPodDaoImpl.java | 124 +- .../dc/dao/StorageNetworkIpAddressDao.java | 32 +- .../dao/StorageNetworkIpAddressDaoImpl.java | 190 +- .../dc/dao/StorageNetworkIpRangeDao.java | 32 +- .../dc/dao/StorageNetworkIpRangeDaoImpl.java | 118 +- .../deploy/UserConcentratedPodPlanner.java | 278 +- .../cloud/deploy/UserDispersingPlanner.java | 406 +- server/src/com/cloud/domain/DomainVO.java | 224 +- .../src/com/cloud/domain/dao/DomainDao.java | 12 +- .../com/cloud/domain/dao/DomainDaoImpl.java | 266 +- .../cloud/ha/AbstractInvestigatorImpl.java | 120 +- .../ha/ManagementIPSystemVMInvestigator.java | 106 +- .../com/cloud/ha/UserVmDomRInvestigator.java | 170 +- server/src/com/cloud/host/dao/HostDao.java | 38 +- .../src/com/cloud/host/dao/HostDaoImpl.java | 18 +- .../src/com/cloud/host/dao/HostTagsDao.java | 28 +- .../dao/HypervisorCapabilitiesDao.java | 34 +- .../dao/HypervisorCapabilitiesDaoImpl.java | 180 +- .../com/cloud/hypervisor/guru/VMwareGuru.java | 176 +- .../hypervisor/vmware/VmwareManagerImpl.java | 4 +- .../vmware/VmwareServerDiscoverer.java | 466 +- .../cloud/migration/DiskOffering20Dao.java | 12 +- .../migration/DiskOffering20DaoImpl.java | 18 +- .../com/cloud/migration/DiskOffering20VO.java | 192 +- .../cloud/migration/DiskOffering21Dao.java | 14 +- .../migration/DiskOffering21DaoImpl.java | 18 +- .../com/cloud/migration/DiskOffering21VO.java | 456 +- .../cloud/migration/ServiceOffering20Dao.java | 12 +- .../migration/ServiceOffering20DaoImpl.java | 18 +- .../cloud/migration/ServiceOffering20VO.java | 336 +- .../cloud/migration/ServiceOffering21Dao.java | 12 +- .../migration/ServiceOffering21DaoImpl.java | 18 +- .../cloud/migration/ServiceOffering21VO.java | 248 +- .../ExternalLoadBalancerUsageManagerImpl.java | 1092 +-- server/src/com/cloud/network/IPAddressVO.java | 166 +- .../cloud/network/LBStickinessPolicyVO.java | 8 +- .../cloud/network/LoadBalancerVMMapVO.java | 72 +- .../src/com/cloud/network/LoadBalancerVO.java | 56 +- .../cloud/network/NetworkRuleConfigVO.java | 150 +- .../com/cloud/network/RemoteAccessVpnVO.java | 54 +- .../cloud/network/StorageNetworkManager.java | 38 +- .../network/StorageNetworkManagerImpl.java | 738 +- .../com/cloud/network/dao/IPAddressDao.java | 26 +- .../network/dao/LBStickinessPolicyDao.java | 8 +- .../dao/LBStickinessPolicyDaoImpl.java | 6 +- .../network/dao/LoadBalancerVMMapDao.java | 18 +- .../network/dao/LoadBalancerVMMapDaoImpl.java | 78 +- .../network/dao/NetworkRuleConfigDao.java | 18 +- .../network/dao/NetworkRuleConfigDaoImpl.java | 50 +- .../cloud/network/dao/RemoteAccessVpnDao.java | 12 +- .../network/dao/RemoteAccessVpnDaoImpl.java | 36 +- .../src/com/cloud/network/dao/VpnUserDao.java | 12 +- .../com/cloud/network/dao/VpnUserDaoImpl.java | 20 +- .../element/VirtualRouterProviderVO.java | 4 +- .../network/guru/StorageNetworkGuru.java | 354 +- .../network/lb/dao/ElasticLbVmMapDao.java | 18 +- .../network/ovs/dao/OvsTunnelAccountDao.java | 26 +- .../ovs/dao/OvsTunnelAccountDaoImpl.java | 146 +- .../network/ovs/dao/OvsTunnelAccountVO.java | 176 +- .../network/rules/PortForwardingRuleVO.java | 50 +- .../security/dao/SecurityGroupDao.java | 18 +- .../security/dao/SecurityGroupDaoImpl.java | 70 +- .../security/dao/SecurityGroupRuleDao.java | 18 +- .../dao/SecurityGroupRuleDaoImpl.java | 50 +- .../security/dao/SecurityGroupRulesDao.java | 64 +- .../dao/SecurityGroupRulesDaoImpl.java | 136 +- .../security/dao/SecurityGroupVMMapDao.java | 20 +- .../dao/SecurityGroupVMMapDaoImpl.java | 122 +- .../security/dao/SecurityGroupWorkDao.java | 12 +- .../dao/SecurityGroupWorkDaoImpl.java | 44 +- .../network/security/dao/VmRulesetLogDao.java | 12 +- .../security/dao/VmRulesetLogDaoImpl.java | 44 +- .../cloud/resource/DummyHostDiscoverer.java | 122 +- .../resource/DummyHostServerResource.java | 262 +- .../cloud/resource/ResourceStateAdapter.java | 94 +- .../com/cloud/server/ManagementServerExt.java | 74 +- .../cloud/server/ManagementServerExtImpl.java | 344 +- .../src/com/cloud/server/StatsCollector.java | 382 +- .../server/auth/DefaultUserAuthenticator.java | 72 +- .../server/auth/LDAPUserAuthenticator.java | 294 +- .../server/auth/MD5UserAuthenticator.java | 116 +- .../cloud/server/auth/UserAuthenticator.java | 38 +- .../com/cloud/service/ServiceOfferingVO.java | 168 +- .../cloud/service/dao/ServiceOfferingDao.java | 16 +- .../service/dao/ServiceOfferingDaoImpl.java | 18 +- .../cloud/servlet/CloudStartupServlet.java | 42 +- .../cloud/servlet/ConsoleProxyServlet.java | 258 +- .../src/com/cloud/storage/OCFS2Manager.java | 30 +- .../com/cloud/storage/OCFS2ManagerImpl.java | 430 +- .../src/com/cloud/storage/StorageManager.java | 310 +- .../cloud/storage/dao/DiskOfferingDao.java | 12 +- .../storage/dao/DiskOfferingDaoImpl.java | 42 +- .../storage/dao/LaunchPermissionDao.java | 82 +- .../storage/dao/LaunchPermissionDaoImpl.java | 236 +- .../com/cloud/storage/dao/SnapshotDao.java | 16 +- .../cloud/storage/dao/SnapshotPolicyDao.java | 26 +- .../storage/dao/SnapshotPolicyDaoImpl.java | 78 +- .../storage/dao/SnapshotScheduleDao.java | 34 +- .../com/cloud/storage/dao/StoragePoolDao.java | 2 +- .../com/cloud/storage/dao/SwiftDaoImpl.java | 4 +- .../com/cloud/storage/dao/VMTemplateDao.java | 34 +- .../cloud/storage/dao/VMTemplateDaoImpl.java | 248 +- .../storage/dao/VMTemplateDetailsDao.java | 32 +- .../storage/dao/VMTemplateDetailsDaoImpl.java | 160 +- .../storage/dao/VMTemplateHostDaoImpl.java | 330 +- .../cloud/storage/dao/VMTemplatePoolDao.java | 56 +- .../storage/dao/VMTemplatePoolDaoImpl.java | 440 +- .../storage/dao/VMTemplateZoneDaoImpl.java | 114 +- .../DummySecondaryStorageResource.java | 198 +- .../secondary/SecStorageVmAlertEventArgs.java | 106 +- .../SecondaryStorageVmAllocator.java | 18 +- .../SecondaryStorageVmDefaultAllocator.java | 88 +- .../secondary/SecondaryStorageVmManager.java | 28 +- .../upgrade/DatabaseIntegrityChecker.java | 458 +- .../cloud/upgrade/dao/Upgrade2214to30.java | 2 +- server/src/com/cloud/usage/StorageTypes.java | 14 +- .../src/com/cloud/usage/UsageIPAddressVO.java | 176 +- server/src/com/cloud/usage/UsageJobVO.java | 324 +- .../usage/UsageLoadBalancerPolicyVO.java | 146 +- .../cloud/usage/UsageNetworkOfferingVO.java | 178 +- .../src/com/cloud/usage/UsageNetworkVO.java | 224 +- .../usage/UsagePortForwardingRuleVO.java | 146 +- .../com/cloud/usage/UsageSecurityGroupVO.java | 156 +- .../src/com/cloud/usage/UsageStorageVO.java | 178 +- server/src/com/cloud/usage/UsageTypes.java | 34 +- .../com/cloud/usage/UsageVMInstanceVO.java | 210 +- server/src/com/cloud/usage/UsageVO.java | 412 +- .../src/com/cloud/usage/UsageVPNUserVO.java | 144 +- server/src/com/cloud/usage/UsageVolumeVO.java | 194 +- server/src/com/cloud/usage/dao/UsageDao.java | 48 +- .../src/com/cloud/usage/dao/UsageDaoImpl.java | 498 +- .../cloud/usage/dao/UsageIPAddressDao.java | 24 +- .../usage/dao/UsageIPAddressDaoImpl.java | 252 +- .../src/com/cloud/usage/dao/UsageJobDao.java | 36 +- .../com/cloud/usage/dao/UsageJobDaoImpl.java | 364 +- .../usage/dao/UsageLoadBalancerPolicyDao.java | 26 +- .../dao/UsageLoadBalancerPolicyDaoImpl.java | 302 +- .../com/cloud/usage/dao/UsageNetworkDao.java | 22 +- .../cloud/usage/dao/UsageNetworkDaoImpl.java | 160 +- .../usage/dao/UsageNetworkOfferingDao.java | 24 +- .../dao/UsageNetworkOfferingDaoImpl.java | 268 +- .../usage/dao/UsagePortForwardingRuleDao.java | 26 +- .../dao/UsagePortForwardingRuleDaoImpl.java | 302 +- .../usage/dao/UsageSecurityGroupDao.java | 14 +- .../usage/dao/UsageSecurityGroupDaoImpl.java | 266 +- .../com/cloud/usage/dao/UsageStorageDao.java | 30 +- .../cloud/usage/dao/UsageStorageDaoImpl.java | 384 +- .../cloud/usage/dao/UsageVMInstanceDao.java | 26 +- .../usage/dao/UsageVMInstanceDaoImpl.java | 238 +- .../com/cloud/usage/dao/UsageVPNUserDao.java | 24 +- .../cloud/usage/dao/UsageVPNUserDaoImpl.java | 262 +- .../com/cloud/usage/dao/UsageVolumeDao.java | 26 +- .../cloud/usage/dao/UsageVolumeDaoImpl.java | 320 +- .../src/com/cloud/user/AccountDetailVO.java | 110 +- .../src/com/cloud/user/AccountDetailsDao.java | 42 +- .../com/cloud/user/AccountDetailsDaoImpl.java | 154 +- server/src/com/cloud/user/dao/AccountDao.java | 22 +- .../com/cloud/user/dao/AccountDaoImpl.java | 236 +- .../com/cloud/user/dao/UserAccountDao.java | 14 +- .../cloud/user/dao/UserAccountDaoImpl.java | 52 +- server/src/com/cloud/user/dao/UserDao.java | 44 +- .../src/com/cloud/user/dao/UserDaoImpl.java | 172 +- .../com/cloud/user/dao/UserStatisticsDao.java | 30 +- .../cloud/user/dao/UserStatisticsDaoImpl.java | 132 +- .../com/cloud/user/dao/UserStatsLogDao.java | 10 +- .../cloud/user/dao/UserStatsLogDaoImpl.java | 10 +- .../cloud/uuididentity/dao/IdentityDao.java | 22 +- .../uuididentity/dao/IdentityDaoImpl.java | 360 +- .../cloud/uuididentity/dao/IdentityVO.java | 18 +- .../src/com/cloud/vm/dao/ConsoleProxyDao.java | 42 +- .../com/cloud/vm/dao/ConsoleProxyDaoImpl.java | 538 +- .../cloud/vm/dao/SecondaryStorageVmDao.java | 22 +- .../vm/dao/SecondaryStorageVmDaoImpl.java | 196 +- .../src/com/cloud/vm/dao/UserVmDaoImpl.java | 1066 +-- server/test/async-job-component.xml | 370 +- .../agent/manager/ResourceManagerTest.java | 728 +- .../agent/manager/SearchCriteria2Test.java | 166 +- .../test/com/cloud/async/CleanupDelegate.java | 26 +- server/test/com/cloud/async/TestAsync.java | 198 +- .../com/cloud/async/TestAsyncJobManager.java | 422 +- .../com/cloud/async/TestSyncQueueManager.java | 348 +- .../cloud/network/MockNetworkManagerImpl.java | 1704 ++--- server/test/sync-queue-component.xml | 16 +- 249 files changed, 23153 insertions(+), 23153 deletions(-) diff --git a/server/conf/migration-components.xml b/server/conf/migration-components.xml index 1a24e58eb0d..12736375c7d 100644 --- a/server/conf/migration-components.xml +++ b/server/conf/migration-components.xml @@ -1,28 +1,28 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index a274803872b..0ff3d666856 100755 --- a/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -10,435 +10,435 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent.manager; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; -import java.util.ArrayList; -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.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; - -import org.apache.log4j.Logger; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CancelCommand; -import com.cloud.agent.api.ChangeAgentCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.TransferAgentCommand; -import com.cloud.agent.transport.Request; -import com.cloud.agent.transport.Request.Version; -import com.cloud.agent.transport.Response; -import com.cloud.cluster.ClusterManager; -import com.cloud.cluster.ClusterManagerListener; -import com.cloud.cluster.ClusteredAgentRebalanceService; -import com.cloud.cluster.ManagementServerHost; -import com.cloud.cluster.ManagementServerHostVO; -import com.cloud.cluster.StackMaid; -import com.cloud.cluster.agentlb.AgentLoadBalancerPlanner; -import com.cloud.cluster.agentlb.HostTransferMapVO; -import com.cloud.cluster.agentlb.HostTransferMapVO.HostTransferState; -import com.cloud.cluster.agentlb.dao.HostTransferMapDao; -import com.cloud.cluster.dao.ManagementServerHostDao; -import com.cloud.configuration.Config; -import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.host.Status.Event; -import com.cloud.resource.ServerResource; -import com.cloud.storage.resource.DummySecondaryStorageResource; -import com.cloud.utils.DateUtil; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.Adapters; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.Inject; -import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.nio.Link; -import com.cloud.utils.nio.Task; - -@Local(value = { AgentManager.class, ClusteredAgentRebalanceService.class }) -public class ClusteredAgentManagerImpl extends AgentManagerImpl implements ClusterManagerListener, ClusteredAgentRebalanceService { - final static Logger s_logger = Logger.getLogger(ClusteredAgentManagerImpl.class); - private static final ScheduledExecutorService s_transferExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Cluster-AgentTransferExecutor")); - private final long rebalanceTimeOut = 300000; // 5 mins - after this time remove the agent from the transfer list - - public final static long STARTUP_DELAY = 5000; - public final static long SCAN_INTERVAL = 90000; // 90 seconds, it takes 60 sec for xenserver to fail login - public final static int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds - public long _loadSize = 100; - protected Set _agentToTransferIds = new HashSet(); - - @Inject - protected ClusterManager _clusterMgr = null; - - protected HashMap _peers; - protected HashMap _sslEngines; - private final Timer _timer = new Timer("ClusteredAgentManager Timer"); - - @Inject - protected ManagementServerHostDao _mshostDao; - @Inject - protected HostTransferMapDao _hostTransferDao; - - @Inject(adapter = AgentLoadBalancerPlanner.class) - protected Adapters _lbPlanners; - - @Inject - protected AgentManager _agentMgr; - - protected ClusteredAgentManagerImpl() { - super(); - } - - @Override - public boolean configure(String name, Map xmlParams) throws ConfigurationException { - _peers = new HashMap(7); - _sslEngines = new HashMap(7); - _nodeId = _clusterMgr.getManagementNodeId(); - - s_logger.info("Configuring ClusterAgentManagerImpl. management server node id(msid): " + _nodeId); - - ConfigurationDao configDao = ComponentLocator.getCurrentLocator().getDao(ConfigurationDao.class); - Map params = configDao.getConfiguration(xmlParams); - String value = params.get(Config.DirectAgentLoadSize.key()); - _loadSize = NumbersUtil.parseInt(value, 16); - - ClusteredAgentAttache.initialize(this); - - _clusterMgr.registerListener(this); - - return super.configure(name, xmlParams); - } - - @Override - public boolean start() { - if (!super.start()) { - return false; - } - _timer.schedule(new DirectAgentScanTimerTask(), STARTUP_DELAY, SCAN_INTERVAL); - - // schedule transfer scan executor - if agent LB is enabled - if (_clusterMgr.isAgentRebalanceEnabled()) { - s_transferExecutor.scheduleAtFixedRate(getTransferScanTask(), 60000, ClusteredAgentRebalanceService.DEFAULT_TRANSFER_CHECK_INTERVAL, - TimeUnit.MILLISECONDS); - } - - return true; - } - - private void runDirectAgentScanTimerTask() { - scanDirectAgentToLoad(); - } - - private void scanDirectAgentToLoad() { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Begin scanning directly connected hosts"); - } - - // for agents that are self-managed, threshold to be considered as disconnected is 3 ping intervals - long cutSeconds = (System.currentTimeMillis() >> 10) - (_pingInterval * 3); - List hosts = _hostDao.findAndUpdateDirectAgentToLoad(cutSeconds, _loadSize, _nodeId); - List appliances = _hostDao.findAndUpdateApplianceToLoad(cutSeconds, _nodeId); - hosts.addAll(appliances); - - if (hosts != null && hosts.size() > 0) { - s_logger.debug("Found " + hosts.size() + " unmanaged direct hosts, processing connect for them..."); - for (HostVO host : hosts) { - try { - AgentAttache agentattache = findAttache(host.getId()); - if (agentattache != null) { - // already loaded, skip - if (agentattache.forForward()) { - if (s_logger.isInfoEnabled()) { - s_logger.info(host + " is detected down, but we have a forward attache running, disconnect this one before launching the host"); - } - removeAgent(agentattache, Status.Disconnected); - } else { - continue; - } - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ")"); - } - loadDirectlyConnectedHost(host, false); - } catch (Throwable e) { - s_logger.warn(" can not load directly connected host " + host.getId() + "(" + host.getName() + ") due to ",e); - } - } - } - - if (s_logger.isTraceEnabled()) { - s_logger.trace("End scanning directly connected hosts"); - } - } - - private class DirectAgentScanTimerTask extends TimerTask { - @Override - public void run() { - try { - runDirectAgentScanTimerTask(); - } catch (Throwable e) { - s_logger.error("Unexpected exception " + e.getMessage(), e); - } - } - } - - @Override - public Task create(Task.Type type, Link link, byte[] data) { - return new ClusteredAgentHandler(type, link, data); - } - - protected AgentAttache createAttache(long id) { - s_logger.debug("create forwarding ClusteredAgentAttache for " + id); - final AgentAttache attache = new ClusteredAgentAttache(this, id); - AgentAttache old = null; - synchronized (_agents) { - old = _agents.get(id); - _agents.put(id, attache); - } - if (old != null) { - old.disconnect(Status.Removed); - } - return attache; - } - - @Override - protected AgentAttache createAttacheForConnect(HostVO host, Link link) { - s_logger.debug("create ClusteredAgentAttache for " + host.getId()); - final AgentAttache attache = new ClusteredAgentAttache(this, host.getId(), link, host.isInMaintenanceStates()); - link.attach(attache); - AgentAttache old = null; - synchronized (_agents) { - old = _agents.get(host.getId()); - _agents.put(host.getId(), attache); - } - if (old != null) { - old.disconnect(Status.Removed); - } - return attache; - } - - @Override - protected AgentAttache createAttacheForDirectConnect(HostVO host, ServerResource resource) { - if (resource instanceof DummySecondaryStorageResource) { - return new DummyAttache(this, host.getId(), false); - } - s_logger.debug("create ClusteredDirectAgentAttache for " + host.getId()); - final DirectAgentAttache attache = new ClusteredDirectAgentAttache(this, host.getId(), _nodeId, resource, host.isInMaintenanceStates(), this); - AgentAttache old = null; - synchronized (_agents) { - old = _agents.get(host.getId()); - _agents.put(host.getId(), attache); - } - if (old != null) { - old.disconnect(Status.Removed); - } - return attache; - } - - @Override - protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event) { - return handleDisconnect(attache, event, false, true); - } - - @Override - protected boolean handleDisconnectWithInvestigation(AgentAttache attache, Status.Event event) { - return handleDisconnect(attache, event, true, true); - } - - protected boolean handleDisconnect(AgentAttache agent, Status.Event event, boolean investigate, boolean broadcast) { - boolean res; - if (!investigate) { - res = super.handleDisconnectWithoutInvestigation(agent, event); - } else { - res = super.handleDisconnectWithInvestigation(agent, event); - } - - if (res) { - if (broadcast) { - notifyNodesInCluster(agent); - } - return true; - } else { - return false; - } - } - - @Override - public boolean executeUserRequest(long hostId, Event event) throws AgentUnavailableException { - if (event == Event.AgentDisconnected) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Received agent disconnect event for host " + hostId); - } - AgentAttache attache = findAttache(hostId); - if (attache != null) { - handleDisconnect(attache, Event.AgentDisconnected, false, false); - } - - return true; - } else { - return super.executeUserRequest(hostId, event); - } - } - - @Override - public boolean reconnect(final long hostId) { - Boolean result; - try { - result = _clusterMgr.propagateAgentEvent(hostId, Event.ShutdownRequested); - if (result != null) { - return result; - } - } catch (AgentUnavailableException e) { - s_logger.debug("cannot propagate agent reconnect because agent is not available", e); - return false; - } - - return super.reconnect(hostId); - } - - public void notifyNodesInCluster(AgentAttache attache) { - s_logger.debug("Notifying other nodes of to disconnect"); - Command[] cmds = new Command[] { new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected) }; - _clusterMgr.broadcast(attache.getId(), cmds); - } - - protected static void logT(byte[] bytes, final String msg) { - s_logger.trace("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " - + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); - } - - protected static void logD(byte[] bytes, final String msg) { - s_logger.debug("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " - + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); - } - - protected static void logI(byte[] bytes, final String msg) { - s_logger.info("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " - + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); - } - - public boolean routeToPeer(String peer, byte[] bytes) { - int i = 0; - SocketChannel ch = null; - SSLEngine sslEngine = null; - while (i++ < 5) { - ch = connectToPeer(peer, ch); - if (ch == null) { - try { - logD(bytes, "Unable to route to peer: " + Request.parse(bytes).toString()); - } catch (Exception e) { - } - return false; - } - sslEngine = getSSLEngine(peer); - if (sslEngine == null) { - logD(bytes, "Unable to get SSLEngine of peer: " + peer); - return false; - } - try { - if (s_logger.isDebugEnabled()) { - logD(bytes, "Routing to peer"); - } - Link.write(ch, new ByteBuffer[] { ByteBuffer.wrap(bytes) }, sslEngine); - return true; - } catch (IOException e) { - try { - logI(bytes, "Unable to route to peer: " + Request.parse(bytes).toString() + " due to " + e.getMessage()); - } catch (Exception ex) { - } - } - } - return false; - } - - public String findPeer(long hostId) { - return _clusterMgr.getPeerName(hostId); - } - - public SSLEngine getSSLEngine(String peerName) { - return _sslEngines.get(peerName); - } - - public void cancel(String peerName, long hostId, long sequence, String reason) { - CancelCommand cancel = new CancelCommand(sequence, reason); - Request req = new Request(hostId, _nodeId, cancel, true); - req.setControl(true); - routeToPeer(peerName, req.getBytes()); - } - - public void closePeer(String peerName) { - synchronized (_peers) { - SocketChannel ch = _peers.get(peerName); - if (ch != null) { - try { - ch.close(); - } catch (IOException e) { - s_logger.warn("Unable to close peer socket connection to " + peerName); - } - } - _peers.remove(peerName); - _sslEngines.remove(peerName); - } - } - - public SocketChannel connectToPeer(String peerName, SocketChannel prevCh) { - synchronized (_peers) { - SocketChannel ch = _peers.get(peerName); - SSLEngine sslEngine = null; - if (prevCh != null) { - try { - prevCh.close(); - } catch (Exception e) { - } - } - if (ch == null || ch == prevCh) { - ManagementServerHostVO ms = _clusterMgr.getPeer(peerName); - if (ms == null) { - s_logger.info("Unable to find peer: " + peerName); - return null; - } - String ip = ms.getServiceIP(); - InetAddress addr; - try { - addr = InetAddress.getByName(ip); - } catch (UnknownHostException e) { - throw new CloudRuntimeException("Unable to resolve " + ip); - } - try { - ch = SocketChannel.open(new InetSocketAddress(addr, _port)); - ch.configureBlocking(true); // make sure we are working at blocking mode - ch.socket().setKeepAlive(true); - ch.socket().setSoTimeout(60 * 1000); +package com.cloud.agent.manager; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.ArrayList; +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.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; + +import org.apache.log4j.Logger; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.CancelCommand; +import com.cloud.agent.api.ChangeAgentCommand; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.TransferAgentCommand; +import com.cloud.agent.transport.Request; +import com.cloud.agent.transport.Request.Version; +import com.cloud.agent.transport.Response; +import com.cloud.cluster.ClusterManager; +import com.cloud.cluster.ClusterManagerListener; +import com.cloud.cluster.ClusteredAgentRebalanceService; +import com.cloud.cluster.ManagementServerHost; +import com.cloud.cluster.ManagementServerHostVO; +import com.cloud.cluster.StackMaid; +import com.cloud.cluster.agentlb.AgentLoadBalancerPlanner; +import com.cloud.cluster.agentlb.HostTransferMapVO; +import com.cloud.cluster.agentlb.HostTransferMapVO.HostTransferState; +import com.cloud.cluster.agentlb.dao.HostTransferMapDao; +import com.cloud.cluster.dao.ManagementServerHostDao; +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.Status; +import com.cloud.host.Status.Event; +import com.cloud.resource.ServerResource; +import com.cloud.storage.resource.DummySecondaryStorageResource; +import com.cloud.utils.DateUtil; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; +import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.nio.Link; +import com.cloud.utils.nio.Task; + +@Local(value = { AgentManager.class, ClusteredAgentRebalanceService.class }) +public class ClusteredAgentManagerImpl extends AgentManagerImpl implements ClusterManagerListener, ClusteredAgentRebalanceService { + final static Logger s_logger = Logger.getLogger(ClusteredAgentManagerImpl.class); + private static final ScheduledExecutorService s_transferExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Cluster-AgentTransferExecutor")); + private final long rebalanceTimeOut = 300000; // 5 mins - after this time remove the agent from the transfer list + + public final static long STARTUP_DELAY = 5000; + public final static long SCAN_INTERVAL = 90000; // 90 seconds, it takes 60 sec for xenserver to fail login + public final static int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds + public long _loadSize = 100; + protected Set _agentToTransferIds = new HashSet(); + + @Inject + protected ClusterManager _clusterMgr = null; + + protected HashMap _peers; + protected HashMap _sslEngines; + private final Timer _timer = new Timer("ClusteredAgentManager Timer"); + + @Inject + protected ManagementServerHostDao _mshostDao; + @Inject + protected HostTransferMapDao _hostTransferDao; + + @Inject(adapter = AgentLoadBalancerPlanner.class) + protected Adapters _lbPlanners; + + @Inject + protected AgentManager _agentMgr; + + protected ClusteredAgentManagerImpl() { + super(); + } + + @Override + public boolean configure(String name, Map xmlParams) throws ConfigurationException { + _peers = new HashMap(7); + _sslEngines = new HashMap(7); + _nodeId = _clusterMgr.getManagementNodeId(); + + s_logger.info("Configuring ClusterAgentManagerImpl. management server node id(msid): " + _nodeId); + + ConfigurationDao configDao = ComponentLocator.getCurrentLocator().getDao(ConfigurationDao.class); + Map params = configDao.getConfiguration(xmlParams); + String value = params.get(Config.DirectAgentLoadSize.key()); + _loadSize = NumbersUtil.parseInt(value, 16); + + ClusteredAgentAttache.initialize(this); + + _clusterMgr.registerListener(this); + + return super.configure(name, xmlParams); + } + + @Override + public boolean start() { + if (!super.start()) { + return false; + } + _timer.schedule(new DirectAgentScanTimerTask(), STARTUP_DELAY, SCAN_INTERVAL); + + // schedule transfer scan executor - if agent LB is enabled + if (_clusterMgr.isAgentRebalanceEnabled()) { + s_transferExecutor.scheduleAtFixedRate(getTransferScanTask(), 60000, ClusteredAgentRebalanceService.DEFAULT_TRANSFER_CHECK_INTERVAL, + TimeUnit.MILLISECONDS); + } + + return true; + } + + private void runDirectAgentScanTimerTask() { + scanDirectAgentToLoad(); + } + + private void scanDirectAgentToLoad() { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Begin scanning directly connected hosts"); + } + + // for agents that are self-managed, threshold to be considered as disconnected is 3 ping intervals + long cutSeconds = (System.currentTimeMillis() >> 10) - (_pingInterval * 3); + List hosts = _hostDao.findAndUpdateDirectAgentToLoad(cutSeconds, _loadSize, _nodeId); + List appliances = _hostDao.findAndUpdateApplianceToLoad(cutSeconds, _nodeId); + hosts.addAll(appliances); + + if (hosts != null && hosts.size() > 0) { + s_logger.debug("Found " + hosts.size() + " unmanaged direct hosts, processing connect for them..."); + for (HostVO host : hosts) { + try { + AgentAttache agentattache = findAttache(host.getId()); + if (agentattache != null) { + // already loaded, skip + if (agentattache.forForward()) { + if (s_logger.isInfoEnabled()) { + s_logger.info(host + " is detected down, but we have a forward attache running, disconnect this one before launching the host"); + } + removeAgent(agentattache, Status.Disconnected); + } else { + continue; + } + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ")"); + } + loadDirectlyConnectedHost(host, false); + } catch (Throwable e) { + s_logger.warn(" can not load directly connected host " + host.getId() + "(" + host.getName() + ") due to ",e); + } + } + } + + if (s_logger.isTraceEnabled()) { + s_logger.trace("End scanning directly connected hosts"); + } + } + + private class DirectAgentScanTimerTask extends TimerTask { + @Override + public void run() { + try { + runDirectAgentScanTimerTask(); + } catch (Throwable e) { + s_logger.error("Unexpected exception " + e.getMessage(), e); + } + } + } + + @Override + public Task create(Task.Type type, Link link, byte[] data) { + return new ClusteredAgentHandler(type, link, data); + } + + protected AgentAttache createAttache(long id) { + s_logger.debug("create forwarding ClusteredAgentAttache for " + id); + final AgentAttache attache = new ClusteredAgentAttache(this, id); + AgentAttache old = null; + synchronized (_agents) { + old = _agents.get(id); + _agents.put(id, attache); + } + if (old != null) { + old.disconnect(Status.Removed); + } + return attache; + } + + @Override + protected AgentAttache createAttacheForConnect(HostVO host, Link link) { + s_logger.debug("create ClusteredAgentAttache for " + host.getId()); + final AgentAttache attache = new ClusteredAgentAttache(this, host.getId(), link, host.isInMaintenanceStates()); + link.attach(attache); + AgentAttache old = null; + synchronized (_agents) { + old = _agents.get(host.getId()); + _agents.put(host.getId(), attache); + } + if (old != null) { + old.disconnect(Status.Removed); + } + return attache; + } + + @Override + protected AgentAttache createAttacheForDirectConnect(HostVO host, ServerResource resource) { + if (resource instanceof DummySecondaryStorageResource) { + return new DummyAttache(this, host.getId(), false); + } + s_logger.debug("create ClusteredDirectAgentAttache for " + host.getId()); + final DirectAgentAttache attache = new ClusteredDirectAgentAttache(this, host.getId(), _nodeId, resource, host.isInMaintenanceStates(), this); + AgentAttache old = null; + synchronized (_agents) { + old = _agents.get(host.getId()); + _agents.put(host.getId(), attache); + } + if (old != null) { + old.disconnect(Status.Removed); + } + return attache; + } + + @Override + protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event) { + return handleDisconnect(attache, event, false, true); + } + + @Override + protected boolean handleDisconnectWithInvestigation(AgentAttache attache, Status.Event event) { + return handleDisconnect(attache, event, true, true); + } + + protected boolean handleDisconnect(AgentAttache agent, Status.Event event, boolean investigate, boolean broadcast) { + boolean res; + if (!investigate) { + res = super.handleDisconnectWithoutInvestigation(agent, event); + } else { + res = super.handleDisconnectWithInvestigation(agent, event); + } + + if (res) { + if (broadcast) { + notifyNodesInCluster(agent); + } + return true; + } else { + return false; + } + } + + @Override + public boolean executeUserRequest(long hostId, Event event) throws AgentUnavailableException { + if (event == Event.AgentDisconnected) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Received agent disconnect event for host " + hostId); + } + AgentAttache attache = findAttache(hostId); + if (attache != null) { + handleDisconnect(attache, Event.AgentDisconnected, false, false); + } + + return true; + } else { + return super.executeUserRequest(hostId, event); + } + } + + @Override + public boolean reconnect(final long hostId) { + Boolean result; + try { + result = _clusterMgr.propagateAgentEvent(hostId, Event.ShutdownRequested); + if (result != null) { + return result; + } + } catch (AgentUnavailableException e) { + s_logger.debug("cannot propagate agent reconnect because agent is not available", e); + return false; + } + + return super.reconnect(hostId); + } + + public void notifyNodesInCluster(AgentAttache attache) { + s_logger.debug("Notifying other nodes of to disconnect"); + Command[] cmds = new Command[] { new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected) }; + _clusterMgr.broadcast(attache.getId(), cmds); + } + + protected static void logT(byte[] bytes, final String msg) { + s_logger.trace("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + } + + protected static void logD(byte[] bytes, final String msg) { + s_logger.debug("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + } + + protected static void logI(byte[] bytes, final String msg) { + s_logger.info("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + } + + public boolean routeToPeer(String peer, byte[] bytes) { + int i = 0; + SocketChannel ch = null; + SSLEngine sslEngine = null; + while (i++ < 5) { + ch = connectToPeer(peer, ch); + if (ch == null) { + try { + logD(bytes, "Unable to route to peer: " + Request.parse(bytes).toString()); + } catch (Exception e) { + } + return false; + } + sslEngine = getSSLEngine(peer); + if (sslEngine == null) { + logD(bytes, "Unable to get SSLEngine of peer: " + peer); + return false; + } + try { + if (s_logger.isDebugEnabled()) { + logD(bytes, "Routing to peer"); + } + Link.write(ch, new ByteBuffer[] { ByteBuffer.wrap(bytes) }, sslEngine); + return true; + } catch (IOException e) { + try { + logI(bytes, "Unable to route to peer: " + Request.parse(bytes).toString() + " due to " + e.getMessage()); + } catch (Exception ex) { + } + } + } + return false; + } + + public String findPeer(long hostId) { + return _clusterMgr.getPeerName(hostId); + } + + public SSLEngine getSSLEngine(String peerName) { + return _sslEngines.get(peerName); + } + + public void cancel(String peerName, long hostId, long sequence, String reason) { + CancelCommand cancel = new CancelCommand(sequence, reason); + Request req = new Request(hostId, _nodeId, cancel, true); + req.setControl(true); + routeToPeer(peerName, req.getBytes()); + } + + public void closePeer(String peerName) { + synchronized (_peers) { + SocketChannel ch = _peers.get(peerName); + if (ch != null) { + try { + ch.close(); + } catch (IOException e) { + s_logger.warn("Unable to close peer socket connection to " + peerName); + } + } + _peers.remove(peerName); + _sslEngines.remove(peerName); + } + } + + public SocketChannel connectToPeer(String peerName, SocketChannel prevCh) { + synchronized (_peers) { + SocketChannel ch = _peers.get(peerName); + SSLEngine sslEngine = null; + if (prevCh != null) { + try { + prevCh.close(); + } catch (Exception e) { + } + } + if (ch == null || ch == prevCh) { + ManagementServerHostVO ms = _clusterMgr.getPeer(peerName); + if (ms == null) { + s_logger.info("Unable to find peer: " + peerName); + return null; + } + String ip = ms.getServiceIP(); + InetAddress addr; + try { + addr = InetAddress.getByName(ip); + } catch (UnknownHostException e) { + throw new CloudRuntimeException("Unable to resolve " + ip); + } + try { + ch = SocketChannel.open(new InetSocketAddress(addr, _port)); + ch.configureBlocking(true); // make sure we are working at blocking mode + ch.socket().setKeepAlive(true); + ch.socket().setSoTimeout(60 * 1000); try { SSLContext sslContext = Link.initSSLContext(true); sslEngine = sslContext.createSSLEngine(ip, _port); @@ -449,633 +449,633 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } catch (Exception e) { throw new IOException("SSL: Fail to init SSL! " + e); } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Connection to peer opened: " + peerName + ", ip: " + ip); - } - _peers.put(peerName, ch); - _sslEngines.put(peerName, sslEngine); - } catch (IOException e) { - s_logger.warn("Unable to connect to peer management server: " + peerName + ", ip: " + ip + " due to " + e.getMessage(), e); - return null; - } - } - - if (s_logger.isTraceEnabled()) { - s_logger.trace("Found open channel for peer: " + peerName); - } - return ch; - } - } - - public SocketChannel connectToPeer(long hostId, SocketChannel prevCh) { - String peerName = _clusterMgr.getPeerName(hostId); - if (peerName == null) { - return null; - } - - return connectToPeer(peerName, prevCh); - } - - @Override - protected AgentAttache getAttache(final Long hostId) throws AgentUnavailableException { - assert (hostId != null) : "Who didn't check their id value?"; - HostVO host = _hostDao.findById(hostId); - if (host == null) { - throw new AgentUnavailableException("Can't find the host ", hostId); - } - - AgentAttache agent = findAttache(hostId); - if (agent == null) { - if (host.getStatus() == Status.Up && (host.getManagementServerId() != null && host.getManagementServerId() != _nodeId)) { - agent = createAttache(hostId); - } - } - if (agent == null) { - AgentUnavailableException ex = new AgentUnavailableException("Host with specified id is not in the right state: " + host.getStatus(), hostId); - ex.addProxyObject(host, hostId, "hostId"); - throw ex; - } - - return agent; - } - - @Override - public boolean stop() { - if (_peers != null) { - for (SocketChannel ch : _peers.values()) { - try { - s_logger.info("Closing: " + ch.toString()); - ch.close(); - } catch (IOException e) { - } - } - } - _timer.cancel(); - - //cancel all transfer tasks - s_transferExecutor.shutdownNow(); - cleanupTransferMap(_nodeId); - - return super.stop(); - } - - @Override - public void startDirectlyConnectedHosts() { - // override and let it be dummy for purpose, we will scan and load direct agents periodically. - // We may also pickup agents that have been left over from other crashed management server - } - - public class ClusteredAgentHandler extends AgentHandler { - - public ClusteredAgentHandler(Task.Type type, Link link, byte[] data) { - super(type, link, data); - } - - @Override - protected void doTask(final Task task) throws Exception { - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - if (task.getType() != Task.Type.DATA) { - super.doTask(task); - return; - } - - final byte[] data = task.getData(); - Version ver = Request.getVersion(data); - if (ver.ordinal() != Version.v1.ordinal() && ver.ordinal() != Version.v3.ordinal()) { - s_logger.warn("Wrong version for clustered agent request"); - super.doTask(task); - return; - } - - long hostId = Request.getAgentId(data); - Link link = task.getLink(); - - if (Request.fromServer(data)) { - - AgentAttache agent = findAttache(hostId); - - if (Request.isControl(data)) { - if (agent == null) { - logD(data, "No attache to process cancellation"); - return; - } - Request req = Request.parse(data); - Command[] cmds = req.getCommands(); - CancelCommand cancel = (CancelCommand) cmds[0]; - if (s_logger.isDebugEnabled()) { - logD(data, "Cancel request received"); - } - agent.cancel(cancel.getSequence()); - return; - } - - try { - if (agent == null || agent.isClosed()) { - throw new AgentUnavailableException("Unable to route to agent ", hostId); - } - - if (Request.isRequest(data) && Request.requiresSequentialExecution(data)) { - // route it to the agent. - // But we have the serialize the control commands here so we have - // to deserialize this and send it through the agent attache. - Request req = Request.parse(data); - agent.send(req, null); - return; - } else { - if (agent instanceof Routable) { - Routable cluster = (Routable) agent; - cluster.routeToAgent(data); - } else { - agent.send(Request.parse(data)); - } - return; - } - } catch (AgentUnavailableException e) { - logD(data, e.getMessage()); - cancel(Long.toString(Request.getManagementServerId(data)), hostId, Request.getSequence(data), e.getMessage()); - } - } else { - - long mgmtId = Request.getManagementServerId(data); - if (mgmtId != -1 && mgmtId != _nodeId) { - routeToPeer(Long.toString(mgmtId), data); - if (Request.requiresSequentialExecution(data)) { - AgentAttache attache = (AgentAttache) link.attachment(); - if (attache != null) { - attache.sendNext(Request.getSequence(data)); - } else if (s_logger.isDebugEnabled()) { - logD(data, "No attache to process " + Request.parse(data).toString()); - } - } - return; - } else { - if (Request.isRequest(data)) { - super.doTask(task); - } else { - // received an answer. - final Response response = Response.parse(data); - AgentAttache attache = findAttache(response.getAgentId()); - if (attache == null) { - s_logger.info("SeqA " + response.getAgentId() + "-" + response.getSequence() + "Unable to find attache to forward " + response.toString()); - return; - } - if (!attache.processAnswers(response.getSequence(), response)) { - s_logger.info("SeqA " + attache.getId() + "-" + response.getSequence() + ": Response is not processed: " + response.toString()); - } - } - return; - } - } - } finally { - txn.close(); - } - } - } - - @Override - public void onManagementNodeJoined(List nodeList, long selfNodeId) { - } - - @Override - public void onManagementNodeLeft(List nodeList, long selfNodeId) { - for (ManagementServerHostVO vo : nodeList) { - s_logger.info("Marking hosts as disconnected on Management server" + vo.getMsid()); - long lastPing = (System.currentTimeMillis() >> 10) - _pingTimeout; - _hostDao.markHostsAsDisconnected(vo.getMsid(), lastPing); - s_logger.info("Deleting entries from op_host_transfer table for Management server " + vo.getMsid()); - cleanupTransferMap(vo.getMsid()); - } - } - - @Override - public void onManagementNodeIsolated() { - } - - @Override - public void removeAgent(AgentAttache attache, Status nextState) { - if (attache == null) { - return; - } - - super.removeAgent(attache, nextState); - } - - @Override - public boolean executeRebalanceRequest(long agentId, long currentOwnerId, long futureOwnerId, Event event) throws AgentUnavailableException, OperationTimedoutException { - boolean result = false; - if (event == Event.RequestAgentRebalance) { - return setToWaitForRebalance(agentId, currentOwnerId, futureOwnerId); - } else if (event == Event.StartAgentRebalance) { - try { - result = rebalanceHost(agentId, currentOwnerId, futureOwnerId); - } catch (Exception e) { - s_logger.warn("Unable to rebalance host id=" + agentId, e); - } - } - return result; - } - - @Override - public void scheduleRebalanceAgents() { - _timer.schedule(new AgentLoadBalancerTask(), 30000); - } - - public class AgentLoadBalancerTask extends TimerTask { - protected volatile boolean cancelled = false; - - public AgentLoadBalancerTask() { - s_logger.debug("Agent load balancer task created"); - } - - @Override - public synchronized boolean cancel() { - if (!cancelled) { - cancelled = true; - s_logger.debug("Agent load balancer task cancelled"); - return super.cancel(); - } - return true; - } - - @Override - public synchronized void run() { - try { - if (!cancelled) { - startRebalanceAgents(); - if (s_logger.isInfoEnabled()) { - s_logger.info("The agent load balancer task is now being cancelled"); - } - cancelled = true; - } - } catch(Throwable e) { - s_logger.error("Unexpected exception " + e.toString(), e); - } - } - } - - public void startRebalanceAgents() { - s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); - List allMS = _mshostDao.listBy(ManagementServerHost.State.Up); - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); - List allManagedAgents = sc.list(); - - int avLoad = 0; - - if (!allManagedAgents.isEmpty() && !allMS.isEmpty()) { - avLoad = allManagedAgents.size() / allMS.size(); - } else { - if (s_logger.isDebugEnabled()) { - s_logger.debug("There are no hosts to rebalance in the system. Current number of active management server nodes in the system is " + allMS.size() + "; number of managed agents is " + allManagedAgents.size()); - } - return; - } - - if (avLoad == 0L) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("As calculated average load is less than 1, rounding it to 1"); - } - avLoad = 1; - } - - for (ManagementServerHostVO node : allMS) { - if (node.getMsid() != _nodeId) { - - List hostsToRebalance = new ArrayList(); - for (AgentLoadBalancerPlanner lbPlanner : _lbPlanners) { - hostsToRebalance = lbPlanner.getHostsToRebalance(node.getMsid(), avLoad); - if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { - break; - } else { - s_logger.debug("Agent load balancer planner " + lbPlanner.getName() + " found no hosts to be rebalanced from management server " + node.getMsid()); - } - } - - - if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { - s_logger.debug("Found " + hostsToRebalance.size() + " hosts to rebalance from management server " + node.getMsid()); - for (HostVO host : hostsToRebalance) { - long hostId = host.getId(); - s_logger.debug("Asking management server " + node.getMsid() + " to give away host id=" + hostId); - boolean result = true; - - if (_hostTransferDao.findById(hostId) != null) { - s_logger.warn("Somebody else is already rebalancing host id: " + hostId); - continue; - } - - HostTransferMapVO transfer = null; - try { - transfer = _hostTransferDao.startAgentTransfering(hostId, node.getMsid(), _nodeId); - Answer[] answer = sendRebalanceCommand(node.getMsid(), hostId, node.getMsid(), _nodeId, Event.RequestAgentRebalance); - if (answer == null) { - s_logger.warn("Failed to get host id=" + hostId + " from management server " + node.getMsid()); - result = false; - } - } catch (Exception ex) { - s_logger.warn("Failed to get host id=" + hostId + " from management server " + node.getMsid(), ex); - result = false; - } finally { - if (transfer != null) { - HostTransferMapVO transferState = _hostTransferDao.findByIdAndFutureOwnerId(transfer.getId(), _nodeId); - if (!result && transferState != null && transferState.getState() == HostTransferState.TransferRequested) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Removing mapping from op_host_transfer as it failed to be set to transfer mode"); - } - //just remove the mapping (if exists) as nothing was done on the peer management server yet - _hostTransferDao.remove(transfer.getId()); - } - } - } - } - } else { - s_logger.debug("Found no hosts to rebalance from the management server " + node.getMsid()); - } - } - } - } - - private Answer[] sendRebalanceCommand(long peer, long agentId, long currentOwnerId, long futureOwnerId, Event event) { - TransferAgentCommand transfer = new TransferAgentCommand(agentId, currentOwnerId, futureOwnerId, event); - Commands commands = new Commands(OnError.Stop); - commands.addCommand(transfer); - - Command[] cmds = commands.toCommands(); - - try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Forwarding " + cmds[0].toString() + " to " + peer); - } - String peerName = Long.toString(peer); - Answer[] answers = _clusterMgr.execute(peerName, agentId, cmds, true); - return answers; - } catch (Exception e) { - s_logger.warn("Caught exception while talking to " + currentOwnerId, e); - return null; - } - } - - private Runnable getTransferScanTask() { - return new Runnable() { - @Override - public void run() { - try { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Clustered agent transfer scan check, management server id:" + _nodeId); - } - synchronized (_agentToTransferIds) { - if (_agentToTransferIds.size() > 0) { - s_logger.debug("Found " + _agentToTransferIds.size() + " agents to transfer"); - //for (Long hostId : _agentToTransferIds) { - for (Iterator iterator = _agentToTransferIds.iterator(); iterator.hasNext();) { - Long hostId = iterator.next(); - AgentAttache attache = findAttache(hostId); - - // if the thread: - // 1) timed out waiting for the host to reconnect - // 2) recipient management server is not active any more - // 3) if the management server doesn't own the host any more - // remove the host from re-balance list and delete from op_host_transfer DB - // no need to do anything with the real attache as we haven't modified it yet - Date cutTime = DateUtil.currentGMTTime(); - HostTransferMapVO transferMap = _hostTransferDao.findActiveHostTransferMapByHostId(hostId, new Date(cutTime.getTime() - rebalanceTimeOut)); - - if (transferMap == null) { - s_logger.debug("Timed out waiting for the host id=" + hostId + " to be ready to transfer, skipping rebalance for the host"); - iterator.remove(); - _hostTransferDao.completeAgentTransfer(hostId); - continue; - } - - if (transferMap.getInitialOwner() != _nodeId || attache.forForward()) { - s_logger.debug("Management server " + _nodeId + " doesn't own host id=" + hostId + " any more, skipping rebalance for the host"); - iterator.remove(); - _hostTransferDao.completeAgentTransfer(hostId); - continue; - } - - ManagementServerHostVO ms = _mshostDao.findByMsid(transferMap.getFutureOwner()); - if (ms != null && ms.getState() != ManagementServerHost.State.Up) { - s_logger.debug("Can't transfer host " + hostId + " as it's future owner is not in UP state: " + ms + ", skipping rebalance for the host"); - iterator.remove(); - _hostTransferDao.completeAgentTransfer(hostId); - continue; - } - - if (attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { - iterator.remove(); - try { - _executor.execute(new RebalanceTask(hostId, transferMap.getInitialOwner(), transferMap.getFutureOwner())); - } catch (RejectedExecutionException ex) { - s_logger.warn("Failed to submit rebalance task for host id=" + hostId + "; postponing the execution"); - continue; - } - - } else { - s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + " and listener queue size is " + attache.getNonRecurringListenersSize()); - } - } - } else { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Found no agents to be transfered by the management server " + _nodeId); - } - } - } - - } catch (Throwable e) { - s_logger.error("Problem with the clustered agent transfer scan check!", e); - } - } - }; - } - - - private boolean setToWaitForRebalance(final long hostId, long currentOwnerId, long futureOwnerId) { - s_logger.debug("Adding agent " + hostId + " to the list of agents to transfer"); - synchronized (_agentToTransferIds) { - return _agentToTransferIds.add(hostId); - } - } - - - protected boolean rebalanceHost(final long hostId, long currentOwnerId, long futureOwnerId) throws AgentUnavailableException{ - - boolean result = true; - if (currentOwnerId == _nodeId) { - if (!startRebalance(hostId)) { - s_logger.debug("Failed to start agent rebalancing"); - finishRebalance(hostId, futureOwnerId, Event.RebalanceFailed); - return false; - } - try { - Answer[] answer = sendRebalanceCommand(futureOwnerId, hostId, currentOwnerId, futureOwnerId, Event.StartAgentRebalance); - if (answer == null || !answer[0].getResult()) { - result = false; - } + if (s_logger.isDebugEnabled()) { + s_logger.debug("Connection to peer opened: " + peerName + ", ip: " + ip); + } + _peers.put(peerName, ch); + _sslEngines.put(peerName, sslEngine); + } catch (IOException e) { + s_logger.warn("Unable to connect to peer management server: " + peerName + ", ip: " + ip + " due to " + e.getMessage(), e); + return null; + } + } - } catch (Exception ex) { - s_logger.warn("Host " + hostId + " failed to connect to the management server " + futureOwnerId + " as a part of rebalance process", ex); - result = false; - } - - if (result) { - s_logger.debug("Successfully transfered host id=" + hostId + " to management server " + futureOwnerId); - finishRebalance(hostId, futureOwnerId, Event.RebalanceCompleted); - } else { - s_logger.warn("Failed to transfer host id=" + hostId + " to management server " + futureOwnerId); - finishRebalance(hostId, futureOwnerId, Event.RebalanceFailed); - } - - } else if (futureOwnerId == _nodeId) { - HostVO host = _hostDao.findById(hostId); - try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); - } - result = loadDirectlyConnectedHost(host, true); - } catch (Exception ex) { - s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process due to:", ex); - result = false; - } - - if (result) { - s_logger.debug("Successfully loaded directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); - } else { - s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); - } - } - - return result; - } - - - protected void finishRebalance(final long hostId, long futureOwnerId, Event event){ - - boolean success = (event == Event.RebalanceCompleted) ? true : false; - if (s_logger.isDebugEnabled()) { - s_logger.debug("Finishing rebalancing for the agent " + hostId + " with event " + event); - } - - AgentAttache attache = findAttache(hostId); - if (attache == null || !(attache instanceof ClusteredAgentAttache)) { - s_logger.debug("Unable to find forward attache for the host id=" + hostId + ", assuming that the agent disconnected already"); - _hostTransferDao.completeAgentTransfer(hostId); - return; - } - - ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache; - - if (success) { - - //1) Set transfer mode to false - so the agent can start processing requests normally - forwardAttache.setTransferMode(false); - - //2) Get all transfer requests and route them to peer - Request requestToTransfer = forwardAttache.getRequestToTransfer(); - while (requestToTransfer != null) { - s_logger.debug("Forwarding request " + requestToTransfer.getSequence() + " held in transfer attache " + hostId + " from the management server " + _nodeId + " to " + futureOwnerId); - boolean routeResult = routeToPeer(Long.toString(futureOwnerId), requestToTransfer.getBytes()); - if (!routeResult) { - logD(requestToTransfer.getBytes(), "Failed to route request to peer"); - } - - requestToTransfer = forwardAttache.getRequestToTransfer(); - } - - s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance to " + futureOwnerId); - - } else { - failRebalance(hostId); - } - - s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance"); - _hostTransferDao.completeAgentTransfer(hostId); - } - - protected void failRebalance(final long hostId){ - try { - s_logger.debug("Management server " + _nodeId + " failed to rebalance agent " + hostId); - _hostTransferDao.completeAgentTransfer(hostId); - handleDisconnectWithoutInvestigation(findAttache(hostId), Event.RebalanceFailed); - } catch (Exception ex) { - s_logger.warn("Failed to reconnect host id=" + hostId + " as a part of failed rebalance task cleanup"); - } - } - - protected boolean startRebalance(final long hostId) { - HostVO host = _hostDao.findById(hostId); - - if (host == null || host.getRemoved() != null) { - s_logger.warn("Unable to find host record, fail start rebalancing process"); - return false; - } - - synchronized (_agents) { - ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); - if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { - handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance); - ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(hostId); - if (forwardAttache == null) { - s_logger.warn("Unable to create a forward attache for the host " + hostId + " as a part of rebalance process"); - return false; - } - s_logger.debug("Putting agent id=" + hostId + " to transfer mode"); - forwardAttache.setTransferMode(true); - _agents.put(hostId, forwardAttache); - } else { - if (attache == null) { - s_logger.warn("Attache for the agent " + hostId + " no longer exists on management server " + _nodeId + ", can't start host rebalancing"); - } else { - s_logger.warn("Attache for the agent " + hostId + " has request queue size= " + attache.getQueueSize() + " and listener queue size " + attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); - } - return false; - } + if (s_logger.isTraceEnabled()) { + s_logger.trace("Found open channel for peer: " + peerName); + } + return ch; } - _hostTransferDao.startAgentTransfer(hostId); - return true; - } - - protected void cleanupTransferMap(long msId) { - List hostsJoingingCluster = _hostTransferDao.listHostsJoiningCluster(msId); - - for (HostTransferMapVO hostJoingingCluster : hostsJoingingCluster) { - _hostTransferDao.remove(hostJoingingCluster.getId()); - } - - List hostsLeavingCluster = _hostTransferDao.listHostsLeavingCluster(msId); - for (HostTransferMapVO hostLeavingCluster : hostsLeavingCluster) { - _hostTransferDao.remove(hostLeavingCluster.getId()); - } - } - - - protected class RebalanceTask implements Runnable { - Long hostId = null; - Long currentOwnerId = null; - Long futureOwnerId = null; - - - public RebalanceTask(long hostId, long currentOwnerId, long futureOwnerId) { - this.hostId = hostId; - this.currentOwnerId = currentOwnerId; - this.futureOwnerId = futureOwnerId; - } - - @Override - public void run() { - try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Rebalancing host id=" + hostId); - } - rebalanceHost(hostId, currentOwnerId, futureOwnerId); - } catch (Exception e) { - s_logger.warn("Unable to rebalance host id=" + hostId, e); - } finally { - StackMaid.current().exitCleanup(); - } - } - } - -} + } + + public SocketChannel connectToPeer(long hostId, SocketChannel prevCh) { + String peerName = _clusterMgr.getPeerName(hostId); + if (peerName == null) { + return null; + } + + return connectToPeer(peerName, prevCh); + } + + @Override + protected AgentAttache getAttache(final Long hostId) throws AgentUnavailableException { + assert (hostId != null) : "Who didn't check their id value?"; + HostVO host = _hostDao.findById(hostId); + if (host == null) { + throw new AgentUnavailableException("Can't find the host ", hostId); + } + + AgentAttache agent = findAttache(hostId); + if (agent == null) { + if (host.getStatus() == Status.Up && (host.getManagementServerId() != null && host.getManagementServerId() != _nodeId)) { + agent = createAttache(hostId); + } + } + if (agent == null) { + AgentUnavailableException ex = new AgentUnavailableException("Host with specified id is not in the right state: " + host.getStatus(), hostId); + ex.addProxyObject(host, hostId, "hostId"); + throw ex; + } + + return agent; + } + + @Override + public boolean stop() { + if (_peers != null) { + for (SocketChannel ch : _peers.values()) { + try { + s_logger.info("Closing: " + ch.toString()); + ch.close(); + } catch (IOException e) { + } + } + } + _timer.cancel(); + + //cancel all transfer tasks + s_transferExecutor.shutdownNow(); + cleanupTransferMap(_nodeId); + + return super.stop(); + } + + @Override + public void startDirectlyConnectedHosts() { + // override and let it be dummy for purpose, we will scan and load direct agents periodically. + // We may also pickup agents that have been left over from other crashed management server + } + + public class ClusteredAgentHandler extends AgentHandler { + + public ClusteredAgentHandler(Task.Type type, Link link, byte[] data) { + super(type, link, data); + } + + @Override + protected void doTask(final Task task) throws Exception { + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + if (task.getType() != Task.Type.DATA) { + super.doTask(task); + return; + } + + final byte[] data = task.getData(); + Version ver = Request.getVersion(data); + if (ver.ordinal() != Version.v1.ordinal() && ver.ordinal() != Version.v3.ordinal()) { + s_logger.warn("Wrong version for clustered agent request"); + super.doTask(task); + return; + } + + long hostId = Request.getAgentId(data); + Link link = task.getLink(); + + if (Request.fromServer(data)) { + + AgentAttache agent = findAttache(hostId); + + if (Request.isControl(data)) { + if (agent == null) { + logD(data, "No attache to process cancellation"); + return; + } + Request req = Request.parse(data); + Command[] cmds = req.getCommands(); + CancelCommand cancel = (CancelCommand) cmds[0]; + if (s_logger.isDebugEnabled()) { + logD(data, "Cancel request received"); + } + agent.cancel(cancel.getSequence()); + return; + } + + try { + if (agent == null || agent.isClosed()) { + throw new AgentUnavailableException("Unable to route to agent ", hostId); + } + + if (Request.isRequest(data) && Request.requiresSequentialExecution(data)) { + // route it to the agent. + // But we have the serialize the control commands here so we have + // to deserialize this and send it through the agent attache. + Request req = Request.parse(data); + agent.send(req, null); + return; + } else { + if (agent instanceof Routable) { + Routable cluster = (Routable) agent; + cluster.routeToAgent(data); + } else { + agent.send(Request.parse(data)); + } + return; + } + } catch (AgentUnavailableException e) { + logD(data, e.getMessage()); + cancel(Long.toString(Request.getManagementServerId(data)), hostId, Request.getSequence(data), e.getMessage()); + } + } else { + + long mgmtId = Request.getManagementServerId(data); + if (mgmtId != -1 && mgmtId != _nodeId) { + routeToPeer(Long.toString(mgmtId), data); + if (Request.requiresSequentialExecution(data)) { + AgentAttache attache = (AgentAttache) link.attachment(); + if (attache != null) { + attache.sendNext(Request.getSequence(data)); + } else if (s_logger.isDebugEnabled()) { + logD(data, "No attache to process " + Request.parse(data).toString()); + } + } + return; + } else { + if (Request.isRequest(data)) { + super.doTask(task); + } else { + // received an answer. + final Response response = Response.parse(data); + AgentAttache attache = findAttache(response.getAgentId()); + if (attache == null) { + s_logger.info("SeqA " + response.getAgentId() + "-" + response.getSequence() + "Unable to find attache to forward " + response.toString()); + return; + } + if (!attache.processAnswers(response.getSequence(), response)) { + s_logger.info("SeqA " + attache.getId() + "-" + response.getSequence() + ": Response is not processed: " + response.toString()); + } + } + return; + } + } + } finally { + txn.close(); + } + } + } + + @Override + public void onManagementNodeJoined(List nodeList, long selfNodeId) { + } + + @Override + public void onManagementNodeLeft(List nodeList, long selfNodeId) { + for (ManagementServerHostVO vo : nodeList) { + s_logger.info("Marking hosts as disconnected on Management server" + vo.getMsid()); + long lastPing = (System.currentTimeMillis() >> 10) - _pingTimeout; + _hostDao.markHostsAsDisconnected(vo.getMsid(), lastPing); + s_logger.info("Deleting entries from op_host_transfer table for Management server " + vo.getMsid()); + cleanupTransferMap(vo.getMsid()); + } + } + + @Override + public void onManagementNodeIsolated() { + } + + @Override + public void removeAgent(AgentAttache attache, Status nextState) { + if (attache == null) { + return; + } + + super.removeAgent(attache, nextState); + } + + @Override + public boolean executeRebalanceRequest(long agentId, long currentOwnerId, long futureOwnerId, Event event) throws AgentUnavailableException, OperationTimedoutException { + boolean result = false; + if (event == Event.RequestAgentRebalance) { + return setToWaitForRebalance(agentId, currentOwnerId, futureOwnerId); + } else if (event == Event.StartAgentRebalance) { + try { + result = rebalanceHost(agentId, currentOwnerId, futureOwnerId); + } catch (Exception e) { + s_logger.warn("Unable to rebalance host id=" + agentId, e); + } + } + return result; + } + + @Override + public void scheduleRebalanceAgents() { + _timer.schedule(new AgentLoadBalancerTask(), 30000); + } + + public class AgentLoadBalancerTask extends TimerTask { + protected volatile boolean cancelled = false; + + public AgentLoadBalancerTask() { + s_logger.debug("Agent load balancer task created"); + } + + @Override + public synchronized boolean cancel() { + if (!cancelled) { + cancelled = true; + s_logger.debug("Agent load balancer task cancelled"); + return super.cancel(); + } + return true; + } + + @Override + public synchronized void run() { + try { + if (!cancelled) { + startRebalanceAgents(); + if (s_logger.isInfoEnabled()) { + s_logger.info("The agent load balancer task is now being cancelled"); + } + cancelled = true; + } + } catch(Throwable e) { + s_logger.error("Unexpected exception " + e.toString(), e); + } + } + } + + public void startRebalanceAgents() { + s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); + List allMS = _mshostDao.listBy(ManagementServerHost.State.Up); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); + sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + List allManagedAgents = sc.list(); + + int avLoad = 0; + + if (!allManagedAgents.isEmpty() && !allMS.isEmpty()) { + avLoad = allManagedAgents.size() / allMS.size(); + } else { + if (s_logger.isDebugEnabled()) { + s_logger.debug("There are no hosts to rebalance in the system. Current number of active management server nodes in the system is " + allMS.size() + "; number of managed agents is " + allManagedAgents.size()); + } + return; + } + + if (avLoad == 0L) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("As calculated average load is less than 1, rounding it to 1"); + } + avLoad = 1; + } + + for (ManagementServerHostVO node : allMS) { + if (node.getMsid() != _nodeId) { + + List hostsToRebalance = new ArrayList(); + for (AgentLoadBalancerPlanner lbPlanner : _lbPlanners) { + hostsToRebalance = lbPlanner.getHostsToRebalance(node.getMsid(), avLoad); + if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { + break; + } else { + s_logger.debug("Agent load balancer planner " + lbPlanner.getName() + " found no hosts to be rebalanced from management server " + node.getMsid()); + } + } + + + if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { + s_logger.debug("Found " + hostsToRebalance.size() + " hosts to rebalance from management server " + node.getMsid()); + for (HostVO host : hostsToRebalance) { + long hostId = host.getId(); + s_logger.debug("Asking management server " + node.getMsid() + " to give away host id=" + hostId); + boolean result = true; + + if (_hostTransferDao.findById(hostId) != null) { + s_logger.warn("Somebody else is already rebalancing host id: " + hostId); + continue; + } + + HostTransferMapVO transfer = null; + try { + transfer = _hostTransferDao.startAgentTransfering(hostId, node.getMsid(), _nodeId); + Answer[] answer = sendRebalanceCommand(node.getMsid(), hostId, node.getMsid(), _nodeId, Event.RequestAgentRebalance); + if (answer == null) { + s_logger.warn("Failed to get host id=" + hostId + " from management server " + node.getMsid()); + result = false; + } + } catch (Exception ex) { + s_logger.warn("Failed to get host id=" + hostId + " from management server " + node.getMsid(), ex); + result = false; + } finally { + if (transfer != null) { + HostTransferMapVO transferState = _hostTransferDao.findByIdAndFutureOwnerId(transfer.getId(), _nodeId); + if (!result && transferState != null && transferState.getState() == HostTransferState.TransferRequested) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Removing mapping from op_host_transfer as it failed to be set to transfer mode"); + } + //just remove the mapping (if exists) as nothing was done on the peer management server yet + _hostTransferDao.remove(transfer.getId()); + } + } + } + } + } else { + s_logger.debug("Found no hosts to rebalance from the management server " + node.getMsid()); + } + } + } + } + + private Answer[] sendRebalanceCommand(long peer, long agentId, long currentOwnerId, long futureOwnerId, Event event) { + TransferAgentCommand transfer = new TransferAgentCommand(agentId, currentOwnerId, futureOwnerId, event); + Commands commands = new Commands(OnError.Stop); + commands.addCommand(transfer); + + Command[] cmds = commands.toCommands(); + + try { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Forwarding " + cmds[0].toString() + " to " + peer); + } + String peerName = Long.toString(peer); + Answer[] answers = _clusterMgr.execute(peerName, agentId, cmds, true); + return answers; + } catch (Exception e) { + s_logger.warn("Caught exception while talking to " + currentOwnerId, e); + return null; + } + } + + private Runnable getTransferScanTask() { + return new Runnable() { + @Override + public void run() { + try { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Clustered agent transfer scan check, management server id:" + _nodeId); + } + synchronized (_agentToTransferIds) { + if (_agentToTransferIds.size() > 0) { + s_logger.debug("Found " + _agentToTransferIds.size() + " agents to transfer"); + //for (Long hostId : _agentToTransferIds) { + for (Iterator iterator = _agentToTransferIds.iterator(); iterator.hasNext();) { + Long hostId = iterator.next(); + AgentAttache attache = findAttache(hostId); + + // if the thread: + // 1) timed out waiting for the host to reconnect + // 2) recipient management server is not active any more + // 3) if the management server doesn't own the host any more + // remove the host from re-balance list and delete from op_host_transfer DB + // no need to do anything with the real attache as we haven't modified it yet + Date cutTime = DateUtil.currentGMTTime(); + HostTransferMapVO transferMap = _hostTransferDao.findActiveHostTransferMapByHostId(hostId, new Date(cutTime.getTime() - rebalanceTimeOut)); + + if (transferMap == null) { + s_logger.debug("Timed out waiting for the host id=" + hostId + " to be ready to transfer, skipping rebalance for the host"); + iterator.remove(); + _hostTransferDao.completeAgentTransfer(hostId); + continue; + } + + if (transferMap.getInitialOwner() != _nodeId || attache.forForward()) { + s_logger.debug("Management server " + _nodeId + " doesn't own host id=" + hostId + " any more, skipping rebalance for the host"); + iterator.remove(); + _hostTransferDao.completeAgentTransfer(hostId); + continue; + } + + ManagementServerHostVO ms = _mshostDao.findByMsid(transferMap.getFutureOwner()); + if (ms != null && ms.getState() != ManagementServerHost.State.Up) { + s_logger.debug("Can't transfer host " + hostId + " as it's future owner is not in UP state: " + ms + ", skipping rebalance for the host"); + iterator.remove(); + _hostTransferDao.completeAgentTransfer(hostId); + continue; + } + + if (attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { + iterator.remove(); + try { + _executor.execute(new RebalanceTask(hostId, transferMap.getInitialOwner(), transferMap.getFutureOwner())); + } catch (RejectedExecutionException ex) { + s_logger.warn("Failed to submit rebalance task for host id=" + hostId + "; postponing the execution"); + continue; + } + + } else { + s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + " and listener queue size is " + attache.getNonRecurringListenersSize()); + } + } + } else { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Found no agents to be transfered by the management server " + _nodeId); + } + } + } + + } catch (Throwable e) { + s_logger.error("Problem with the clustered agent transfer scan check!", e); + } + } + }; + } + + + private boolean setToWaitForRebalance(final long hostId, long currentOwnerId, long futureOwnerId) { + s_logger.debug("Adding agent " + hostId + " to the list of agents to transfer"); + synchronized (_agentToTransferIds) { + return _agentToTransferIds.add(hostId); + } + } + + + protected boolean rebalanceHost(final long hostId, long currentOwnerId, long futureOwnerId) throws AgentUnavailableException{ + + boolean result = true; + if (currentOwnerId == _nodeId) { + if (!startRebalance(hostId)) { + s_logger.debug("Failed to start agent rebalancing"); + finishRebalance(hostId, futureOwnerId, Event.RebalanceFailed); + return false; + } + try { + Answer[] answer = sendRebalanceCommand(futureOwnerId, hostId, currentOwnerId, futureOwnerId, Event.StartAgentRebalance); + if (answer == null || !answer[0].getResult()) { + result = false; + } + + } catch (Exception ex) { + s_logger.warn("Host " + hostId + " failed to connect to the management server " + futureOwnerId + " as a part of rebalance process", ex); + result = false; + } + + if (result) { + s_logger.debug("Successfully transfered host id=" + hostId + " to management server " + futureOwnerId); + finishRebalance(hostId, futureOwnerId, Event.RebalanceCompleted); + } else { + s_logger.warn("Failed to transfer host id=" + hostId + " to management server " + futureOwnerId); + finishRebalance(hostId, futureOwnerId, Event.RebalanceFailed); + } + + } else if (futureOwnerId == _nodeId) { + HostVO host = _hostDao.findById(hostId); + try { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); + } + result = loadDirectlyConnectedHost(host, true); + } catch (Exception ex) { + s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process due to:", ex); + result = false; + } + + if (result) { + s_logger.debug("Successfully loaded directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); + } else { + s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); + } + } + + return result; + } + + + protected void finishRebalance(final long hostId, long futureOwnerId, Event event){ + + boolean success = (event == Event.RebalanceCompleted) ? true : false; + if (s_logger.isDebugEnabled()) { + s_logger.debug("Finishing rebalancing for the agent " + hostId + " with event " + event); + } + + AgentAttache attache = findAttache(hostId); + if (attache == null || !(attache instanceof ClusteredAgentAttache)) { + s_logger.debug("Unable to find forward attache for the host id=" + hostId + ", assuming that the agent disconnected already"); + _hostTransferDao.completeAgentTransfer(hostId); + return; + } + + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache; + + if (success) { + + //1) Set transfer mode to false - so the agent can start processing requests normally + forwardAttache.setTransferMode(false); + + //2) Get all transfer requests and route them to peer + Request requestToTransfer = forwardAttache.getRequestToTransfer(); + while (requestToTransfer != null) { + s_logger.debug("Forwarding request " + requestToTransfer.getSequence() + " held in transfer attache " + hostId + " from the management server " + _nodeId + " to " + futureOwnerId); + boolean routeResult = routeToPeer(Long.toString(futureOwnerId), requestToTransfer.getBytes()); + if (!routeResult) { + logD(requestToTransfer.getBytes(), "Failed to route request to peer"); + } + + requestToTransfer = forwardAttache.getRequestToTransfer(); + } + + s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance to " + futureOwnerId); + + } else { + failRebalance(hostId); + } + + s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance"); + _hostTransferDao.completeAgentTransfer(hostId); + } + + protected void failRebalance(final long hostId){ + try { + s_logger.debug("Management server " + _nodeId + " failed to rebalance agent " + hostId); + _hostTransferDao.completeAgentTransfer(hostId); + handleDisconnectWithoutInvestigation(findAttache(hostId), Event.RebalanceFailed); + } catch (Exception ex) { + s_logger.warn("Failed to reconnect host id=" + hostId + " as a part of failed rebalance task cleanup"); + } + } + + protected boolean startRebalance(final long hostId) { + HostVO host = _hostDao.findById(hostId); + + if (host == null || host.getRemoved() != null) { + s_logger.warn("Unable to find host record, fail start rebalancing process"); + return false; + } + + synchronized (_agents) { + ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); + if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { + handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance); + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(hostId); + if (forwardAttache == null) { + s_logger.warn("Unable to create a forward attache for the host " + hostId + " as a part of rebalance process"); + return false; + } + s_logger.debug("Putting agent id=" + hostId + " to transfer mode"); + forwardAttache.setTransferMode(true); + _agents.put(hostId, forwardAttache); + } else { + if (attache == null) { + s_logger.warn("Attache for the agent " + hostId + " no longer exists on management server " + _nodeId + ", can't start host rebalancing"); + } else { + s_logger.warn("Attache for the agent " + hostId + " has request queue size= " + attache.getQueueSize() + " and listener queue size " + attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); + } + return false; + } + } + _hostTransferDao.startAgentTransfer(hostId); + return true; + } + + protected void cleanupTransferMap(long msId) { + List hostsJoingingCluster = _hostTransferDao.listHostsJoiningCluster(msId); + + for (HostTransferMapVO hostJoingingCluster : hostsJoingingCluster) { + _hostTransferDao.remove(hostJoingingCluster.getId()); + } + + List hostsLeavingCluster = _hostTransferDao.listHostsLeavingCluster(msId); + for (HostTransferMapVO hostLeavingCluster : hostsLeavingCluster) { + _hostTransferDao.remove(hostLeavingCluster.getId()); + } + } + + + protected class RebalanceTask implements Runnable { + Long hostId = null; + Long currentOwnerId = null; + Long futureOwnerId = null; + + + public RebalanceTask(long hostId, long currentOwnerId, long futureOwnerId) { + this.hostId = hostId; + this.currentOwnerId = currentOwnerId; + this.futureOwnerId = futureOwnerId; + } + + @Override + public void run() { + try { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Rebalancing host id=" + hostId); + } + rebalanceHost(hostId, currentOwnerId, futureOwnerId); + } catch (Exception e) { + s_logger.warn("Unable to rebalance host id=" + hostId, e); + } finally { + StackMaid.current().exitCleanup(); + } + } + } + +} diff --git a/server/src/com/cloud/agent/manager/ConnectedAgentAttache.java b/server/src/com/cloud/agent/manager/ConnectedAgentAttache.java index ebd1f9b9221..63a631531f5 100755 --- a/server/src/com/cloud/agent/manager/ConnectedAgentAttache.java +++ b/server/src/com/cloud/agent/manager/ConnectedAgentAttache.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent.manager; - +package com.cloud.agent.manager; + import java.nio.channels.ClosedChannelException; import org.apache.log4j.Logger; @@ -22,57 +22,57 @@ import com.cloud.agent.transport.Request; import com.cloud.exception.AgentUnavailableException; import com.cloud.host.Status; import com.cloud.utils.nio.Link; - -/** - * ConnectedAgentAttache implements an direct connection to this management server. - */ -public class ConnectedAgentAttache extends AgentAttache { - private static final Logger s_logger = Logger.getLogger(ConnectedAgentAttache.class); - - protected Link _link; - - public ConnectedAgentAttache(AgentManagerImpl agentMgr, final long id, final Link link, boolean maintenance) { - super(agentMgr, id, maintenance); - _link = link; - } - - @Override - public synchronized void send(Request req) throws AgentUnavailableException { - try { - _link.send(req.toBytes()); - } catch (ClosedChannelException e) { - throw new AgentUnavailableException("Channel is closed", _id); - } - } - - @Override - public synchronized boolean isClosed() { - return _link == null; - } - - @Override - public void disconnect(final Status state) { - synchronized (this) { - s_logger.debug("Processing Disconnect."); - if (_link != null) { - _link.close(); - _link.terminated(); - } - _link = null; - } - cancelAllCommands(state, true); - _requests.clear(); - } - - @Override - public boolean equals(Object obj) { - try { - ConnectedAgentAttache that = (ConnectedAgentAttache) obj; - return super.equals(obj) && this._link == that._link && this._link != null; - } catch (ClassCastException e) { + +/** + * ConnectedAgentAttache implements an direct connection to this management server. + */ +public class ConnectedAgentAttache extends AgentAttache { + private static final Logger s_logger = Logger.getLogger(ConnectedAgentAttache.class); + + protected Link _link; + + public ConnectedAgentAttache(AgentManagerImpl agentMgr, final long id, final Link link, boolean maintenance) { + super(agentMgr, id, maintenance); + _link = link; + } + + @Override + public synchronized void send(Request req) throws AgentUnavailableException { + try { + _link.send(req.toBytes()); + } catch (ClosedChannelException e) { + throw new AgentUnavailableException("Channel is closed", _id); + } + } + + @Override + public synchronized boolean isClosed() { + return _link == null; + } + + @Override + public void disconnect(final Status state) { + synchronized (this) { + s_logger.debug("Processing Disconnect."); + if (_link != null) { + _link.close(); + _link.terminated(); + } + _link = null; + } + cancelAllCommands(state, true); + _requests.clear(); + } + + @Override + public boolean equals(Object obj) { + try { + ConnectedAgentAttache that = (ConnectedAgentAttache) obj; + return super.equals(obj) && this._link == that._link && this._link != null; + } catch (ClassCastException e) { assert false : "Who's sending an " + obj.getClass().getSimpleName() + " to " + this.getClass().getSimpleName() + ".equals()? "; - return false; - } + return false; + } } @Override @@ -94,4 +94,4 @@ public class ConnectedAgentAttache extends AgentAttache { public void updatePassword(Command newPassword) { throw new IllegalStateException("Should not have come here "); } -} +} diff --git a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitRoutingAllocator.java b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitRoutingAllocator.java index ee60681a432..0be21f0b2c5 100644 --- a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitRoutingAllocator.java +++ b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitRoutingAllocator.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent.manager.allocator.impl; - +package com.cloud.agent.manager.allocator.impl; + import java.util.ArrayList; import java.util.List; import javax.ejb.Local; @@ -23,22 +23,22 @@ import com.cloud.host.Host; import com.cloud.host.Host.Type; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; - -@Local(value={HostAllocator.class}) -public class FirstFitRoutingAllocator extends FirstFitAllocator { - @Override + +@Local(value={HostAllocator.class}) +public class FirstFitRoutingAllocator extends FirstFitAllocator { + @Override public List allocateTo(VirtualMachineProfile vmProfile, DeploymentPlan plan, Type type, ExcludeList avoid, int returnUpTo) { - try { - NDC.push("FirstFitRoutingAllocator"); - if (type != Host.Type.Routing) { - // FirstFitRoutingAllocator is to find space on routing capable hosts only - return new ArrayList(); - } - //all hosts should be of type routing anyway. - return super.allocateTo(vmProfile, plan, type, avoid, returnUpTo); - } finally { - NDC.pop(); - } - } -} + try { + NDC.push("FirstFitRoutingAllocator"); + if (type != Host.Type.Routing) { + // FirstFitRoutingAllocator is to find space on routing capable hosts only + return new ArrayList(); + } + //all hosts should be of type routing anyway. + return super.allocateTo(vmProfile, plan, type, avoid, returnUpTo); + } finally { + NDC.pop(); + } + } +} diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java index 612078d963f..5b19b9d9fa1 100755 --- a/server/src/com/cloud/alert/AlertManagerImpl.java +++ b/server/src/com/cloud/alert/AlertManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert; - +package com.cloud.alert; + import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.util.ArrayList; @@ -71,112 +71,112 @@ import com.cloud.utils.db.SearchCriteria; import com.sun.mail.smtp.SMTPMessage; import com.sun.mail.smtp.SMTPSSLTransport; import com.sun.mail.smtp.SMTPTransport; - -@Local(value={AlertManager.class}) -public class AlertManagerImpl implements AlertManager { - private static final Logger s_logger = Logger.getLogger(AlertManagerImpl.class.getName()); - - private static final long INITIAL_CAPACITY_CHECK_DELAY = 30L * 1000L; // thirty seconds expressed in milliseconds - - private static final DecimalFormat _dfPct = new DecimalFormat("###.##"); - private static final DecimalFormat _dfWhole = new DecimalFormat("########"); - - private String _name = null; - private EmailAlert _emailAlert; - @Inject private AlertDao _alertDao; + +@Local(value={AlertManager.class}) +public class AlertManagerImpl implements AlertManager { + private static final Logger s_logger = Logger.getLogger(AlertManagerImpl.class.getName()); + + private static final long INITIAL_CAPACITY_CHECK_DELAY = 30L * 1000L; // thirty seconds expressed in milliseconds + + private static final DecimalFormat _dfPct = new DecimalFormat("###.##"); + private static final DecimalFormat _dfWhole = new DecimalFormat("########"); + + private String _name = null; + private EmailAlert _emailAlert; + @Inject private AlertDao _alertDao; @Inject private HostDao _hostDao; @Inject protected StorageManager _storageMgr; - @Inject protected CapacityManager _capacityMgr; - @Inject private CapacityDao _capacityDao; - @Inject private DataCenterDao _dcDao; + @Inject protected CapacityManager _capacityMgr; + @Inject private CapacityDao _capacityDao; + @Inject private DataCenterDao _dcDao; @Inject private HostPodDao _podDao; - @Inject private ClusterDao _clusterDao; - @Inject private VolumeDao _volumeDao; - @Inject private IPAddressDao _publicIPAddressDao; - @Inject private DataCenterIpAddressDao _privateIPAddressDao; + @Inject private ClusterDao _clusterDao; + @Inject private VolumeDao _volumeDao; + @Inject private IPAddressDao _publicIPAddressDao; + @Inject private DataCenterIpAddressDao _privateIPAddressDao; @Inject private StoragePoolDao _storagePoolDao; @Inject private ConfigurationDao _configDao; - @Inject private ResourceManager _resourceMgr; - - private Timer _timer = null; - private float _cpuOverProvisioningFactor = 1; - private long _capacityCheckPeriod = 60L * 60L * 1000L; // one hour by default - private double _memoryCapacityThreshold = 0.75; - private double _cpuCapacityThreshold = 0.75; - private double _storageCapacityThreshold = 0.75; - private double _storageAllocCapacityThreshold = 0.75; - private double _publicIPCapacityThreshold = 0.75; + @Inject private ResourceManager _resourceMgr; + + private Timer _timer = null; + private float _cpuOverProvisioningFactor = 1; + private long _capacityCheckPeriod = 60L * 60L * 1000L; // one hour by default + private double _memoryCapacityThreshold = 0.75; + private double _cpuCapacityThreshold = 0.75; + private double _storageCapacityThreshold = 0.75; + private double _storageAllocCapacityThreshold = 0.75; + private double _publicIPCapacityThreshold = 0.75; private double _privateIPCapacityThreshold = 0.75; private double _secondaryStorageCapacityThreshold = 0.75; private double _vlanCapacityThreshold = 0.75; private double _directNetworkPublicIpCapacityThreshold = 0.75; private double _localStorageCapacityThreshold = 0.75; - Map _capacityTypeThresholdMap = new HashMap(); - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - if (configDao == null) { - s_logger.error("Unable to get the configuration dao."); - return false; - } - - Map configs = configDao.getConfiguration("management-server", params); - - // set up the email system for alerts - String emailAddressList = configs.get("alert.email.addresses"); - String[] emailAddresses = null; - if (emailAddressList != null) { - emailAddresses = emailAddressList.split(","); - } - - String smtpHost = configs.get("alert.smtp.host"); - int smtpPort = NumbersUtil.parseInt(configs.get("alert.smtp.port"), 25); - String useAuthStr = configs.get("alert.smtp.useAuth"); - boolean useAuth = ((useAuthStr == null) ? false : Boolean.parseBoolean(useAuthStr)); - String smtpUsername = configs.get("alert.smtp.username"); - String smtpPassword = configs.get("alert.smtp.password"); - String emailSender = configs.get("alert.email.sender"); - String smtpDebugStr = configs.get("alert.smtp.debug"); - boolean smtpDebug = false; - if (smtpDebugStr != null) { - smtpDebug = Boolean.parseBoolean(smtpDebugStr); - } - - _emailAlert = new EmailAlert(emailAddresses, smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug); + Map _capacityTypeThresholdMap = new HashMap(); + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + if (configDao == null) { + s_logger.error("Unable to get the configuration dao."); + return false; + } + + Map configs = configDao.getConfiguration("management-server", params); + + // set up the email system for alerts + String emailAddressList = configs.get("alert.email.addresses"); + String[] emailAddresses = null; + if (emailAddressList != null) { + emailAddresses = emailAddressList.split(","); + } + + String smtpHost = configs.get("alert.smtp.host"); + int smtpPort = NumbersUtil.parseInt(configs.get("alert.smtp.port"), 25); + String useAuthStr = configs.get("alert.smtp.useAuth"); + boolean useAuth = ((useAuthStr == null) ? false : Boolean.parseBoolean(useAuthStr)); + String smtpUsername = configs.get("alert.smtp.username"); + String smtpPassword = configs.get("alert.smtp.password"); + String emailSender = configs.get("alert.email.sender"); + String smtpDebugStr = configs.get("alert.smtp.debug"); + boolean smtpDebug = false; + if (smtpDebugStr != null) { + smtpDebug = Boolean.parseBoolean(smtpDebugStr); + } + + _emailAlert = new EmailAlert(emailAddresses, smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug); - String storageCapacityThreshold = _configDao.getValue(Config.StorageCapacityThreshold.key()); - String cpuCapacityThreshold = _configDao.getValue(Config.CPUCapacityThreshold.key()); - String memoryCapacityThreshold = _configDao.getValue(Config.MemoryCapacityThreshold.key()); - String storageAllocCapacityThreshold = _configDao.getValue(Config.StorageAllocatedCapacityThreshold.key()); - String publicIPCapacityThreshold = _configDao.getValue(Config.PublicIpCapacityThreshold.key()); + String storageCapacityThreshold = _configDao.getValue(Config.StorageCapacityThreshold.key()); + String cpuCapacityThreshold = _configDao.getValue(Config.CPUCapacityThreshold.key()); + String memoryCapacityThreshold = _configDao.getValue(Config.MemoryCapacityThreshold.key()); + String storageAllocCapacityThreshold = _configDao.getValue(Config.StorageAllocatedCapacityThreshold.key()); + String publicIPCapacityThreshold = _configDao.getValue(Config.PublicIpCapacityThreshold.key()); String privateIPCapacityThreshold = _configDao.getValue(Config.PrivateIpCapacityThreshold.key()); String secondaryStorageCapacityThreshold = _configDao.getValue(Config.SecondaryStorageCapacityThreshold.key()); String vlanCapacityThreshold = _configDao.getValue(Config.VlanCapacityThreshold.key()); String directNetworkPublicIpCapacityThreshold = _configDao.getValue(Config.DirectNetworkPublicIpCapacityThreshold.key()); - String localStorageCapacityThreshold = _configDao.getValue(Config.LocalStorageCapacityThreshold.key()); - - if (storageCapacityThreshold != null) { - _storageCapacityThreshold = Double.parseDouble(storageCapacityThreshold); - } - if (storageAllocCapacityThreshold != null) { - _storageAllocCapacityThreshold = Double.parseDouble(storageAllocCapacityThreshold); - } - if (cpuCapacityThreshold != null) { - _cpuCapacityThreshold = Double.parseDouble(cpuCapacityThreshold); - } - if (memoryCapacityThreshold != null) { - _memoryCapacityThreshold = Double.parseDouble(memoryCapacityThreshold); - } - if (publicIPCapacityThreshold != null) { - _publicIPCapacityThreshold = Double.parseDouble(publicIPCapacityThreshold); - } - if (privateIPCapacityThreshold != null) { - _privateIPCapacityThreshold = Double.parseDouble(privateIPCapacityThreshold); + String localStorageCapacityThreshold = _configDao.getValue(Config.LocalStorageCapacityThreshold.key()); + + if (storageCapacityThreshold != null) { + _storageCapacityThreshold = Double.parseDouble(storageCapacityThreshold); + } + if (storageAllocCapacityThreshold != null) { + _storageAllocCapacityThreshold = Double.parseDouble(storageAllocCapacityThreshold); + } + if (cpuCapacityThreshold != null) { + _cpuCapacityThreshold = Double.parseDouble(cpuCapacityThreshold); + } + if (memoryCapacityThreshold != null) { + _memoryCapacityThreshold = Double.parseDouble(memoryCapacityThreshold); + } + if (publicIPCapacityThreshold != null) { + _publicIPCapacityThreshold = Double.parseDouble(publicIPCapacityThreshold); + } + if (privateIPCapacityThreshold != null) { + _privateIPCapacityThreshold = Double.parseDouble(privateIPCapacityThreshold); } if (secondaryStorageCapacityThreshold != null) { _secondaryStorageCapacityThreshold = Double.parseDouble(secondaryStorageCapacityThreshold); @@ -192,7 +192,7 @@ public class AlertManagerImpl implements AlertManager { } _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_STORAGE, _storageCapacityThreshold); - _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, _storageAllocCapacityThreshold); + _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, _storageAllocCapacityThreshold); _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, _cpuCapacityThreshold); _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, _memoryCapacityThreshold); _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP, _publicIPCapacityThreshold); @@ -202,75 +202,75 @@ public class AlertManagerImpl implements AlertManager { _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP, _directNetworkPublicIpCapacityThreshold); _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_LOCAL_STORAGE, _localStorageCapacityThreshold); - - String capacityCheckPeriodStr = configs.get("capacity.check.period"); - if (capacityCheckPeriodStr != null) { + + String capacityCheckPeriodStr = configs.get("capacity.check.period"); + if (capacityCheckPeriodStr != null) { _capacityCheckPeriod = Long.parseLong(capacityCheckPeriodStr); if(_capacityCheckPeriod <= 0) _capacityCheckPeriod = Long.parseLong(Config.CapacityCheckPeriod.getDefaultValue()); - } - - String cpuOverProvisioningFactorStr = configs.get("cpu.overprovisioning.factor"); - if (cpuOverProvisioningFactorStr != null) { - _cpuOverProvisioningFactor = NumbersUtil.parseFloat(cpuOverProvisioningFactorStr,1); - if(_cpuOverProvisioningFactor < 1){ - _cpuOverProvisioningFactor = 1; - } } - - _timer = new Timer("CapacityChecker"); - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - _timer.schedule(new CapacityChecker(), INITIAL_CAPACITY_CHECK_DELAY, _capacityCheckPeriod); - return true; - } - - @Override - public boolean stop() { - _timer.cancel(); - return true; - } - - @Override - public void clearAlert(short alertType, long dataCenterId, long podId) { - try { - if (_emailAlert != null) { - _emailAlert.clearAlert(alertType, dataCenterId, podId); - } - } catch (Exception ex) { - s_logger.error("Problem clearing email alert", ex); - } - } - - @Override - public void sendAlert(short alertType, long dataCenterId, Long podId, String subject, String 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 { - if (_emailAlert != null) { - _emailAlert.sendAlert(alertType, dataCenterId, podId, null, subject, body); - } - } catch (Exception ex) { - s_logger.error("Problem sending email alert", ex); - } - } - - @Override @DB - public void recalculateCapacity() { - // FIXME: the right way to do this is to register a listener (see RouterStatsListener, VMSyncListener) - // for the vm sync state. The listener model has connects/disconnects to keep things in sync much better - // than this model right now, so when a VM is started, we update the amount allocated, and when a VM - // is stopped we updated the amount allocated, and when VM sync reports a changed state, we update - // the amount allocated. Hopefully it's limited to 3 entry points and will keep the amount allocated + + String cpuOverProvisioningFactorStr = configs.get("cpu.overprovisioning.factor"); + if (cpuOverProvisioningFactorStr != null) { + _cpuOverProvisioningFactor = NumbersUtil.parseFloat(cpuOverProvisioningFactorStr,1); + if(_cpuOverProvisioningFactor < 1){ + _cpuOverProvisioningFactor = 1; + } + } + + _timer = new Timer("CapacityChecker"); + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + _timer.schedule(new CapacityChecker(), INITIAL_CAPACITY_CHECK_DELAY, _capacityCheckPeriod); + return true; + } + + @Override + public boolean stop() { + _timer.cancel(); + return true; + } + + @Override + public void clearAlert(short alertType, long dataCenterId, long podId) { + try { + if (_emailAlert != null) { + _emailAlert.clearAlert(alertType, dataCenterId, podId); + } + } catch (Exception ex) { + s_logger.error("Problem clearing email alert", ex); + } + } + + @Override + public void sendAlert(short alertType, long dataCenterId, Long podId, String subject, String 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 { + if (_emailAlert != null) { + _emailAlert.sendAlert(alertType, dataCenterId, podId, null, subject, body); + } + } catch (Exception ex) { + s_logger.error("Problem sending email alert", ex); + } + } + + @Override @DB + public void recalculateCapacity() { + // FIXME: the right way to do this is to register a listener (see RouterStatsListener, VMSyncListener) + // for the vm sync state. The listener model has connects/disconnects to keep things in sync much better + // than this model right now, so when a VM is started, we update the amount allocated, and when a VM + // is stopped we updated the amount allocated, and when VM sync reports a changed state, we update + // the amount allocated. Hopefully it's limited to 3 entry points and will keep the amount allocated // per host accurate. try { @@ -279,8 +279,8 @@ public class AlertManagerImpl implements AlertManager { s_logger.debug("recalculating system capacity"); s_logger.debug("Executing cpu/ram capacity update"); } - - // Calculate CPU and RAM capacities + + // Calculate CPU and RAM capacities // get all hosts...even if they are not in 'UP' state List hosts = _resourceMgr.listAllNotInMaintenanceHostsInOneZone(Host.Type.Routing, null); for (HostVO host : hosts) { @@ -291,9 +291,9 @@ public class AlertManagerImpl implements AlertManager { s_logger.debug("Done executing cpu/ram capacity update"); s_logger.debug("Executing storage capacity update"); } - // Calculate storage pool capacity - List storagePools = _storagePoolDao.listAll(); - for (StoragePoolVO pool : storagePools) { + // Calculate storage pool capacity + List storagePools = _storagePoolDao.listAll(); + for (StoragePoolVO pool : storagePools) { long disk = _capacityMgr.getAllocatedPoolCapacity(pool, null); if (pool.isShared()){ _storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, disk); @@ -305,18 +305,18 @@ public class AlertManagerImpl implements AlertManager { if (s_logger.isDebugEnabled()) { s_logger.debug("Done executing storage capacity update"); s_logger.debug("Executing capacity updates for public ip and Vlans"); - } - - List datacenters = _dcDao.listAll(); - for (DataCenterVO datacenter : datacenters) { - long dcId = datacenter.getId(); + } + + List datacenters = _dcDao.listAll(); + for (DataCenterVO datacenter : datacenters) { + long dcId = datacenter.getId(); //NOTE //What happens if we have multiple vlans? Dashboard currently shows stats //with no filter based on a vlan //ideal way would be to remove out the vlan param, and filter only on dcId //implementing the same - + // Calculate new Public IP capacity for Virtual Network if (datacenter.getNetworkType() == NetworkType.Advanced){ createOrUpdateIpCapacity(dcId, null, CapacityVO.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP); @@ -328,7 +328,7 @@ public class AlertManagerImpl implements AlertManager { if (datacenter.getNetworkType() == NetworkType.Advanced){ //Calculate VLAN's capacity createOrUpdateVlanCapacity(dcId); - } + } } if (s_logger.isDebugEnabled()) { @@ -336,23 +336,23 @@ public class AlertManagerImpl implements AlertManager { s_logger.debug("Executing capacity updates for private ip"); } - // Calculate new Private IP capacity - List pods = _podDao.listAll(); - for (HostPodVO pod : pods) { - long podId = pod.getId(); - long dcId = pod.getDataCenterId(); + // Calculate new Private IP capacity + List pods = _podDao.listAll(); + for (HostPodVO pod : pods) { + long podId = pod.getId(); + long dcId = pod.getDataCenterId(); - createOrUpdateIpCapacity(dcId, podId, CapacityVO.CAPACITY_TYPE_PRIVATE_IP); + createOrUpdateIpCapacity(dcId, podId, CapacityVO.CAPACITY_TYPE_PRIVATE_IP); } if (s_logger.isDebugEnabled()) { s_logger.debug("Done executing capacity updates for private ip"); s_logger.debug("Done recalculating system capacity"); - } + } } catch (Throwable t) { s_logger.error("Caught exception in recalculating capacity", t); - } + } } private void createOrUpdateVlanCapacity(long dcId) { @@ -416,19 +416,19 @@ public class AlertManagerImpl implements AlertManager { _capacityDao.update(capacity.getId(), capacity); } - } - - class CapacityChecker extends TimerTask { - @Override - public void run() { + } + + class CapacityChecker extends TimerTask { + @Override + public void run() { try { s_logger.debug("Running Capacity Checker ... "); checkForAlerts(); - s_logger.debug("Done running Capacity Checker ... "); - } catch (Throwable t) { - s_logger.error("Exception in CapacityChecker", t); - } - } + s_logger.debug("Done running Capacity Checker ... "); + } catch (Throwable t) { + s_logger.error("Exception in CapacityChecker", t); + } + } } @@ -659,142 +659,142 @@ public class AlertManagerImpl implements AlertManager { clusterCapacityTypes.add(Capacity.CAPACITY_TYPE_LOCAL_STORAGE); return clusterCapacityTypes; - } - - class EmailAlert { - private Session _smtpSession; - private InternetAddress[] _recipientList; - private final String _smtpHost; - private int _smtpPort = -1; - private boolean _smtpUseAuth = false; - private final String _smtpUsername; - private final String _smtpPassword; - private final String _emailSender; - - public EmailAlert(String[] recipientList, String smtpHost, int smtpPort, boolean smtpUseAuth, final String smtpUsername, final String smtpPassword, String emailSender, boolean smtpDebug) { - if (recipientList != null) { - _recipientList = new InternetAddress[recipientList.length]; - for (int i = 0; i < recipientList.length; i++) { - try { - _recipientList[i] = new InternetAddress(recipientList[i], recipientList[i]); - } catch (Exception ex) { - s_logger.error("Exception creating address for: " + recipientList[i], ex); - } - } - } - - _smtpHost = smtpHost; - _smtpPort = smtpPort; - _smtpUseAuth = smtpUseAuth; - _smtpUsername = smtpUsername; - _smtpPassword = smtpPassword; - _emailSender = emailSender; - - if (_smtpHost != null) { - Properties smtpProps = new Properties(); - smtpProps.put("mail.smtp.host", smtpHost); - smtpProps.put("mail.smtp.port", smtpPort); - smtpProps.put("mail.smtp.auth", ""+smtpUseAuth); - if (smtpUsername != null) { - smtpProps.put("mail.smtp.user", smtpUsername); - } - - smtpProps.put("mail.smtps.host", smtpHost); - smtpProps.put("mail.smtps.port", smtpPort); - smtpProps.put("mail.smtps.auth", ""+smtpUseAuth); - if (smtpUsername != null) { - smtpProps.put("mail.smtps.user", smtpUsername); - } - - if ((smtpUsername != null) && (smtpPassword != null)) { - _smtpSession = Session.getInstance(smtpProps, new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(smtpUsername, smtpPassword); - } - }); - } else { - _smtpSession = Session.getInstance(smtpProps); - } - _smtpSession.setDebug(smtpDebug); - } else { - _smtpSession = null; - } - } - - // TODO: make sure this handles SSL transport (useAuth is true) and regular - public void sendAlert(short alertType, long dataCenterId, Long podId, Long clusterId, String subject, String content) throws MessagingException, UnsupportedEncodingException { - AlertVO alert = null; - if ((alertType != AlertManager.ALERT_TYPE_HOST) && - (alertType != AlertManager.ALERT_TYPE_USERVM) && - (alertType != AlertManager.ALERT_TYPE_DOMAIN_ROUTER) && + } + + class EmailAlert { + private Session _smtpSession; + private InternetAddress[] _recipientList; + private final String _smtpHost; + private int _smtpPort = -1; + private boolean _smtpUseAuth = false; + private final String _smtpUsername; + private final String _smtpPassword; + private final String _emailSender; + + public EmailAlert(String[] recipientList, String smtpHost, int smtpPort, boolean smtpUseAuth, final String smtpUsername, final String smtpPassword, String emailSender, boolean smtpDebug) { + if (recipientList != null) { + _recipientList = new InternetAddress[recipientList.length]; + for (int i = 0; i < recipientList.length; i++) { + try { + _recipientList[i] = new InternetAddress(recipientList[i], recipientList[i]); + } catch (Exception ex) { + s_logger.error("Exception creating address for: " + recipientList[i], ex); + } + } + } + + _smtpHost = smtpHost; + _smtpPort = smtpPort; + _smtpUseAuth = smtpUseAuth; + _smtpUsername = smtpUsername; + _smtpPassword = smtpPassword; + _emailSender = emailSender; + + if (_smtpHost != null) { + Properties smtpProps = new Properties(); + smtpProps.put("mail.smtp.host", smtpHost); + smtpProps.put("mail.smtp.port", smtpPort); + smtpProps.put("mail.smtp.auth", ""+smtpUseAuth); + if (smtpUsername != null) { + smtpProps.put("mail.smtp.user", smtpUsername); + } + + smtpProps.put("mail.smtps.host", smtpHost); + smtpProps.put("mail.smtps.port", smtpPort); + smtpProps.put("mail.smtps.auth", ""+smtpUseAuth); + if (smtpUsername != null) { + smtpProps.put("mail.smtps.user", smtpUsername); + } + + if ((smtpUsername != null) && (smtpPassword != null)) { + _smtpSession = Session.getInstance(smtpProps, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(smtpUsername, smtpPassword); + } + }); + } else { + _smtpSession = Session.getInstance(smtpProps); + } + _smtpSession.setDebug(smtpDebug); + } else { + _smtpSession = null; + } + } + + // TODO: make sure this handles SSL transport (useAuth is true) and regular + public void sendAlert(short alertType, long dataCenterId, Long podId, Long clusterId, String subject, String content) throws MessagingException, UnsupportedEncodingException { + AlertVO alert = null; + if ((alertType != AlertManager.ALERT_TYPE_HOST) && + (alertType != AlertManager.ALERT_TYPE_USERVM) && + (alertType != AlertManager.ALERT_TYPE_DOMAIN_ROUTER) && (alertType != AlertManager.ALERT_TYPE_CONSOLE_PROXY) && - (alertType != AlertManager.ALERT_TYPE_SSVM) && - (alertType != AlertManager.ALERT_TYPE_STORAGE_MISC) && - (alertType != AlertManager.ALERT_TYPE_MANAGMENT_NODE)) { - alert = _alertDao.getLastAlert(alertType, dataCenterId, podId, clusterId); - } - - if (alert == null) { - // set up a new alert - AlertVO newAlert = new AlertVO(); - newAlert.setType(alertType); + (alertType != AlertManager.ALERT_TYPE_SSVM) && + (alertType != AlertManager.ALERT_TYPE_STORAGE_MISC) && + (alertType != AlertManager.ALERT_TYPE_MANAGMENT_NODE)) { + alert = _alertDao.getLastAlert(alertType, dataCenterId, podId, clusterId); + } + + if (alert == null) { + // set up a new alert + AlertVO newAlert = new AlertVO(); + newAlert.setType(alertType); newAlert.setSubject(subject); - newAlert.setClusterId(clusterId); - newAlert.setPodId(podId); - newAlert.setDataCenterId(dataCenterId); - newAlert.setSentCount(1); // initialize sent count to 1 since we are now sending an alert - newAlert.setLastSent(new Date()); - _alertDao.persist(newAlert); - } else { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Have already sent: " + alert.getSentCount() + " emails for alert type '" + alertType + "' -- skipping send email"); - } - return; - } - - if (_smtpSession != null) { - SMTPMessage msg = new SMTPMessage(_smtpSession); - msg.setSender(new InternetAddress(_emailSender, _emailSender)); - msg.setFrom(new InternetAddress(_emailSender, _emailSender)); - for (InternetAddress address : _recipientList) { - msg.addRecipient(RecipientType.TO, address); - } - msg.setSubject(subject); - msg.setSentDate(new Date()); - msg.setContent(content, "text/plain"); - msg.saveChanges(); - - SMTPTransport smtpTrans = null; - if (_smtpUseAuth) { - smtpTrans = new SMTPSSLTransport(_smtpSession, new URLName("smtp", _smtpHost, _smtpPort, null, _smtpUsername, _smtpPassword)); - } else { - smtpTrans = new SMTPTransport(_smtpSession, new URLName("smtp", _smtpHost, _smtpPort, null, _smtpUsername, _smtpPassword)); - } - smtpTrans.connect(); - smtpTrans.sendMessage(msg, msg.getAllRecipients()); - smtpTrans.close(); - } - } - - public void clearAlert(short alertType, long dataCenterId, Long podId) { - if (alertType != -1) { - AlertVO alert = _alertDao.getLastAlert(alertType, dataCenterId, podId, null); - if (alert != null) { - AlertVO updatedAlert = _alertDao.createForUpdate(); - updatedAlert.setResolved(new Date()); - _alertDao.update(alert.getId(), updatedAlert); - } - } - } - } - - private static String formatPercent(double percentage) { - return _dfPct.format(percentage*100); - } - - private static String formatBytesToMegabytes(double bytes) { - double megaBytes = (bytes / (1024 * 1024)); - return _dfWhole.format(megaBytes); - } -} + newAlert.setClusterId(clusterId); + newAlert.setPodId(podId); + newAlert.setDataCenterId(dataCenterId); + newAlert.setSentCount(1); // initialize sent count to 1 since we are now sending an alert + newAlert.setLastSent(new Date()); + _alertDao.persist(newAlert); + } else { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Have already sent: " + alert.getSentCount() + " emails for alert type '" + alertType + "' -- skipping send email"); + } + return; + } + + if (_smtpSession != null) { + SMTPMessage msg = new SMTPMessage(_smtpSession); + msg.setSender(new InternetAddress(_emailSender, _emailSender)); + msg.setFrom(new InternetAddress(_emailSender, _emailSender)); + for (InternetAddress address : _recipientList) { + msg.addRecipient(RecipientType.TO, address); + } + msg.setSubject(subject); + msg.setSentDate(new Date()); + msg.setContent(content, "text/plain"); + msg.saveChanges(); + + SMTPTransport smtpTrans = null; + if (_smtpUseAuth) { + smtpTrans = new SMTPSSLTransport(_smtpSession, new URLName("smtp", _smtpHost, _smtpPort, null, _smtpUsername, _smtpPassword)); + } else { + smtpTrans = new SMTPTransport(_smtpSession, new URLName("smtp", _smtpHost, _smtpPort, null, _smtpUsername, _smtpPassword)); + } + smtpTrans.connect(); + smtpTrans.sendMessage(msg, msg.getAllRecipients()); + smtpTrans.close(); + } + } + + public void clearAlert(short alertType, long dataCenterId, Long podId) { + if (alertType != -1) { + AlertVO alert = _alertDao.getLastAlert(alertType, dataCenterId, podId, null); + if (alert != null) { + AlertVO updatedAlert = _alertDao.createForUpdate(); + updatedAlert.setResolved(new Date()); + _alertDao.update(alert.getId(), updatedAlert); + } + } + } + } + + private static String formatPercent(double percentage) { + return _dfPct.format(percentage*100); + } + + private static String formatBytesToMegabytes(double bytes) { + double megaBytes = (bytes / (1024 * 1024)); + return _dfWhole.format(megaBytes); + } +} diff --git a/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java b/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java index e93a1f5f8b8..49dfbbc609e 100644 --- a/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java +++ b/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java @@ -10,217 +10,217 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert; - -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.alert.AlertAdapter; -import com.cloud.alert.AlertManager; -import com.cloud.consoleproxy.ConsoleProxyAlertEventArgs; -import com.cloud.consoleproxy.ConsoleProxyManager; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.events.SubscriptionMgr; -import com.cloud.vm.ConsoleProxyVO; -import com.cloud.vm.dao.ConsoleProxyDao; - -@Local(value=AlertAdapter.class) -public class ConsoleProxyAlertAdapter implements AlertAdapter { - - private static final Logger s_logger = Logger.getLogger(ConsoleProxyAlertAdapter.class); - - private AlertManager _alertMgr; - private String _name; - - private DataCenterDao _dcDao; - private ConsoleProxyDao _consoleProxyDao; - - public void onProxyAlert(Object sender, ConsoleProxyAlertEventArgs args) { - if(s_logger.isDebugEnabled()) - s_logger.debug("received console proxy alert"); - - DataCenterVO dc = _dcDao.findById(args.getZoneId()); - ConsoleProxyVO proxy = args.getProxy(); - if(proxy == null) - proxy = _consoleProxyDao.findById(args.getProxyId()); - - switch(args.getType()) { - case ConsoleProxyAlertEventArgs.PROXY_CREATED : - if(s_logger.isDebugEnabled()) - s_logger.debug("New console proxy created, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - proxy.getPrivateIpAddress()); - break; - - case ConsoleProxyAlertEventArgs.PROXY_UP : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy is up, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - proxy.getPrivateIpAddress()); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_CONSOLE_PROXY, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Console proxy up in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() - + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), - "Console proxy up (zone " + dc.getName() + ")" - ); - break; - - case ConsoleProxyAlertEventArgs.PROXY_DOWN : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy is down, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_CONSOLE_PROXY, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Console proxy down in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() - + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), - "Console proxy down (zone " + dc.getName() + ")" - ); - break; - - case ConsoleProxyAlertEventArgs.PROXY_REBOOTED : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy is rebooted, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_CONSOLE_PROXY, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Console proxy rebooted in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() - + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), - "Console proxy rebooted (zone " + dc.getName() + ")" - ); - break; - - case ConsoleProxyAlertEventArgs.PROXY_CREATE_FAILURE : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy creation failure, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_CONSOLE_PROXY, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Console proxy creation failure. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() - + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()) - + ", error details: " + args.getMessage(), - "Console proxy creation failure (zone " + dc.getName() + ")" - ); - break; - - case ConsoleProxyAlertEventArgs.PROXY_START_FAILURE : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy startup failure, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_CONSOLE_PROXY, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Console proxy startup failure. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() - + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()) - + ", error details: " + args.getMessage(), - "Console proxy startup failure (zone " + dc.getName() + ")" - ); - break; - - case ConsoleProxyAlertEventArgs.PROXY_FIREWALL_ALERT : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy firewall alert, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_CONSOLE_PROXY, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Failed to open console proxy firewall port. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() - + ", public IP: " + proxy.getPublicIpAddress() - + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), - "Console proxy alert (zone " + dc.getName() + ")" - ); - break; - - case ConsoleProxyAlertEventArgs.PROXY_STORAGE_ALERT : - if(s_logger.isDebugEnabled()) - s_logger.debug("Console proxy storage alert, zone: " + dc.getName() + ", proxy: " + - proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - proxy.getPrivateIpAddress() + ", message: " + args.getMessage()); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_STORAGE_MISC, - args.getZoneId(), - proxy.getPodIdToDeployIn(), - "Console proxy storage issue. zone: " + dc.getName() + ", message: " + args.getMessage(), - "Console proxy alert (zone " + dc.getName() + ")" - ); - break; - } - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - - if (s_logger.isInfoEnabled()) - s_logger.info("Start configuring console proxy alert manager : " + name); - - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - - _dcDao = locator.getDao(DataCenterDao.class); - if (_dcDao == null) { - throw new ConfigurationException("Unable to get " + DataCenterDao.class.getName()); - } - - _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); - if (_consoleProxyDao == null) { - throw new ConfigurationException("Unable to get " + ConsoleProxyDao.class.getName()); - } - - _alertMgr = locator.getManager(AlertManager.class); - if (_alertMgr == null) { - throw new ConfigurationException("Unable to get " + AlertManager.class.getName()); - } - - try { - SubscriptionMgr.getInstance().subscribe(ConsoleProxyManager.ALERT_SUBJECT, this, "onProxyAlert"); - } catch (SecurityException e) { - throw new ConfigurationException("Unable to register console proxy event subscription, exception: " + e); - } catch (NoSuchMethodException e) { - throw new ConfigurationException("Unable to register console proxy event subscription, exception: " + e); - } - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } -} +package com.cloud.alert; + +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.alert.AlertAdapter; +import com.cloud.alert.AlertManager; +import com.cloud.consoleproxy.ConsoleProxyAlertEventArgs; +import com.cloud.consoleproxy.ConsoleProxyManager; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.events.SubscriptionMgr; +import com.cloud.vm.ConsoleProxyVO; +import com.cloud.vm.dao.ConsoleProxyDao; + +@Local(value=AlertAdapter.class) +public class ConsoleProxyAlertAdapter implements AlertAdapter { + + private static final Logger s_logger = Logger.getLogger(ConsoleProxyAlertAdapter.class); + + private AlertManager _alertMgr; + private String _name; + + private DataCenterDao _dcDao; + private ConsoleProxyDao _consoleProxyDao; + + public void onProxyAlert(Object sender, ConsoleProxyAlertEventArgs args) { + if(s_logger.isDebugEnabled()) + s_logger.debug("received console proxy alert"); + + DataCenterVO dc = _dcDao.findById(args.getZoneId()); + ConsoleProxyVO proxy = args.getProxy(); + if(proxy == null) + proxy = _consoleProxyDao.findById(args.getProxyId()); + + switch(args.getType()) { + case ConsoleProxyAlertEventArgs.PROXY_CREATED : + if(s_logger.isDebugEnabled()) + s_logger.debug("New console proxy created, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + proxy.getPrivateIpAddress()); + break; + + case ConsoleProxyAlertEventArgs.PROXY_UP : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy is up, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + proxy.getPrivateIpAddress()); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_CONSOLE_PROXY, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Console proxy up in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), + "Console proxy up (zone " + dc.getName() + ")" + ); + break; + + case ConsoleProxyAlertEventArgs.PROXY_DOWN : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy is down, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_CONSOLE_PROXY, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Console proxy down in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), + "Console proxy down (zone " + dc.getName() + ")" + ); + break; + + case ConsoleProxyAlertEventArgs.PROXY_REBOOTED : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy is rebooted, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_CONSOLE_PROXY, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Console proxy rebooted in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), + "Console proxy rebooted (zone " + dc.getName() + ")" + ); + break; + + case ConsoleProxyAlertEventArgs.PROXY_CREATE_FAILURE : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy creation failure, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_CONSOLE_PROXY, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Console proxy creation failure. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()) + + ", error details: " + args.getMessage(), + "Console proxy creation failure (zone " + dc.getName() + ")" + ); + break; + + case ConsoleProxyAlertEventArgs.PROXY_START_FAILURE : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy startup failure, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_CONSOLE_PROXY, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Console proxy startup failure. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()) + + ", error details: " + args.getMessage(), + "Console proxy startup failure (zone " + dc.getName() + ")" + ); + break; + + case ConsoleProxyAlertEventArgs.PROXY_FIREWALL_ALERT : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy firewall alert, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_CONSOLE_PROXY, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Failed to open console proxy firewall port. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + + ", public IP: " + proxy.getPublicIpAddress() + + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), + "Console proxy alert (zone " + dc.getName() + ")" + ); + break; + + case ConsoleProxyAlertEventArgs.PROXY_STORAGE_ALERT : + if(s_logger.isDebugEnabled()) + s_logger.debug("Console proxy storage alert, zone: " + dc.getName() + ", proxy: " + + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + proxy.getPrivateIpAddress() + ", message: " + args.getMessage()); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_STORAGE_MISC, + args.getZoneId(), + proxy.getPodIdToDeployIn(), + "Console proxy storage issue. zone: " + dc.getName() + ", message: " + args.getMessage(), + "Console proxy alert (zone " + dc.getName() + ")" + ); + break; + } + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + + if (s_logger.isInfoEnabled()) + s_logger.info("Start configuring console proxy alert manager : " + name); + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + + _dcDao = locator.getDao(DataCenterDao.class); + if (_dcDao == null) { + throw new ConfigurationException("Unable to get " + DataCenterDao.class.getName()); + } + + _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); + if (_consoleProxyDao == null) { + throw new ConfigurationException("Unable to get " + ConsoleProxyDao.class.getName()); + } + + _alertMgr = locator.getManager(AlertManager.class); + if (_alertMgr == null) { + throw new ConfigurationException("Unable to get " + AlertManager.class.getName()); + } + + try { + SubscriptionMgr.getInstance().subscribe(ConsoleProxyManager.ALERT_SUBJECT, this, "onProxyAlert"); + } catch (SecurityException e) { + throw new ConfigurationException("Unable to register console proxy event subscription, exception: " + e); + } catch (NoSuchMethodException e) { + throw new ConfigurationException("Unable to register console proxy event subscription, exception: " + e); + } + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } +} diff --git a/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java b/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java index 6119bc25cb9..9b1e33da8c8 100644 --- a/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java +++ b/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java @@ -10,200 +10,200 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert; - -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.alert.AlertAdapter; -import com.cloud.alert.AlertManager; -import com.cloud.consoleproxy.ConsoleProxyManager; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.storage.secondary.SecStorageVmAlertEventArgs; -import com.cloud.storage.secondary.SecondaryStorageVmManager; -import com.cloud.utils.component.Inject; -import com.cloud.utils.events.SubscriptionMgr; -import com.cloud.vm.SecondaryStorageVmVO; -import com.cloud.vm.dao.SecondaryStorageVmDao; - -@Local(value=AlertAdapter.class) -public class SecondaryStorageVmAlertAdapter implements AlertAdapter { - - private static final Logger s_logger = Logger.getLogger(SecondaryStorageVmAlertAdapter.class); - private String _name; - - @Inject private AlertManager _alertMgr; - @Inject private DataCenterDao _dcDao; - @Inject private SecondaryStorageVmDao _ssvmDao; - - public void onSSVMAlert(Object sender, SecStorageVmAlertEventArgs args) { - if(s_logger.isDebugEnabled()) - s_logger.debug("received secondary storage vm alert"); - - DataCenterVO dc = _dcDao.findById(args.getZoneId()); - SecondaryStorageVmVO secStorageVm = args.getSecStorageVm(); - if(secStorageVm == null) - secStorageVm = _ssvmDao.findById(args.getSecStorageVmId()); - - switch(args.getType()) { - case SecStorageVmAlertEventArgs.SSVM_CREATED : - if(s_logger.isDebugEnabled()) - s_logger.debug("New secondary storage vm created, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - secStorageVm.getPrivateIpAddress()); - break; - - case SecStorageVmAlertEventArgs.SSVM_UP : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm is up, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - secStorageVm.getPrivateIpAddress()); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_SSVM, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Secondary Storage Vm up in zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() - + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), - "Secondary Storage Vm up (zone " + dc.getName() + ")" - ); - break; - - case SecStorageVmAlertEventArgs.SSVM_DOWN : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm is down, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_SSVM, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Secondary Storage Vm down in zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() - + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), - "Secondary Storage Vm down (zone " + dc.getName() + ")" - ); - break; - - case SecStorageVmAlertEventArgs.SSVM_REBOOTED : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm is rebooted, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_SSVM, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Secondary Storage Vm rebooted in zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() - + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), - "Secondary Storage Vm rebooted (zone " + dc.getName() + ")" - ); - break; - - case SecStorageVmAlertEventArgs.SSVM_CREATE_FAILURE : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm creation failure, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_SSVM, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Secondary Storage Vm creation failure. zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() - + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) - + ", error details: " + args.getMessage(), - "Secondary Storage Vm creation failure (zone " + dc.getName() + ")" - ); - break; - - case SecStorageVmAlertEventArgs.SSVM_START_FAILURE : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm startup failure, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_SSVM, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Secondary Storage Vm startup failure. zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() - + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) - + ", error details: " + args.getMessage(), - "Secondary Storage Vm startup failure (zone " + dc.getName() + ")" - ); - break; - - case SecStorageVmAlertEventArgs.SSVM_FIREWALL_ALERT : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm firewall alert, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_SSVM, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Failed to open secondary storage vm firewall port. zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() - + ", public IP: " + secStorageVm.getPublicIpAddress() - + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), - "Secondary Storage Vm alert (zone " + dc.getName() + ")" - ); - break; - - case SecStorageVmAlertEventArgs.SSVM_STORAGE_ALERT : - if(s_logger.isDebugEnabled()) - s_logger.debug("Secondary Storage Vm storage alert, zone: " + dc.getName() + ", secStorageVm: " + - secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - secStorageVm.getPrivateIpAddress() + ", message: " + args.getMessage()); - - _alertMgr.sendAlert( - AlertManager.ALERT_TYPE_STORAGE_MISC, - args.getZoneId(), - secStorageVm.getPodIdToDeployIn(), - "Secondary Storage Vm storage issue. zone: " + dc.getName() + ", message: " + args.getMessage(), - "Secondary Storage Vm alert (zone " + dc.getName() + ")" - ); - break; - } - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - - if (s_logger.isInfoEnabled()) - s_logger.info("Start configuring secondary storage vm alert manager : " + name); - - try { - SubscriptionMgr.getInstance().subscribe(SecondaryStorageVmManager.ALERT_SUBJECT, this, "onSSVMAlert"); - } catch (SecurityException e) { - throw new ConfigurationException("Unable to register secondary storage vm event subscription, exception: " + e); - } catch (NoSuchMethodException e) { - throw new ConfigurationException("Unable to register secondary storage vm event subscription, exception: " + e); - } - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } -} +package com.cloud.alert; + +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.alert.AlertAdapter; +import com.cloud.alert.AlertManager; +import com.cloud.consoleproxy.ConsoleProxyManager; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.storage.secondary.SecStorageVmAlertEventArgs; +import com.cloud.storage.secondary.SecondaryStorageVmManager; +import com.cloud.utils.component.Inject; +import com.cloud.utils.events.SubscriptionMgr; +import com.cloud.vm.SecondaryStorageVmVO; +import com.cloud.vm.dao.SecondaryStorageVmDao; + +@Local(value=AlertAdapter.class) +public class SecondaryStorageVmAlertAdapter implements AlertAdapter { + + private static final Logger s_logger = Logger.getLogger(SecondaryStorageVmAlertAdapter.class); + private String _name; + + @Inject private AlertManager _alertMgr; + @Inject private DataCenterDao _dcDao; + @Inject private SecondaryStorageVmDao _ssvmDao; + + public void onSSVMAlert(Object sender, SecStorageVmAlertEventArgs args) { + if(s_logger.isDebugEnabled()) + s_logger.debug("received secondary storage vm alert"); + + DataCenterVO dc = _dcDao.findById(args.getZoneId()); + SecondaryStorageVmVO secStorageVm = args.getSecStorageVm(); + if(secStorageVm == null) + secStorageVm = _ssvmDao.findById(args.getSecStorageVmId()); + + switch(args.getType()) { + case SecStorageVmAlertEventArgs.SSVM_CREATED : + if(s_logger.isDebugEnabled()) + s_logger.debug("New secondary storage vm created, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + secStorageVm.getPrivateIpAddress()); + break; + + case SecStorageVmAlertEventArgs.SSVM_UP : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm is up, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + secStorageVm.getPrivateIpAddress()); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_SSVM, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm up in zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), + "Secondary Storage Vm up (zone " + dc.getName() + ")" + ); + break; + + case SecStorageVmAlertEventArgs.SSVM_DOWN : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm is down, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_SSVM, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm down in zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), + "Secondary Storage Vm down (zone " + dc.getName() + ")" + ); + break; + + case SecStorageVmAlertEventArgs.SSVM_REBOOTED : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm is rebooted, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_SSVM, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm rebooted in zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), + "Secondary Storage Vm rebooted (zone " + dc.getName() + ")" + ); + break; + + case SecStorageVmAlertEventArgs.SSVM_CREATE_FAILURE : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm creation failure, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_SSVM, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm creation failure. zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) + + ", error details: " + args.getMessage(), + "Secondary Storage Vm creation failure (zone " + dc.getName() + ")" + ); + break; + + case SecStorageVmAlertEventArgs.SSVM_START_FAILURE : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm startup failure, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_SSVM, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm startup failure. zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) + + ", error details: " + args.getMessage(), + "Secondary Storage Vm startup failure (zone " + dc.getName() + ")" + ); + break; + + case SecStorageVmAlertEventArgs.SSVM_FIREWALL_ALERT : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm firewall alert, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_SSVM, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Failed to open secondary storage vm firewall port. zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + + ", public IP: " + secStorageVm.getPublicIpAddress() + + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()), + "Secondary Storage Vm alert (zone " + dc.getName() + ")" + ); + break; + + case SecStorageVmAlertEventArgs.SSVM_STORAGE_ALERT : + if(s_logger.isDebugEnabled()) + s_logger.debug("Secondary Storage Vm storage alert, zone: " + dc.getName() + ", secStorageVm: " + + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + secStorageVm.getPrivateIpAddress() + ", message: " + args.getMessage()); + + _alertMgr.sendAlert( + AlertManager.ALERT_TYPE_STORAGE_MISC, + args.getZoneId(), + secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm storage issue. zone: " + dc.getName() + ", message: " + args.getMessage(), + "Secondary Storage Vm alert (zone " + dc.getName() + ")" + ); + break; + } + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + + if (s_logger.isInfoEnabled()) + s_logger.info("Start configuring secondary storage vm alert manager : " + name); + + try { + SubscriptionMgr.getInstance().subscribe(SecondaryStorageVmManager.ALERT_SUBJECT, this, "onSSVMAlert"); + } catch (SecurityException e) { + throw new ConfigurationException("Unable to register secondary storage vm event subscription, exception: " + e); + } catch (NoSuchMethodException e) { + throw new ConfigurationException("Unable to register secondary storage vm event subscription, exception: " + e); + } + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } +} diff --git a/server/src/com/cloud/alert/dao/AlertDao.java b/server/src/com/cloud/alert/dao/AlertDao.java index 2280fcf49c0..8fd21090fb1 100755 --- a/server/src/com/cloud/alert/dao/AlertDao.java +++ b/server/src/com/cloud/alert/dao/AlertDao.java @@ -10,13 +10,13 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert.dao; - +package com.cloud.alert.dao; + import com.cloud.alert.AlertVO; import com.cloud.utils.db.GenericDao; - -public interface AlertDao extends GenericDao { + +public interface AlertDao extends GenericDao { AlertVO getLastAlert(short type, long dataCenterId, Long podId, Long clusterId); // This is for backward compatibility - AlertVO getLastAlert(short type, long dataCenterId, Long podId); -} + AlertVO getLastAlert(short type, long dataCenterId, Long podId); +} diff --git a/server/src/com/cloud/alert/dao/AlertDaoImpl.java b/server/src/com/cloud/alert/dao/AlertDaoImpl.java index 2134ba495a2..ad3c1f13cb1 100755 --- a/server/src/com/cloud/alert/dao/AlertDaoImpl.java +++ b/server/src/com/cloud/alert/dao/AlertDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert.dao; - +package com.cloud.alert.dao; + import java.util.List; import javax.ejb.Local; @@ -20,28 +20,28 @@ import com.cloud.alert.AlertVO; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria; - -@Local(value = { AlertDao.class }) -public class AlertDaoImpl extends GenericDaoBase implements AlertDao { - @Override - public AlertVO getLastAlert(short type, long dataCenterId, Long podId, Long clusterId) { - Filter searchFilter = new Filter(AlertVO.class, "createdDate", Boolean.FALSE, Long.valueOf(0), Long.valueOf(1)); - SearchCriteria sc = createSearchCriteria(); - - sc.addAnd("type", SearchCriteria.Op.EQ, Short.valueOf(type)); - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, Long.valueOf(dataCenterId)); - if (podId != null) { - sc.addAnd("podId", SearchCriteria.Op.EQ, podId); + +@Local(value = { AlertDao.class }) +public class AlertDaoImpl extends GenericDaoBase implements AlertDao { + @Override + public AlertVO getLastAlert(short type, long dataCenterId, Long podId, Long clusterId) { + Filter searchFilter = new Filter(AlertVO.class, "createdDate", Boolean.FALSE, Long.valueOf(0), Long.valueOf(1)); + SearchCriteria sc = createSearchCriteria(); + + sc.addAnd("type", SearchCriteria.Op.EQ, Short.valueOf(type)); + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, Long.valueOf(dataCenterId)); + if (podId != null) { + sc.addAnd("podId", SearchCriteria.Op.EQ, podId); } if (clusterId != null) { sc.addAnd("clusterId", SearchCriteria.Op.EQ, clusterId); - } - - List alerts = listBy(sc, searchFilter); - if ((alerts != null) && !alerts.isEmpty()) { - return alerts.get(0); - } - return null; + } + + List alerts = listBy(sc, searchFilter); + if ((alerts != null) && !alerts.isEmpty()) { + return alerts.get(0); + } + return null; } @Override @@ -60,5 +60,5 @@ public class AlertDaoImpl extends GenericDaoBase implements Alert return alerts.get(0); } return null; - } -} + } +} diff --git a/server/src/com/cloud/api/ApiGsonHelper.java b/server/src/com/cloud/api/ApiGsonHelper.java index fa4b690f34d..22afb79f3d3 100644 --- a/server/src/com/cloud/api/ApiGsonHelper.java +++ b/server/src/com/cloud/api/ApiGsonHelper.java @@ -10,23 +10,23 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api; - +package com.cloud.api; + import com.google.gson.GsonBuilder; import com.cloud.utils.IdentityProxy; import java.util.Map; -public class ApiGsonHelper { - private static final GsonBuilder s_gBuilder; - static { - s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - s_gBuilder.setVersion(1.3); +public class ApiGsonHelper { + private static final GsonBuilder s_gBuilder; + static { + s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + s_gBuilder.setVersion(1.3); s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter()); s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter()); s_gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter()); - } - - public static GsonBuilder getBuilder() { - return s_gBuilder; - } -} + } + + public static GsonBuilder getBuilder() { + return s_gBuilder; + } +} diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index ec018c967b5..31678d84d88 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -10,3346 +10,3346 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import org.apache.log4j.Logger; - -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.ApiResponseSerializer; -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.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.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.ProjectAccountResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; -import com.cloud.api.response.ResourceCountResponse; -import com.cloud.api.response.ResourceLimitResponse; -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.SnapshotPolicyResponse; -import com.cloud.api.response.SnapshotResponse; -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.VpnUsersResponse; -import com.cloud.api.response.ZoneResponse; -import com.cloud.async.AsyncJob; -import com.cloud.capacity.Capacity; -import com.cloud.capacity.CapacityVO; -import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; -import com.cloud.configuration.Configuration; -import com.cloud.configuration.Resource.ResourceOwnerType; -import com.cloud.configuration.Resource.ResourceType; -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.Vlan.VlanType; -import com.cloud.dc.VlanVO; -import com.cloud.domain.Domain; -import com.cloud.event.Event; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.host.HostStats; -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.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkProfile; -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.RemoteAccessVpn; -import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VpnUser; -import com.cloud.network.router.VirtualRouter; -import com.cloud.network.rules.FirewallRule; -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.security.SecurityGroup; -import com.cloud.network.security.SecurityGroupRules; -import com.cloud.network.security.SecurityGroupVO; -import com.cloud.network.security.SecurityRule; -import com.cloud.network.security.SecurityRule.SecurityRuleType; -import com.cloud.offering.DiskOffering; -import com.cloud.offering.NetworkOffering; -import com.cloud.offering.ServiceOffering; -import com.cloud.org.Cluster; -import com.cloud.projects.Project; -import com.cloud.projects.ProjectAccount; -import com.cloud.projects.ProjectInvitation; -import com.cloud.server.Criteria; -import com.cloud.storage.DiskOfferingVO; -import com.cloud.storage.GuestOS; -import com.cloud.storage.GuestOSCategoryVO; -import com.cloud.storage.Snapshot; -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.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.template.VirtualMachineTemplate; -import com.cloud.test.PodZoneConfig; -import com.cloud.user.Account; -import com.cloud.user.User; -import com.cloud.user.UserAccount; -import com.cloud.user.UserContext; -import com.cloud.user.UserStatisticsVO; -import com.cloud.user.UserVO; -import com.cloud.uservm.UserVm; -import com.cloud.utils.Pair; -import com.cloud.utils.StringUtils; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.ConsoleProxyVO; -import com.cloud.vm.InstanceGroup; -import com.cloud.vm.InstanceGroupVO; -import com.cloud.vm.NicProfile; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.VirtualMachine.Type; -import com.cloud.vm.VmStats; -import com.cloud.vm.dao.UserVmData; -import com.cloud.vm.dao.UserVmData.NicData; -import com.cloud.vm.dao.UserVmData.SecurityGroupData; - -public class ApiResponseHelper implements ResponseGenerator { - - public final Logger s_logger = Logger.getLogger(ApiResponseHelper.class); - private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##"); - - @Override - public UserResponse createUserResponse(User user) { - UserResponse userResponse = new UserResponse(); - Account account = ApiDBUtils.findAccountById(user.getAccountId()); - userResponse.setAccountName(account.getAccountName()); - userResponse.setAccountType(account.getType()); - userResponse.setCreated(user.getCreated()); - userResponse.setDomainId(account.getDomainId()); - userResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); - userResponse.setEmail(user.getEmail()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setId(user.getId()); - userResponse.setLastname(user.getLastname()); - userResponse.setState(user.getState().toString()); - userResponse.setTimezone(user.getTimezone()); - userResponse.setUsername(user.getUsername()); - userResponse.setApiKey(user.getApiKey()); - userResponse.setSecretKey(user.getSecretKey()); - userResponse.setObjectName("user"); - - return userResponse; - } - - // this method is used for response generation via createAccount (which creates an account + user) - @Override - public AccountResponse createUserAccountResponse(UserAccount user) { - return createAccountResponse(ApiDBUtils.findAccountById(user.getAccountId())); - } - - @Override - public AccountResponse createAccountResponse(Account account) { - boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); - AccountResponse accountResponse = new AccountResponse(); - accountResponse.setId(account.getId()); - accountResponse.setName(account.getAccountName()); - accountResponse.setAccountType(account.getType()); - accountResponse.setDomainId(account.getDomainId()); - accountResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); - accountResponse.setState(account.getState().toString()); - accountResponse.setNetworkDomain(account.getNetworkDomain()); - - // get network stat - List stats = ApiDBUtils.listUserStatsBy(account.getId()); - if (stats == null) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats"); - } - - Long bytesSent = 0L; - Long bytesReceived = 0L; - for (UserStatisticsVO stat : stats) { - Long rx = stat.getNetBytesReceived() + stat.getCurrentBytesReceived(); - Long tx = stat.getNetBytesSent() + stat.getCurrentBytesSent(); - bytesReceived = bytesReceived + Long.valueOf(rx); - bytesSent = bytesSent + Long.valueOf(tx); - } - accountResponse.setBytesReceived(bytesReceived); - accountResponse.setBytesSent(bytesSent); - - // Get resource limits and counts - - Long vmLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.user_vm, account.getId()); - String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); - Long vmTotal = ApiDBUtils.getResourceCount(ResourceType.user_vm, account.getId()); - String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); - accountResponse.setVmLimit(vmLimitDisplay); - accountResponse.setVmTotal(vmTotal); - accountResponse.setVmAvailable(vmAvail); - - Long ipLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.public_ip, account.getId()); - String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); - Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId()); - - Long ips = ipLimit - ipTotal; - // check how many free ips are left, and if it's less than max allowed number of ips from account - use this - // value - Long ipsLeft = ApiDBUtils.countFreePublicIps(); - boolean unlimited = true; - if (ips.longValue() > ipsLeft.longValue()) { - ips = ipsLeft; - unlimited = false; - } - - String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); - - accountResponse.setIpLimit(ipLimitDisplay); - accountResponse.setIpTotal(ipTotal); - accountResponse.setIpAvailable(ipAvail); - - Long volumeLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.volume, account.getId()); - String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); - Long volumeTotal = ApiDBUtils.getResourceCount(ResourceType.volume, account.getId()); - String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); - accountResponse.setVolumeLimit(volumeLimitDisplay); - accountResponse.setVolumeTotal(volumeTotal); - accountResponse.setVolumeAvailable(volumeAvail); - - Long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.snapshot, account.getId()); - String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); - Long snapshotTotal = ApiDBUtils.getResourceCount(ResourceType.snapshot, account.getId()); - String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); - accountResponse.setSnapshotLimit(snapshotLimitDisplay); - accountResponse.setSnapshotTotal(snapshotTotal); - accountResponse.setSnapshotAvailable(snapshotAvail); - - Long templateLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.template, account.getId()); - String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); - Long templateTotal = ApiDBUtils.getResourceCount(ResourceType.template, account.getId()); - String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); - accountResponse.setTemplateLimit(templateLimitDisplay); - accountResponse.setTemplateTotal(templateTotal); - accountResponse.setTemplateAvailable(templateAvail); - - // Get stopped and running VMs - int vmStopped = 0; - int vmRunning = 0; - - List permittedAccounts = new ArrayList(); - permittedAccounts.add(account.getId()); - - List virtualMachines = ApiDBUtils.searchForUserVMs(new Criteria(), permittedAccounts); - - // get Running/Stopped VMs - for (Iterator iter = virtualMachines.iterator(); iter.hasNext();) { - // count how many stopped/running vms we have - UserVm vm = iter.next(); - - if (vm.getState() == State.Stopped) { - vmStopped++; - } else if (vm.getState() == State.Running) { - vmRunning++; - } - } - - accountResponse.setVmStopped(vmStopped); - accountResponse.setVmRunning(vmRunning); - accountResponse.setObjectName("account"); - - //get resource limits for projects - Long projectLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.project, account.getId()); - String projectLimitDisplay = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit); - Long projectTotal = ApiDBUtils.getResourceCount(ResourceType.project, account.getId()); - String projectAvail = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal); - accountResponse.setProjectLimit(projectLimitDisplay); - accountResponse.setProjectTotal(projectTotal); - accountResponse.setProjectAvailable(projectAvail); - - //get resource limits for networks - Long networkLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.network, account.getId()); - String networkLimitDisplay = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit); - Long networkTotal = ApiDBUtils.getResourceCount(ResourceType.network, account.getId()); - String networkAvail = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit - networkTotal); - accountResponse.setNetworkLimit(networkLimitDisplay); - accountResponse.setNetworkTotal(networkTotal); - accountResponse.setNetworkAvailable(networkAvail); - - // adding all the users for an account as part of the response obj - List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); - List userResponseList = new ArrayList(); - for (UserVO user : usersForAccount) { - UserResponse userResponse = createUserResponse(user); - userResponseList.add(userResponse); - } - - accountResponse.setUsers(userResponseList); - accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); - return accountResponse; - } - - @Override - public UserResponse createUserResponse(UserAccount user) { - UserResponse userResponse = new UserResponse(); - userResponse.setAccountName(user.getAccountName()); - userResponse.setAccountType(user.getType()); - userResponse.setCreated(user.getCreated()); - userResponse.setDomainId(user.getDomainId()); - userResponse.setDomainName(ApiDBUtils.findDomainById(user.getDomainId()).getName()); - userResponse.setEmail(user.getEmail()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setId(user.getId()); - userResponse.setLastname(user.getLastname()); - userResponse.setState(user.getState()); - userResponse.setTimezone(user.getTimezone()); - userResponse.setUsername(user.getUsername()); - userResponse.setApiKey(user.getApiKey()); - userResponse.setSecretKey(user.getSecretKey()); - userResponse.setAccountId((user.getAccountId())); - userResponse.setObjectName("user"); - - return userResponse; - } - - @Override - public DomainResponse createDomainResponse(Domain domain) { - DomainResponse domainResponse = new DomainResponse(); - domainResponse.setDomainName(domain.getName()); - domainResponse.setId(domain.getId()); - domainResponse.setLevel(domain.getLevel()); - domainResponse.setNetworkDomain(domain.getNetworkDomain()); - domainResponse.setParentDomainId(domain.getParent()); - StringBuilder domainPath = new StringBuilder("ROOT"); - (domainPath.append(domain.getPath())).deleteCharAt(domainPath.length() - 1); - domainResponse.setPath(domainPath.toString()); - if (domain.getParent() != null) { - domainResponse.setParentDomainName(ApiDBUtils.findDomainById(domain.getParent()).getName()); - } - if (domain.getChildCount() > 0) { - domainResponse.setHasChild(true); - } - domainResponse.setObjectName("domain"); - return domainResponse; - } - - @Override - public DiskOfferingResponse createDiskOfferingResponse(DiskOffering offering) { - DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); - diskOfferingResponse.setId(offering.getId()); - diskOfferingResponse.setName(offering.getName()); - diskOfferingResponse.setDisplayText(offering.getDisplayText()); - diskOfferingResponse.setCreated(offering.getCreated()); - diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); - if (offering.getDomainId() != null) { - diskOfferingResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); - diskOfferingResponse.setDomainId(offering.getDomainId()); - } - diskOfferingResponse.setTags(offering.getTags()); - diskOfferingResponse.setCustomized(offering.isCustomized()); - diskOfferingResponse.setObjectName("diskoffering"); - return diskOfferingResponse; - } - - @Override - public ResourceLimitResponse createResourceLimitResponse(ResourceLimit limit) { - ResourceLimitResponse resourceLimitResponse = new ResourceLimitResponse(); - if (limit.getResourceOwnerType() == ResourceOwnerType.Domain) { - populateDomain(resourceLimitResponse, limit.getOwnerId()); - } else if (limit.getResourceOwnerType() == ResourceOwnerType.Account) { - Account accountTemp = ApiDBUtils.findAccountById(limit.getOwnerId()); - populateAccount(resourceLimitResponse, limit.getOwnerId()); - populateDomain(resourceLimitResponse, accountTemp.getDomainId()); - } - resourceLimitResponse.setResourceType(Integer.valueOf(limit.getType().getOrdinal()).toString()); - resourceLimitResponse.setMax(limit.getMax()); - resourceLimitResponse.setObjectName("resourcelimit"); - - return resourceLimitResponse; - } - - @Override - public ResourceCountResponse createResourceCountResponse(ResourceCount resourceCount) { - ResourceCountResponse resourceCountResponse = new ResourceCountResponse(); - - if (resourceCount.getResourceOwnerType() == ResourceOwnerType.Account) { - Account accountTemp = ApiDBUtils.findAccountById(resourceCount.getOwnerId()); - if (accountTemp != null) { - populateAccount(resourceCountResponse, accountTemp.getId()); - populateDomain(resourceCountResponse, accountTemp.getDomainId()); - } - } else if (resourceCount.getResourceOwnerType() == ResourceOwnerType.Domain) { - populateDomain(resourceCountResponse, resourceCount.getOwnerId()); - } - - resourceCountResponse.setResourceType(Integer.valueOf(resourceCount.getType().getOrdinal()).toString()); - resourceCountResponse.setResourceCount(resourceCount.getCount()); - resourceCountResponse.setObjectName("resourcecount"); - return resourceCountResponse; - } - - @Override - public ServiceOfferingResponse createServiceOfferingResponse(ServiceOffering offering) { - ServiceOfferingResponse offeringResponse = new ServiceOfferingResponse(); - offeringResponse.setId(offering.getId()); - offeringResponse.setName(offering.getName()); - offeringResponse.setIsSystemOffering(offering.getSystemUse()); - offeringResponse.setDefaultUse(offering.getDefaultUse()); - offeringResponse.setSystemVmType(offering.getSystemVmType()); - offeringResponse.setDisplayText(offering.getDisplayText()); - offeringResponse.setCpuNumber(offering.getCpu()); - offeringResponse.setCpuSpeed(offering.getSpeed()); - offeringResponse.setMemory(offering.getRamSize()); - offeringResponse.setCreated(offering.getCreated()); - offeringResponse.setStorageType(offering.getUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); - offeringResponse.setOfferHa(offering.getOfferHA()); - offeringResponse.setLimitCpuUse(offering.getLimitCpuUse()); - offeringResponse.setTags(offering.getTags()); - if (offering.getDomainId() != null) { - offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); - offeringResponse.setDomainId(offering.getDomainId()); - } - offeringResponse.setNetworkRate(offering.getRateMbps()); - offeringResponse.setHostTag(offering.getHostTag()); - offeringResponse.setObjectName("serviceoffering"); - - return offeringResponse; - } - - @Override - public ConfigurationResponse createConfigurationResponse(Configuration cfg) { - ConfigurationResponse cfgResponse = new ConfigurationResponse(); - cfgResponse.setCategory(cfg.getCategory()); - cfgResponse.setDescription(cfg.getDescription()); - cfgResponse.setName(cfg.getName()); - cfgResponse.setValue(cfg.getValue()); - cfgResponse.setObjectName("configuration"); - - return cfgResponse; - } - - @Override - public SnapshotResponse createSnapshotResponse(Snapshot snapshot) { - SnapshotResponse snapshotResponse = new SnapshotResponse(); - snapshotResponse.setId(snapshot.getId()); - - populateOwner(snapshotResponse, snapshot); - - VolumeVO volume = findVolumeById(snapshot.getVolumeId()); - String snapshotTypeStr = snapshot.getType().name(); - snapshotResponse.setSnapshotType(snapshotTypeStr); - snapshotResponse.setVolumeId(snapshot.getVolumeId()); - if (volume != null) { - snapshotResponse.setVolumeName(volume.getName()); - snapshotResponse.setVolumeType(volume.getVolumeType().name()); - } - snapshotResponse.setCreated(snapshot.getCreated()); - snapshotResponse.setName(snapshot.getName()); - snapshotResponse.setIntervalType(ApiDBUtils.getSnapshotIntervalTypes(snapshot.getId())); - snapshotResponse.setState(snapshot.getStatus()); - snapshotResponse.setObjectName("snapshot"); - return snapshotResponse; - } - - @Override - public SnapshotPolicyResponse createSnapshotPolicyResponse(SnapshotPolicy policy) { - SnapshotPolicyResponse policyResponse = new SnapshotPolicyResponse(); - policyResponse.setId(policy.getId()); - policyResponse.setVolumeId(policy.getVolumeId()); - policyResponse.setSchedule(policy.getSchedule()); - policyResponse.setIntervalType(policy.getInterval()); - policyResponse.setMaxSnaps(policy.getMaxSnaps()); - policyResponse.setTimezone(policy.getTimezone()); - policyResponse.setObjectName("snapshotpolicy"); - - return policyResponse; - } - - @Override - public HostResponse createHostResponse(Host host) { - return createHostResponse(host, EnumSet.of(HostDetails.all)); - } - - @Override - public HostResponse createHostResponse(Host host, EnumSet details) { - HostResponse hostResponse = new HostResponse(); - hostResponse.setId(host.getId()); - hostResponse.setCapabilities(host.getCapabilities()); - hostResponse.setClusterId(host.getClusterId()); - hostResponse.setCpuNumber(host.getCpus()); - hostResponse.setZoneId(host.getDataCenterId()); - hostResponse.setDisconnectedOn(host.getDisconnectedOn()); - hostResponse.setHypervisor(host.getHypervisorType()); - hostResponse.setHostType(host.getType()); - hostResponse.setLastPinged(new Date(host.getLastPinged())); - hostResponse.setManagementServerId(host.getManagementServerId()); - hostResponse.setName(host.getName()); - hostResponse.setPodId(host.getPodId()); - hostResponse.setRemoved(host.getRemoved()); - hostResponse.setCpuSpeed(host.getSpeed()); - hostResponse.setState(host.getStatus()); - hostResponse.setIpAddress(host.getPrivateIpAddress()); - hostResponse.setVersion(host.getVersion()); - hostResponse.setCreated(host.getCreated()); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) - || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { - - GuestOSCategoryVO guestOSCategory = ApiDBUtils.getHostGuestOSCategory(host.getId()); - if (guestOSCategory != null) { - hostResponse.setOsCategoryId(guestOSCategory.getId()); - hostResponse.setOsCategoryName(guestOSCategory.getName()); - } - hostResponse.setZoneName(ApiDBUtils.findZoneById(host.getDataCenterId()).getName()); - - if (host.getPodId() != null) { - HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); - if (pod != null) { - hostResponse.setPodName(pod.getName()); - } - } - - if (host.getClusterId() != null) { - ClusterVO cluster = ApiDBUtils.findClusterById(host.getClusterId()); - hostResponse.setClusterName(cluster.getName()); - hostResponse.setClusterType(cluster.getClusterType().toString()); - } - } - - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - if (host.getType() == Host.Type.Routing) { - - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { - // set allocated capacities - Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_MEMORY); - Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_CPU); - - hostResponse.setMemoryAllocated(mem); - hostResponse.setMemoryTotal(host.getTotalMemory()); - hostResponse.setHostTags(ApiDBUtils.getHostTags(host.getId())); - hostResponse.setHypervisorVersion(host.getHypervisorVersion()); - - String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; - hostResponse.setCpuAllocated(cpuAlloc); - String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); - hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); - } - - if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { - // set CPU/RAM/Network stats - String cpuUsed = null; - HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); - if (hostStats != null) { - float cpuUtil = (float) hostStats.getCpuUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - hostResponse.setCpuUsed(cpuUsed); - hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); - hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); - hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); - - } - } - - } else if (host.getType() == Host.Type.SecondaryStorage) { - StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); - if (secStorageStats != null) { - hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); - hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); - } - } - - hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host)); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { - Set possibleEvents = host.getStatus().getPossibleEvents(); - if ((possibleEvents != null) && !possibleEvents.isEmpty()) { - String events = ""; - Iterator iter = possibleEvents.iterator(); - while (iter.hasNext()) { - com.cloud.host.Status.Event event = iter.next(); - events += event.toString(); - if (iter.hasNext()) { - events += "; "; - } - } - hostResponse.setEvents(events); - } - } - - hostResponse.setResourceState(host.getResourceState().toString()); - - hostResponse.setObjectName("host"); - - return hostResponse; - } - - @Override - public SwiftResponse createSwiftResponse(Swift swift) { - SwiftResponse swiftResponse = new SwiftResponse(); - swiftResponse.setId(swift.getId()); - swiftResponse.setUrl(swift.getUrl()); - swiftResponse.setAccount(swift.getAccount()); - swiftResponse.setUsername(swift.getUserName()); - swiftResponse.setObjectName("swift"); - return swiftResponse; - } - - @Override - public VlanIpRangeResponse createVlanIpRangeResponse(Vlan vlan) { - Long podId = ApiDBUtils.getPodIdForVlan(vlan.getId()); - - VlanIpRangeResponse vlanResponse = new VlanIpRangeResponse(); - vlanResponse.setId(vlan.getId()); - vlanResponse.setForVirtualNetwork(vlan.getVlanType().equals(VlanType.VirtualNetwork)); - vlanResponse.setVlan(vlan.getVlanTag()); - vlanResponse.setZoneId(vlan.getDataCenterId()); - - if (podId != null) { - HostPodVO pod = ApiDBUtils.findPodById(podId); - vlanResponse.setPodId(podId); - if (pod != null) { - vlanResponse.setPodName(pod.getName()); - } - } - - vlanResponse.setGateway(vlan.getVlanGateway()); - vlanResponse.setNetmask(vlan.getVlanNetmask()); - - // get start ip and end ip of corresponding vlan - String ipRange = vlan.getIpRange(); - String[] range = ipRange.split("-"); - vlanResponse.setStartIp(range[0]); - vlanResponse.setEndIp(range[1]); - - vlanResponse.setNetworkId(vlan.getNetworkId()); - Account owner = ApiDBUtils.getVlanAccount(vlan.getId()); - if (owner != null) { - populateAccount(vlanResponse, owner.getId()); - populateDomain(vlanResponse, owner.getDomainId()); - } - - vlanResponse.setPhysicalNetworkId(vlan.getPhysicalNetworkId()); - - vlanResponse.setObjectName("vlan"); - return vlanResponse; - } - - @Override - public IPAddressResponse createIPAddressResponse(IpAddress ipAddress) { - VlanVO vlan = ApiDBUtils.findVlanById(ipAddress.getVlanId()); - boolean forVirtualNetworks = vlan.getVlanType().equals(VlanType.VirtualNetwork); - long zoneId = ipAddress.getDataCenterId(); - - IPAddressResponse ipResponse = new IPAddressResponse(); - ipResponse.setId(ipAddress.getId()); - ipResponse.setIpAddress(ipAddress.getAddress().toString()); - if (ipAddress.getAllocatedTime() != null) { - ipResponse.setAllocated(ipAddress.getAllocatedTime()); - } - ipResponse.setZoneId(zoneId); - ipResponse.setZoneName(ApiDBUtils.findZoneById(ipAddress.getDataCenterId()).getName()); - ipResponse.setSourceNat(ipAddress.isSourceNat()); - ipResponse.setIsSystem(ipAddress.getSystem()); - - // get account information - populateOwner(ipResponse, ipAddress); - - ipResponse.setForVirtualNetwork(forVirtualNetworks); - ipResponse.setStaticNat(ipAddress.isOneToOneNat()); - - if (ipAddress.getAssociatedWithVmId() != null) { - UserVm vm = ApiDBUtils.findUserVmById(ipAddress.getAssociatedWithVmId()); - ipResponse.setVirtualMachineId(vm.getId()); - ipResponse.setVirtualMachineName(vm.getHostName()); - if (vm.getDisplayName() != null) { - ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); - } else { - ipResponse.setVirtualMachineDisplayName(vm.getHostName()); - } - } - - ipResponse.setAssociatedNetworkId(ipAddress.getAssociatedWithNetworkId()); - - // Network id the ip is associated withif associated networkId is null, try to get this information from vlan - Long associatedNetworkId = ipAddress.getAssociatedWithNetworkId(); - Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddress.getVlanId()); - if (associatedNetworkId == null) { - associatedNetworkId = vlanNetworkId; - } - - ipResponse.setAssociatedNetworkId(associatedNetworkId); - - // Network id the ip belongs to - Long networkId; - if (vlanNetworkId != null) { - networkId = vlanNetworkId; - } else { - networkId = ApiDBUtils.getPublicNetworkIdByZone(zoneId); - } - - ipResponse.setNetworkId(networkId); - ipResponse.setState(ipAddress.getState().toString()); - ipResponse.setPhysicalNetworkId(ipAddress.getPhysicalNetworkId()); - - // show this info to admin only - Account account = UserContext.current().getCaller(); - if ((account == null) || account.getType() == Account.ACCOUNT_TYPE_ADMIN) { - ipResponse.setVlanId(ipAddress.getVlanId()); - ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddress.getVlanId()).getVlanTag()); - } - - if (ipAddress.getSystem()) { - if (ipAddress.isOneToOneNat()) { - ipResponse.setPurpose(IpAddress.Purpose.StaticNat.toString()); - } else { - ipResponse.setPurpose(IpAddress.Purpose.Lb.toString()); - } - } - - ipResponse.setObjectName("ipaddress"); - return ipResponse; - } - - @Override - public LoadBalancerResponse createLoadBalancerResponse(LoadBalancer loadBalancer) { - LoadBalancerResponse lbResponse = new LoadBalancerResponse(); - lbResponse.setId(loadBalancer.getId()); - lbResponse.setName(loadBalancer.getName()); - lbResponse.setDescription(loadBalancer.getDescription()); - List cidrs = ApiDBUtils.findFirewallSourceCidrs(loadBalancer.getId()); - lbResponse.setCidrList(StringUtils.join(cidrs, ",")); - - IPAddressVO publicIp = ApiDBUtils.findIpAddressById(loadBalancer.getSourceIpAddressId()); - lbResponse.setPublicIpId(publicIp.getId()); - lbResponse.setPublicIp(publicIp.getAddress().addr()); - lbResponse.setPublicPort(Integer.toString(loadBalancer.getSourcePortStart())); - lbResponse.setPrivatePort(Integer.toString(loadBalancer.getDefaultPortStart())); - lbResponse.setAlgorithm(loadBalancer.getAlgorithm()); - FirewallRule.State state = loadBalancer.getState(); - String stateToSet = state.toString(); - if (state.equals(FirewallRule.State.Revoke)) { - stateToSet = "Deleting"; - } - lbResponse.setState(stateToSet); - populateOwner(lbResponse, loadBalancer); - lbResponse.setZoneId(publicIp.getDataCenterId()); - - lbResponse.setObjectName("loadbalancer"); - return lbResponse; - } - - @Override - public PodResponse createPodResponse(Pod pod, Boolean showCapacities) { - String[] ipRange = new String[2]; - if (pod.getDescription() != null && pod.getDescription().length() > 0) { - ipRange = pod.getDescription().split("-"); - } else { - ipRange[0] = pod.getDescription(); - } - - PodResponse podResponse = new PodResponse(); - podResponse.setId(pod.getId()); - podResponse.setName(pod.getName()); - podResponse.setZoneId(pod.getDataCenterId()); - podResponse.setZoneName(PodZoneConfig.getZoneName(pod.getDataCenterId())); - podResponse.setNetmask(NetUtils.getCidrNetmask(pod.getCidrSize())); - podResponse.setStartIp(ipRange[0]); - podResponse.setEndIp(((ipRange.length > 1) && (ipRange[1] != null)) ? ipRange[1] : ""); - podResponse.setGateway(pod.getGateway()); - podResponse.setAllocationState(pod.getAllocationState().toString()); - if (showCapacities != null && showCapacities) { - List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, pod.getId(), null); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities) { - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { - capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); - } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId(), null); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - } else { - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, null, pod.getId(), pod.getDataCenterId())); - podResponse.setCapacitites(new ArrayList(capacityResponses)); - } - podResponse.setObjectName("pod"); - return podResponse; - } - - @Override - public ZoneResponse createZoneResponse(DataCenter dataCenter, Boolean showCapacities) { - Account account = UserContext.current().getCaller(); - ZoneResponse zoneResponse = new ZoneResponse(); - zoneResponse.setId(dataCenter.getId()); - zoneResponse.setName(dataCenter.getName()); - zoneResponse.setSecurityGroupsEnabled(ApiDBUtils.isSecurityGroupEnabledInZone(dataCenter.getId())); - - if ((dataCenter.getDescription() != null) && !dataCenter.getDescription().equalsIgnoreCase("null")) { - zoneResponse.setDescription(dataCenter.getDescription()); - } - - if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { - zoneResponse.setDns1(dataCenter.getDns1()); - zoneResponse.setDns2(dataCenter.getDns2()); - zoneResponse.setInternalDns1(dataCenter.getInternalDns1()); - zoneResponse.setInternalDns2(dataCenter.getInternalDns2()); - // FIXME zoneResponse.setVlan(dataCenter.get.getVnet()); - zoneResponse.setGuestCidrAddress(dataCenter.getGuestNetworkCidr()); - } - - if (showCapacities != null && showCapacities) { - List capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(), null, null); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities) { - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { - capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); - } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null, null); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - } else { - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, null, null, dataCenter.getId())); - - zoneResponse.setCapacitites(new ArrayList(capacityResponses)); - } - - // set network domain info - zoneResponse.setDomain(dataCenter.getDomain()); - - // set domain info - Long domainId = dataCenter.getDomainId(); - if (domainId != null) { - Domain domain = ApiDBUtils.findDomainById(domainId); - zoneResponse.setDomainId(domain.getId()); - zoneResponse.setDomainName(domain.getName()); - } - - zoneResponse.setType(dataCenter.getNetworkType().toString()); - zoneResponse.setAllocationState(dataCenter.getAllocationState().toString()); - zoneResponse.setZoneToken(dataCenter.getZoneToken()); - zoneResponse.setDhcpProvider(dataCenter.getDhcpProvider()); - zoneResponse.setObjectName("zone"); - return zoneResponse; - } - - private List getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId) { - List capacities = new ArrayList(); - capacities.add(ApiDBUtils.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId)); - if (clusterId == null && podId == null) { - capacities.add(ApiDBUtils.getSecondaryStorageUsedStats(poolId, zoneId)); - } - - List capacityResponses = new ArrayList(); - for (CapacityVO capacity : capacities) { - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - - return capacityResponses; - } - - @Override - public VolumeResponse createVolumeResponse(Volume volume) { - VolumeResponse volResponse = new VolumeResponse(); - volResponse.setId(volume.getId()); - - if (volume.getName() != null) { - volResponse.setName(volume.getName()); - } else { - volResponse.setName(""); - } - - volResponse.setZoneId(volume.getDataCenterId()); - volResponse.setZoneName(ApiDBUtils.findZoneById(volume.getDataCenterId()).getName()); - - volResponse.setVolumeType(volume.getVolumeType().toString()); - volResponse.setDeviceId(volume.getDeviceId()); - - Long instanceId = volume.getInstanceId(); - if (instanceId != null && volume.getState() != Volume.State.Destroy) { - VMInstanceVO vm = ApiDBUtils.findVMInstanceById(instanceId); - if (vm != null) { - volResponse.setVirtualMachineId(vm.getId()); - volResponse.setVirtualMachineName(vm.getHostName()); - UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); - if (userVm != null) { - if (userVm.getDisplayName() != null) { - volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); - } else { - volResponse.setVirtualMachineDisplayName(userVm.getHostName()); - } - volResponse.setVirtualMachineState(vm.getState().toString()); - } else { - s_logger.error("User Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); - } - } else { - s_logger.error("Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); - } - } - - // Show the virtual size of the volume - volResponse.setSize(volume.getSize()); - - volResponse.setCreated(volume.getCreated()); - volResponse.setState(volume.getState().toString()); - - populateOwner(volResponse, volume); - - String storageType; - try { - if (volume.getPoolId() == null) { - if (volume.getState() == Volume.State.Allocated) { - /* set it as shared, so the UI can attach it to VM */ - storageType = "shared"; - } else { - storageType = "unknown"; - } - } else { - storageType = ApiDBUtils.volumeIsOnSharedStorage(volume.getId()) ? ServiceOffering.StorageType.shared.toString() : ServiceOffering.StorageType.local.toString(); - } - } catch (InvalidParameterValueException e) { - s_logger.error(e.getMessage(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Volume " + volume.getName() + " does not have a valid ID"); - } - - volResponse.setStorageType(storageType); - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - volResponse.setServiceOfferingId(volume.getDiskOfferingId()); - } else { - volResponse.setDiskOfferingId(volume.getDiskOfferingId()); - } - - DiskOfferingVO diskOffering = ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId()); - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - volResponse.setServiceOfferingName(diskOffering.getName()); - volResponse.setServiceOfferingDisplayText(diskOffering.getDisplayText()); - } else { - volResponse.setDiskOfferingName(diskOffering.getName()); - volResponse.setDiskOfferingDisplayText(diskOffering.getDisplayText()); - } - - Long poolId = volume.getPoolId(); - String poolName = (poolId == null) ? "none" : ApiDBUtils.findStoragePoolById(poolId).getName(); - volResponse.setStoragePoolName(poolName); - // volResponse.setSourceId(volume.getSourceId()); - // if (volume.getSourceType() != null) { - // volResponse.setSourceType(volume.getSourceType().toString()); - // } - - // return hypervisor for ROOT and Resource domain only - Account caller = UserContext.current().getCaller(); - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString()); - } - - volResponse.setAttached(volume.getAttached()); - volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - boolean isExtractable = template != null && template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM); - volResponse.setExtractable(isExtractable); - volResponse.setObjectName("volume"); - return volResponse; - } - - @Override - public InstanceGroupResponse createInstanceGroupResponse(InstanceGroup group) { - InstanceGroupResponse groupResponse = new InstanceGroupResponse(); - groupResponse.setId(group.getId()); - groupResponse.setName(group.getName()); - groupResponse.setCreated(group.getCreated()); - - populateOwner(groupResponse, group); - - groupResponse.setObjectName("instancegroup"); - return groupResponse; - } - - @Override - public StoragePoolResponse createStoragePoolResponse(StoragePool pool) { - StoragePoolResponse poolResponse = new StoragePoolResponse(); - poolResponse.setId(pool.getId()); - poolResponse.setName(pool.getName()); - poolResponse.setState(pool.getStatus()); - poolResponse.setPath(pool.getPath()); - poolResponse.setIpAddress(pool.getHostAddress()); - poolResponse.setZoneId(pool.getDataCenterId()); - poolResponse.setZoneName(ApiDBUtils.findZoneById(pool.getDataCenterId()).getName()); - if (pool.getPoolType() != null) { - poolResponse.setType(pool.getPoolType().toString()); - } - if (pool.getPodId() != null) { - poolResponse.setPodId(pool.getPodId()); - HostPodVO pod = ApiDBUtils.findPodById(pool.getPodId()); - if (pod != null) { - poolResponse.setPodName(pod.getName()); - } - } - if (pool.getCreated() != null) { - poolResponse.setCreated(pool.getCreated()); - } - - StorageStats stats = ApiDBUtils.getStoragePoolStatistics(pool.getId()); - long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(), Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); - poolResponse.setDiskSizeTotal(pool.getCapacityBytes()); - poolResponse.setDiskSizeAllocated(allocatedSize); - - if (stats != null) { - Long used = stats.getByteUsed(); - poolResponse.setDiskSizeUsed(used); - } - - if (pool.getClusterId() != null) { - ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); - poolResponse.setClusterId(cluster.getId()); - poolResponse.setClusterName(cluster.getName()); - } - poolResponse.setTags(ApiDBUtils.getStoragePoolTags(pool.getId())); - poolResponse.setObjectName("storagepool"); - return poolResponse; - } - - @Override - public ClusterResponse createClusterResponse(Cluster cluster, Boolean showCapacities) { - ClusterResponse clusterResponse = new ClusterResponse(); - clusterResponse.setId(cluster.getId()); - clusterResponse.setName(cluster.getName()); - clusterResponse.setPodId(cluster.getPodId()); - clusterResponse.setZoneId(cluster.getDataCenterId()); - clusterResponse.setHypervisorType(cluster.getHypervisorType().toString()); - clusterResponse.setClusterType(cluster.getClusterType().toString()); - clusterResponse.setAllocationState(cluster.getAllocationState().toString()); - clusterResponse.setManagedState(cluster.getManagedState().toString()); - HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); - if (pod != null) { - clusterResponse.setPodName(pod.getName()); - } - DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); - clusterResponse.setZoneName(zone.getName()); - if (showCapacities != null && showCapacities) { - List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, null, cluster.getId()); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities) { - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { - capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); - } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, null, cluster.getId()); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - } else { - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, cluster.getId(), pod.getId(), pod.getDataCenterId())); - clusterResponse.setCapacitites(new ArrayList(capacityResponses)); - } - clusterResponse.setObjectName("cluster"); - return clusterResponse; - } - - @Override - public FirewallRuleResponse createPortForwardingRuleResponse(PortForwardingRule fwRule) { - FirewallRuleResponse response = new FirewallRuleResponse(); - response.setId(fwRule.getId()); - response.setPrivateStartPort(Integer.toString(fwRule.getDestinationPortStart())); - response.setPrivateEndPort(Integer.toString(fwRule.getDestinationPortEnd())); - response.setProtocol(fwRule.getProtocol()); - response.setPublicStartPort(Integer.toString(fwRule.getSourcePortStart())); - response.setPublicEndPort(Integer.toString(fwRule.getSourcePortEnd())); - List cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId()); - response.setCidrList(StringUtils.join(cidrs, ",")); - - IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); - response.setPublicIpAddressId(ip.getId()); - response.setPublicIpAddress(ip.getAddress().addr()); - - if (ip != null && fwRule.getDestinationIpAddress() != null) { - UserVm vm = ApiDBUtils.findUserVmById(fwRule.getVirtualMachineId()); - if (vm != null) { - response.setVirtualMachineId(vm.getId()); - response.setVirtualMachineName(vm.getHostName()); - - if (vm.getDisplayName() != null) { - response.setVirtualMachineDisplayName(vm.getDisplayName()); - } else { - response.setVirtualMachineDisplayName(vm.getHostName()); - } - } - } - FirewallRule.State state = fwRule.getState(); - String stateToSet = state.toString(); - if (state.equals(FirewallRule.State.Revoke)) { - stateToSet = "Deleting"; - } - response.setState(stateToSet); - response.setObjectName("portforwardingrule"); - return response; - } - - @Override - public IpForwardingRuleResponse createIpForwardingRuleResponse(StaticNatRule fwRule) { - IpForwardingRuleResponse response = new IpForwardingRuleResponse(); - response.setId(fwRule.getId()); - response.setProtocol(fwRule.getProtocol()); - - IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); - response.setPublicIpAddressId(ip.getId()); - response.setPublicIpAddress(ip.getAddress().addr()); - - if (ip != null && fwRule.getDestIpAddress() != null) { - UserVm vm = ApiDBUtils.findUserVmById(ip.getAssociatedWithVmId()); - if (vm != null) {// vm might be destroyed - response.setVirtualMachineId(vm.getId()); - response.setVirtualMachineName(vm.getHostName()); - if (vm.getDisplayName() != null) { - response.setVirtualMachineDisplayName(vm.getDisplayName()); - } else { - response.setVirtualMachineDisplayName(vm.getHostName()); - } - } - } - FirewallRule.State state = fwRule.getState(); - String stateToSet = state.toString(); - if (state.equals(FirewallRule.State.Revoke)) { - stateToSet = "Deleting"; - } - - response.setStartPort(fwRule.getSourcePortStart()); - response.setEndPort(fwRule.getSourcePortEnd()); - response.setProtocol(fwRule.getProtocol()); - response.setState(stateToSet); - response.setObjectName("ipforwardingrule"); - return response; - } - - @Override - public List createUserVmResponse(String objectName, EnumSet details, UserVm... userVms) { - Account caller = UserContext.current().getCaller(); - Map dataCenters = new HashMap(); - Map hosts = new HashMap(); - Map templates = new HashMap(); - Map serviceOfferings = new HashMap(); - Map networks = new HashMap(); - - List vmResponses = new ArrayList(); - - for (UserVm userVm : userVms) { - UserVmResponse userVmResponse = new UserVmResponse(); - Account acct = ApiDBUtils.findAccountById(Long.valueOf(userVm.getAccountId())); - if (acct != null) { - userVmResponse.setAccountName(acct.getAccountName()); - userVmResponse.setDomainId(acct.getDomainId()); - userVmResponse.setDomainName(ApiDBUtils.findDomainById(acct.getDomainId()).getName()); - } - - userVmResponse.setId(userVm.getId()); - userVmResponse.setName(userVm.getHostName()); - userVmResponse.setCreated(userVm.getCreated()); - - userVmResponse.setHaEnable(userVm.isHaEnabled()); - - if (userVm.getDisplayName() != null) { - userVmResponse.setDisplayName(userVm.getDisplayName()); - } else { - userVmResponse.setDisplayName(userVm.getHostName()); - } - - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - userVmResponse.setInstanceName(userVm.getInstanceName()); - } - - - if (userVm.getPassword() != null) { - userVmResponse.setPassword(userVm.getPassword()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { - InstanceGroupVO group = ApiDBUtils.findInstanceGroupForVM(userVm.getId()); - if (group != null) { - userVmResponse.setGroup(group.getName()); - userVmResponse.setGroupId(group.getId()); - } - - } - - // Data Center Info - DataCenter zone = dataCenters.get(userVm.getDataCenterIdToDeployIn()); - if (zone == null) { - zone = ApiDBUtils.findZoneById(userVm.getDataCenterIdToDeployIn()); - dataCenters.put(zone.getId(), zone); - } - - userVmResponse.setZoneId(zone.getId()); - userVmResponse.setZoneName(zone.getName()); - - // if user is an admin, display host id - if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { - Host host = hosts.get(userVm.getHostId()); - - if (host == null) { - host = ApiDBUtils.findHostById(userVm.getHostId()); - hosts.put(host.getId(), host); - } - - userVmResponse.setHostId(host.getId()); - userVmResponse.setHostName(host.getName()); - } - - if (userVm.getState() != null) { - if (userVm.getHostId() != null) { - Host host = hosts.get(userVm.getHostId()); - - if (host == null) { - host = ApiDBUtils.findHostById(userVm.getHostId()); - hosts.put(host.getId(), host); - } - if (host.getStatus() != com.cloud.host.Status.Up) { - userVmResponse.setState(VirtualMachine.State.Unknown.toString()); - } else { - userVmResponse.setState(userVm.getState().toString()); - } - } else { - userVmResponse.setState(userVm.getState().toString()); - } - } - - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - if (userVm.getHypervisorType() != null) { - userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { - // Template Info - VMTemplateVO template = templates.get(userVm.getTemplateId()); - if (template == null) { - template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); - if (template != null) { - templates.put(template.getId(), template); - } - } - - if (template != null) { - userVmResponse.setTemplateId(userVm.getTemplateId()); - userVmResponse.setTemplateName(template.getName()); - userVmResponse.setTemplateDisplayText(template.getDisplayText()); - userVmResponse.setPasswordEnabled(template.getEnablePassword()); - } else { - userVmResponse.setTemplateId(-1L); - userVmResponse.setTemplateName("ISO Boot"); - userVmResponse.setTemplateDisplayText("ISO Boot"); - userVmResponse.setPasswordEnabled(false); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { - // ISO Info - VMTemplateVO iso = templates.get(userVm.getIsoId()); - if (iso == null) { - iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); - if (iso != null) { - templates.put(iso.getId(), iso); - } - } - - if (iso != null) { - userVmResponse.setIsoId(iso.getId()); - userVmResponse.setIsoName(iso.getName()); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - - userVmResponse.setServiceOfferingId(offering.getId()); - userVmResponse.setServiceOfferingName(offering.getName()); - userVmResponse.setCpuNumber(offering.getCpu()); - userVmResponse.setCpuSpeed(offering.getSpeed()); - userVmResponse.setMemory(offering.getRamSize()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { - VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId()); - if (rootVolume != null) { - userVmResponse.setRootDeviceId(rootVolume.getDeviceId()); - String rootDeviceType = "Not created"; - if (rootVolume.getPoolId() != null) { - StoragePoolVO storagePool = ApiDBUtils.findStoragePoolById(rootVolume.getPoolId()); - rootDeviceType = storagePool.getPoolType().toString(); - } - userVmResponse.setRootDeviceType(rootDeviceType); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { - // stats calculation - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - String cpuUsed = null; - VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } - } - - userVmResponse.setGuestOsId(userVm.getGuestOSId()); - - if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { - // security groups - list only when zone is security group enabled - if (zone.isSecurityGroupEnabled()) { - List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); - List securityGroupResponse = new ArrayList(); - for (SecurityGroupVO grp : securityGroups) { - SecurityGroupResponse resp = new SecurityGroupResponse(); - resp.setId(grp.getId()); - resp.setName(grp.getName()); - resp.setDescription(grp.getDescription()); - resp.setObjectName("securitygroup"); - securityGroupResponse.add(resp); - } - userVmResponse.setSecurityGroupList(securityGroupResponse); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { - List nicProfiles = ApiDBUtils.getNics(userVm); - List nicResponses = new ArrayList(); - for (NicProfile singleNicProfile : nicProfiles) { - NicResponse nicResponse = new NicResponse(); - nicResponse.setId(singleNicProfile.getId()); - nicResponse.setIpaddress(singleNicProfile.getIp4Address()); - nicResponse.setGateway(singleNicProfile.getGateway()); - nicResponse.setNetmask(singleNicProfile.getNetmask()); - nicResponse.setNetworkid(singleNicProfile.getNetworkId()); - if (acct.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (singleNicProfile.getBroadCastUri() != null) { - nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); - } - if (singleNicProfile.getIsolationUri() != null) { - nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); - } - } - - // Long networkId = singleNicProfile.getNetworkId(); - Network network = networks.get(singleNicProfile.getNetworkId()); - if (network == null) { - network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - networks.put(singleNicProfile.getNetworkId(), network); - } - - nicResponse.setTrafficType(network.getTrafficType().toString()); - nicResponse.setType(network.getGuestType().toString()); - nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); - nicResponse.setObjectName("nic"); - nicResponses.add(nicResponse); - } - userVmResponse.setNics(nicResponses); - } - - IpAddress ip = ApiDBUtils.findIpByAssociatedVmId(userVm.getId()); - if (ip != null) { - userVmResponse.setPublicIpId(ip.getId()); - userVmResponse.setPublicIp(ip.getAddress().addr()); - } - - userVmResponse.setObjectName(objectName); - vmResponses.add(userVmResponse); - } - - return vmResponses; - } - - @Override - public List createUserVmResponse(String objectName, UserVm... userVms) { - Account caller = UserContext.current().getCaller(); - boolean caller_is_admin = ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)); - - Hashtable vmDataList = new Hashtable(); - // Initialise the vmdatalist with the input data - for (UserVm userVm : userVms) { - UserVmData userVmData = newUserVmData(userVm); - vmDataList.put(userVm.getId(), userVmData); - } - - vmDataList = ApiDBUtils.listVmDetails(vmDataList); - - // initialize vmresponse from vmdatalist - List vmResponses = new ArrayList(); - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - for (UserVmData uvd : vmDataList.values()) { - UserVmResponse userVmResponse = newUserVmResponse(uvd, caller_is_admin); - - // stats calculation - String cpuUsed = null; - // VmStats vmStats = ApiDBUtils.getVmStatistics(userVmResponse.getId()); - VmStats vmStats = ApiDBUtils.getVmStatistics(uvd.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } - userVmResponse.setObjectName(objectName); - - vmResponses.add(userVmResponse); - } - return vmResponses; - } - - @Override - public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) { - Account caller = UserContext.current().getCaller(); - Map serviceOfferings = new HashMap(); - - DomainRouterResponse routerResponse = new DomainRouterResponse(); - routerResponse.setId(router.getId()); - routerResponse.setZoneId(router.getDataCenterIdToDeployIn()); - routerResponse.setName(router.getHostName()); - routerResponse.setTemplateId(router.getTemplateId()); - routerResponse.setCreated(router.getCreated()); - routerResponse.setState(router.getState()); - routerResponse.setIsRedundantRouter(router.getIsRedundantRouter()); - routerResponse.setRedundantState(router.getRedundantState().toString()); - - if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (router.getHostId() != null) { - routerResponse.setHostId(router.getHostId()); - routerResponse.setHostName(ApiDBUtils.findHostById(router.getHostId()).getName()); - } - routerResponse.setPodId(router.getPodIdToDeployIn()); - List nicProfiles = ApiDBUtils.getNics(router); - for (NicProfile singleNicProfile : nicProfiles) { - Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - if (network != null) { - if (network.getTrafficType() == TrafficType.Public) { - routerResponse.setPublicIp(singleNicProfile.getIp4Address()); - routerResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setPublicNetmask(singleNicProfile.getNetmask()); - routerResponse.setGateway(singleNicProfile.getGateway()); - routerResponse.setPublicNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Control) { - routerResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); - routerResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); - routerResponse.setLinkLocalNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Guest) { - routerResponse.setGuestIpAddress(singleNicProfile.getIp4Address()); - routerResponse.setGuestMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setGuestNetmask(singleNicProfile.getNetmask()); - routerResponse.setGuestNetworkId(singleNicProfile.getNetworkId()); - routerResponse.setNetworkDomain(network.getNetworkDomain()); - } - } - } - } - - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(router.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(router.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - routerResponse.setServiceOfferingId(offering.getId()); - routerResponse.setServiceOfferingName(offering.getName()); - - populateOwner(routerResponse, router); - - DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn()); - if (zone != null) { - routerResponse.setZoneName(zone.getName()); - routerResponse.setDns1(zone.getDns1()); - routerResponse.setDns2(zone.getDns2()); - } - - routerResponse.setObjectName("domainrouter"); - return routerResponse; - } - - @Override - public SystemVmResponse createSystemVmResponse(VirtualMachine vm) { - SystemVmResponse vmResponse = new SystemVmResponse(); - if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy) { - // SystemVm vm = (SystemVm) systemVM; - vmResponse.setId(vm.getId()); - vmResponse.setObjectId(vm.getId()); - vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); - vmResponse.setZoneId(vm.getDataCenterIdToDeployIn()); - - vmResponse.setName(vm.getHostName()); - vmResponse.setPodId(vm.getPodIdToDeployIn()); - vmResponse.setTemplateId(vm.getTemplateId()); - vmResponse.setCreated(vm.getCreated()); - - if (vm.getHostId() != null) { - vmResponse.setHostId(vm.getHostId()); - vmResponse.setHostName(ApiDBUtils.findHostById(vm.getHostId()).getName()); - } - - if (vm.getState() != null) { - vmResponse.setState(vm.getState().toString()); - } - - // for console proxies, add the active sessions - if (vm.getType() == Type.ConsoleProxy) { - ConsoleProxyVO proxy = ApiDBUtils.findConsoleProxy(vm.getId()); - // proxy can be already destroyed - if (proxy != null) { - vmResponse.setActiveViewerSessions(proxy.getActiveSession()); - } - } - - DataCenter zone = ApiDBUtils.findZoneById(vm.getDataCenterIdToDeployIn()); - if (zone != null) { - vmResponse.setZoneName(zone.getName()); - vmResponse.setDns1(zone.getDns1()); - vmResponse.setDns2(zone.getDns2()); - } - - List nicProfiles = ApiDBUtils.getNics(vm); - for (NicProfile singleNicProfile : nicProfiles) { - Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - if (network != null) { - if (network.getTrafficType() == TrafficType.Management) { - vmResponse.setPrivateIp(singleNicProfile.getIp4Address()); - vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress()); - vmResponse.setPrivateNetmask(singleNicProfile.getNetmask()); - } else if (network.getTrafficType() == TrafficType.Control) { - vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); - vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); +package com.cloud.api; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import org.apache.log4j.Logger; + +import com.cloud.acl.ControlledEntity; +import com.cloud.acl.ControlledEntity.ACLType; +import com.cloud.api.ApiConstants.HostDetails; +import com.cloud.api.ApiConstants.VMDetails; +import com.cloud.api.commands.QueryAsyncJobResultCmd; +import com.cloud.api.response.AccountResponse; +import com.cloud.api.response.ApiResponseSerializer; +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.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.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.ProjectAccountResponse; +import com.cloud.api.response.ProjectInvitationResponse; +import com.cloud.api.response.ProjectResponse; +import com.cloud.api.response.ProviderResponse; +import com.cloud.api.response.RemoteAccessVpnResponse; +import com.cloud.api.response.ResourceCountResponse; +import com.cloud.api.response.ResourceLimitResponse; +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.SnapshotPolicyResponse; +import com.cloud.api.response.SnapshotResponse; +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.VpnUsersResponse; +import com.cloud.api.response.ZoneResponse; +import com.cloud.async.AsyncJob; +import com.cloud.capacity.Capacity; +import com.cloud.capacity.CapacityVO; +import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; +import com.cloud.configuration.Configuration; +import com.cloud.configuration.Resource.ResourceOwnerType; +import com.cloud.configuration.Resource.ResourceType; +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.Vlan.VlanType; +import com.cloud.dc.VlanVO; +import com.cloud.domain.Domain; +import com.cloud.event.Event; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.host.Host; +import com.cloud.host.HostStats; +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.Network.Capability; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.NetworkProfile; +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.RemoteAccessVpn; +import com.cloud.network.VirtualRouterProvider; +import com.cloud.network.VpnUser; +import com.cloud.network.router.VirtualRouter; +import com.cloud.network.rules.FirewallRule; +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.security.SecurityGroup; +import com.cloud.network.security.SecurityGroupRules; +import com.cloud.network.security.SecurityGroupVO; +import com.cloud.network.security.SecurityRule; +import com.cloud.network.security.SecurityRule.SecurityRuleType; +import com.cloud.offering.DiskOffering; +import com.cloud.offering.NetworkOffering; +import com.cloud.offering.ServiceOffering; +import com.cloud.org.Cluster; +import com.cloud.projects.Project; +import com.cloud.projects.ProjectAccount; +import com.cloud.projects.ProjectInvitation; +import com.cloud.server.Criteria; +import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.GuestOS; +import com.cloud.storage.GuestOSCategoryVO; +import com.cloud.storage.Snapshot; +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.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.template.VirtualMachineTemplate; +import com.cloud.test.PodZoneConfig; +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.user.UserAccount; +import com.cloud.user.UserContext; +import com.cloud.user.UserStatisticsVO; +import com.cloud.user.UserVO; +import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; +import com.cloud.utils.StringUtils; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.ConsoleProxyVO; +import com.cloud.vm.InstanceGroup; +import com.cloud.vm.InstanceGroupVO; +import com.cloud.vm.NicProfile; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.State; +import com.cloud.vm.VirtualMachine.Type; +import com.cloud.vm.VmStats; +import com.cloud.vm.dao.UserVmData; +import com.cloud.vm.dao.UserVmData.NicData; +import com.cloud.vm.dao.UserVmData.SecurityGroupData; + +public class ApiResponseHelper implements ResponseGenerator { + + public final Logger s_logger = Logger.getLogger(ApiResponseHelper.class); + private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##"); + + @Override + public UserResponse createUserResponse(User user) { + UserResponse userResponse = new UserResponse(); + Account account = ApiDBUtils.findAccountById(user.getAccountId()); + userResponse.setAccountName(account.getAccountName()); + userResponse.setAccountType(account.getType()); + userResponse.setCreated(user.getCreated()); + userResponse.setDomainId(account.getDomainId()); + userResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); + userResponse.setEmail(user.getEmail()); + userResponse.setFirstname(user.getFirstname()); + userResponse.setId(user.getId()); + userResponse.setLastname(user.getLastname()); + userResponse.setState(user.getState().toString()); + userResponse.setTimezone(user.getTimezone()); + userResponse.setUsername(user.getUsername()); + userResponse.setApiKey(user.getApiKey()); + userResponse.setSecretKey(user.getSecretKey()); + userResponse.setObjectName("user"); + + return userResponse; + } + + // this method is used for response generation via createAccount (which creates an account + user) + @Override + public AccountResponse createUserAccountResponse(UserAccount user) { + return createAccountResponse(ApiDBUtils.findAccountById(user.getAccountId())); + } + + @Override + public AccountResponse createAccountResponse(Account account) { + boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); + AccountResponse accountResponse = new AccountResponse(); + accountResponse.setId(account.getId()); + accountResponse.setName(account.getAccountName()); + accountResponse.setAccountType(account.getType()); + accountResponse.setDomainId(account.getDomainId()); + accountResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); + accountResponse.setState(account.getState().toString()); + accountResponse.setNetworkDomain(account.getNetworkDomain()); + + // get network stat + List stats = ApiDBUtils.listUserStatsBy(account.getId()); + if (stats == null) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats"); + } + + Long bytesSent = 0L; + Long bytesReceived = 0L; + for (UserStatisticsVO stat : stats) { + Long rx = stat.getNetBytesReceived() + stat.getCurrentBytesReceived(); + Long tx = stat.getNetBytesSent() + stat.getCurrentBytesSent(); + bytesReceived = bytesReceived + Long.valueOf(rx); + bytesSent = bytesSent + Long.valueOf(tx); + } + accountResponse.setBytesReceived(bytesReceived); + accountResponse.setBytesSent(bytesSent); + + // Get resource limits and counts + + Long vmLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.user_vm, account.getId()); + String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); + Long vmTotal = ApiDBUtils.getResourceCount(ResourceType.user_vm, account.getId()); + String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); + accountResponse.setVmLimit(vmLimitDisplay); + accountResponse.setVmTotal(vmTotal); + accountResponse.setVmAvailable(vmAvail); + + Long ipLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.public_ip, account.getId()); + String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); + Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId()); + + Long ips = ipLimit - ipTotal; + // check how many free ips are left, and if it's less than max allowed number of ips from account - use this + // value + Long ipsLeft = ApiDBUtils.countFreePublicIps(); + boolean unlimited = true; + if (ips.longValue() > ipsLeft.longValue()) { + ips = ipsLeft; + unlimited = false; + } + + String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); + + accountResponse.setIpLimit(ipLimitDisplay); + accountResponse.setIpTotal(ipTotal); + accountResponse.setIpAvailable(ipAvail); + + Long volumeLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.volume, account.getId()); + String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); + Long volumeTotal = ApiDBUtils.getResourceCount(ResourceType.volume, account.getId()); + String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); + accountResponse.setVolumeLimit(volumeLimitDisplay); + accountResponse.setVolumeTotal(volumeTotal); + accountResponse.setVolumeAvailable(volumeAvail); + + Long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.snapshot, account.getId()); + String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); + Long snapshotTotal = ApiDBUtils.getResourceCount(ResourceType.snapshot, account.getId()); + String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); + accountResponse.setSnapshotLimit(snapshotLimitDisplay); + accountResponse.setSnapshotTotal(snapshotTotal); + accountResponse.setSnapshotAvailable(snapshotAvail); + + Long templateLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.template, account.getId()); + String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); + Long templateTotal = ApiDBUtils.getResourceCount(ResourceType.template, account.getId()); + String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); + accountResponse.setTemplateLimit(templateLimitDisplay); + accountResponse.setTemplateTotal(templateTotal); + accountResponse.setTemplateAvailable(templateAvail); + + // Get stopped and running VMs + int vmStopped = 0; + int vmRunning = 0; + + List permittedAccounts = new ArrayList(); + permittedAccounts.add(account.getId()); + + List virtualMachines = ApiDBUtils.searchForUserVMs(new Criteria(), permittedAccounts); + + // get Running/Stopped VMs + for (Iterator iter = virtualMachines.iterator(); iter.hasNext();) { + // count how many stopped/running vms we have + UserVm vm = iter.next(); + + if (vm.getState() == State.Stopped) { + vmStopped++; + } else if (vm.getState() == State.Running) { + vmRunning++; + } + } + + accountResponse.setVmStopped(vmStopped); + accountResponse.setVmRunning(vmRunning); + accountResponse.setObjectName("account"); + + //get resource limits for projects + Long projectLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.project, account.getId()); + String projectLimitDisplay = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit); + Long projectTotal = ApiDBUtils.getResourceCount(ResourceType.project, account.getId()); + String projectAvail = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal); + accountResponse.setProjectLimit(projectLimitDisplay); + accountResponse.setProjectTotal(projectTotal); + accountResponse.setProjectAvailable(projectAvail); + + //get resource limits for networks + Long networkLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.network, account.getId()); + String networkLimitDisplay = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit); + Long networkTotal = ApiDBUtils.getResourceCount(ResourceType.network, account.getId()); + String networkAvail = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit - networkTotal); + accountResponse.setNetworkLimit(networkLimitDisplay); + accountResponse.setNetworkTotal(networkTotal); + accountResponse.setNetworkAvailable(networkAvail); + + // adding all the users for an account as part of the response obj + List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); + List userResponseList = new ArrayList(); + for (UserVO user : usersForAccount) { + UserResponse userResponse = createUserResponse(user); + userResponseList.add(userResponse); + } + + accountResponse.setUsers(userResponseList); + accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); + return accountResponse; + } + + @Override + public UserResponse createUserResponse(UserAccount user) { + UserResponse userResponse = new UserResponse(); + userResponse.setAccountName(user.getAccountName()); + userResponse.setAccountType(user.getType()); + userResponse.setCreated(user.getCreated()); + userResponse.setDomainId(user.getDomainId()); + userResponse.setDomainName(ApiDBUtils.findDomainById(user.getDomainId()).getName()); + userResponse.setEmail(user.getEmail()); + userResponse.setFirstname(user.getFirstname()); + userResponse.setId(user.getId()); + userResponse.setLastname(user.getLastname()); + userResponse.setState(user.getState()); + userResponse.setTimezone(user.getTimezone()); + userResponse.setUsername(user.getUsername()); + userResponse.setApiKey(user.getApiKey()); + userResponse.setSecretKey(user.getSecretKey()); + userResponse.setAccountId((user.getAccountId())); + userResponse.setObjectName("user"); + + return userResponse; + } + + @Override + public DomainResponse createDomainResponse(Domain domain) { + DomainResponse domainResponse = new DomainResponse(); + domainResponse.setDomainName(domain.getName()); + domainResponse.setId(domain.getId()); + domainResponse.setLevel(domain.getLevel()); + domainResponse.setNetworkDomain(domain.getNetworkDomain()); + domainResponse.setParentDomainId(domain.getParent()); + StringBuilder domainPath = new StringBuilder("ROOT"); + (domainPath.append(domain.getPath())).deleteCharAt(domainPath.length() - 1); + domainResponse.setPath(domainPath.toString()); + if (domain.getParent() != null) { + domainResponse.setParentDomainName(ApiDBUtils.findDomainById(domain.getParent()).getName()); + } + if (domain.getChildCount() > 0) { + domainResponse.setHasChild(true); + } + domainResponse.setObjectName("domain"); + return domainResponse; + } + + @Override + public DiskOfferingResponse createDiskOfferingResponse(DiskOffering offering) { + DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); + diskOfferingResponse.setId(offering.getId()); + diskOfferingResponse.setName(offering.getName()); + diskOfferingResponse.setDisplayText(offering.getDisplayText()); + diskOfferingResponse.setCreated(offering.getCreated()); + diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); + if (offering.getDomainId() != null) { + diskOfferingResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); + diskOfferingResponse.setDomainId(offering.getDomainId()); + } + diskOfferingResponse.setTags(offering.getTags()); + diskOfferingResponse.setCustomized(offering.isCustomized()); + diskOfferingResponse.setObjectName("diskoffering"); + return diskOfferingResponse; + } + + @Override + public ResourceLimitResponse createResourceLimitResponse(ResourceLimit limit) { + ResourceLimitResponse resourceLimitResponse = new ResourceLimitResponse(); + if (limit.getResourceOwnerType() == ResourceOwnerType.Domain) { + populateDomain(resourceLimitResponse, limit.getOwnerId()); + } else if (limit.getResourceOwnerType() == ResourceOwnerType.Account) { + Account accountTemp = ApiDBUtils.findAccountById(limit.getOwnerId()); + populateAccount(resourceLimitResponse, limit.getOwnerId()); + populateDomain(resourceLimitResponse, accountTemp.getDomainId()); + } + resourceLimitResponse.setResourceType(Integer.valueOf(limit.getType().getOrdinal()).toString()); + resourceLimitResponse.setMax(limit.getMax()); + resourceLimitResponse.setObjectName("resourcelimit"); + + return resourceLimitResponse; + } + + @Override + public ResourceCountResponse createResourceCountResponse(ResourceCount resourceCount) { + ResourceCountResponse resourceCountResponse = new ResourceCountResponse(); + + if (resourceCount.getResourceOwnerType() == ResourceOwnerType.Account) { + Account accountTemp = ApiDBUtils.findAccountById(resourceCount.getOwnerId()); + if (accountTemp != null) { + populateAccount(resourceCountResponse, accountTemp.getId()); + populateDomain(resourceCountResponse, accountTemp.getDomainId()); + } + } else if (resourceCount.getResourceOwnerType() == ResourceOwnerType.Domain) { + populateDomain(resourceCountResponse, resourceCount.getOwnerId()); + } + + resourceCountResponse.setResourceType(Integer.valueOf(resourceCount.getType().getOrdinal()).toString()); + resourceCountResponse.setResourceCount(resourceCount.getCount()); + resourceCountResponse.setObjectName("resourcecount"); + return resourceCountResponse; + } + + @Override + public ServiceOfferingResponse createServiceOfferingResponse(ServiceOffering offering) { + ServiceOfferingResponse offeringResponse = new ServiceOfferingResponse(); + offeringResponse.setId(offering.getId()); + offeringResponse.setName(offering.getName()); + offeringResponse.setIsSystemOffering(offering.getSystemUse()); + offeringResponse.setDefaultUse(offering.getDefaultUse()); + offeringResponse.setSystemVmType(offering.getSystemVmType()); + offeringResponse.setDisplayText(offering.getDisplayText()); + offeringResponse.setCpuNumber(offering.getCpu()); + offeringResponse.setCpuSpeed(offering.getSpeed()); + offeringResponse.setMemory(offering.getRamSize()); + offeringResponse.setCreated(offering.getCreated()); + offeringResponse.setStorageType(offering.getUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); + offeringResponse.setOfferHa(offering.getOfferHA()); + offeringResponse.setLimitCpuUse(offering.getLimitCpuUse()); + offeringResponse.setTags(offering.getTags()); + if (offering.getDomainId() != null) { + offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); + offeringResponse.setDomainId(offering.getDomainId()); + } + offeringResponse.setNetworkRate(offering.getRateMbps()); + offeringResponse.setHostTag(offering.getHostTag()); + offeringResponse.setObjectName("serviceoffering"); + + return offeringResponse; + } + + @Override + public ConfigurationResponse createConfigurationResponse(Configuration cfg) { + ConfigurationResponse cfgResponse = new ConfigurationResponse(); + cfgResponse.setCategory(cfg.getCategory()); + cfgResponse.setDescription(cfg.getDescription()); + cfgResponse.setName(cfg.getName()); + cfgResponse.setValue(cfg.getValue()); + cfgResponse.setObjectName("configuration"); + + return cfgResponse; + } + + @Override + public SnapshotResponse createSnapshotResponse(Snapshot snapshot) { + SnapshotResponse snapshotResponse = new SnapshotResponse(); + snapshotResponse.setId(snapshot.getId()); + + populateOwner(snapshotResponse, snapshot); + + VolumeVO volume = findVolumeById(snapshot.getVolumeId()); + String snapshotTypeStr = snapshot.getType().name(); + snapshotResponse.setSnapshotType(snapshotTypeStr); + snapshotResponse.setVolumeId(snapshot.getVolumeId()); + if (volume != null) { + snapshotResponse.setVolumeName(volume.getName()); + snapshotResponse.setVolumeType(volume.getVolumeType().name()); + } + snapshotResponse.setCreated(snapshot.getCreated()); + snapshotResponse.setName(snapshot.getName()); + snapshotResponse.setIntervalType(ApiDBUtils.getSnapshotIntervalTypes(snapshot.getId())); + snapshotResponse.setState(snapshot.getStatus()); + snapshotResponse.setObjectName("snapshot"); + return snapshotResponse; + } + + @Override + public SnapshotPolicyResponse createSnapshotPolicyResponse(SnapshotPolicy policy) { + SnapshotPolicyResponse policyResponse = new SnapshotPolicyResponse(); + policyResponse.setId(policy.getId()); + policyResponse.setVolumeId(policy.getVolumeId()); + policyResponse.setSchedule(policy.getSchedule()); + policyResponse.setIntervalType(policy.getInterval()); + policyResponse.setMaxSnaps(policy.getMaxSnaps()); + policyResponse.setTimezone(policy.getTimezone()); + policyResponse.setObjectName("snapshotpolicy"); + + return policyResponse; + } + + @Override + public HostResponse createHostResponse(Host host) { + return createHostResponse(host, EnumSet.of(HostDetails.all)); + } + + @Override + public HostResponse createHostResponse(Host host, EnumSet details) { + HostResponse hostResponse = new HostResponse(); + hostResponse.setId(host.getId()); + hostResponse.setCapabilities(host.getCapabilities()); + hostResponse.setClusterId(host.getClusterId()); + hostResponse.setCpuNumber(host.getCpus()); + hostResponse.setZoneId(host.getDataCenterId()); + hostResponse.setDisconnectedOn(host.getDisconnectedOn()); + hostResponse.setHypervisor(host.getHypervisorType()); + hostResponse.setHostType(host.getType()); + hostResponse.setLastPinged(new Date(host.getLastPinged())); + hostResponse.setManagementServerId(host.getManagementServerId()); + hostResponse.setName(host.getName()); + hostResponse.setPodId(host.getPodId()); + hostResponse.setRemoved(host.getRemoved()); + hostResponse.setCpuSpeed(host.getSpeed()); + hostResponse.setState(host.getStatus()); + hostResponse.setIpAddress(host.getPrivateIpAddress()); + hostResponse.setVersion(host.getVersion()); + hostResponse.setCreated(host.getCreated()); + + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) + || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { + + GuestOSCategoryVO guestOSCategory = ApiDBUtils.getHostGuestOSCategory(host.getId()); + if (guestOSCategory != null) { + hostResponse.setOsCategoryId(guestOSCategory.getId()); + hostResponse.setOsCategoryName(guestOSCategory.getName()); + } + hostResponse.setZoneName(ApiDBUtils.findZoneById(host.getDataCenterId()).getName()); + + if (host.getPodId() != null) { + HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); + if (pod != null) { + hostResponse.setPodName(pod.getName()); + } + } + + if (host.getClusterId() != null) { + ClusterVO cluster = ApiDBUtils.findClusterById(host.getClusterId()); + hostResponse.setClusterName(cluster.getName()); + hostResponse.setClusterType(cluster.getClusterType().toString()); + } + } + + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + if (host.getType() == Host.Type.Routing) { + + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { + // set allocated capacities + Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_MEMORY); + Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_CPU); + + hostResponse.setMemoryAllocated(mem); + hostResponse.setMemoryTotal(host.getTotalMemory()); + hostResponse.setHostTags(ApiDBUtils.getHostTags(host.getId())); + hostResponse.setHypervisorVersion(host.getHypervisorVersion()); + + String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; + hostResponse.setCpuAllocated(cpuAlloc); + String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); + hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); + } + + if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { + // set CPU/RAM/Network stats + String cpuUsed = null; + HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); + if (hostStats != null) { + float cpuUtil = (float) hostStats.getCpuUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + hostResponse.setCpuUsed(cpuUsed); + hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); + hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); + hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); + + } + } + + } else if (host.getType() == Host.Type.SecondaryStorage) { + StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); + if (secStorageStats != null) { + hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); + hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); + } + } + + hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host)); + + if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { + Set possibleEvents = host.getStatus().getPossibleEvents(); + if ((possibleEvents != null) && !possibleEvents.isEmpty()) { + String events = ""; + Iterator iter = possibleEvents.iterator(); + while (iter.hasNext()) { + com.cloud.host.Status.Event event = iter.next(); + events += event.toString(); + if (iter.hasNext()) { + events += "; "; + } + } + hostResponse.setEvents(events); + } + } + + hostResponse.setResourceState(host.getResourceState().toString()); + + hostResponse.setObjectName("host"); + + return hostResponse; + } + + @Override + public SwiftResponse createSwiftResponse(Swift swift) { + SwiftResponse swiftResponse = new SwiftResponse(); + swiftResponse.setId(swift.getId()); + swiftResponse.setUrl(swift.getUrl()); + swiftResponse.setAccount(swift.getAccount()); + swiftResponse.setUsername(swift.getUserName()); + swiftResponse.setObjectName("swift"); + return swiftResponse; + } + + @Override + public VlanIpRangeResponse createVlanIpRangeResponse(Vlan vlan) { + Long podId = ApiDBUtils.getPodIdForVlan(vlan.getId()); + + VlanIpRangeResponse vlanResponse = new VlanIpRangeResponse(); + vlanResponse.setId(vlan.getId()); + vlanResponse.setForVirtualNetwork(vlan.getVlanType().equals(VlanType.VirtualNetwork)); + vlanResponse.setVlan(vlan.getVlanTag()); + vlanResponse.setZoneId(vlan.getDataCenterId()); + + if (podId != null) { + HostPodVO pod = ApiDBUtils.findPodById(podId); + vlanResponse.setPodId(podId); + if (pod != null) { + vlanResponse.setPodName(pod.getName()); + } + } + + vlanResponse.setGateway(vlan.getVlanGateway()); + vlanResponse.setNetmask(vlan.getVlanNetmask()); + + // get start ip and end ip of corresponding vlan + String ipRange = vlan.getIpRange(); + String[] range = ipRange.split("-"); + vlanResponse.setStartIp(range[0]); + vlanResponse.setEndIp(range[1]); + + vlanResponse.setNetworkId(vlan.getNetworkId()); + Account owner = ApiDBUtils.getVlanAccount(vlan.getId()); + if (owner != null) { + populateAccount(vlanResponse, owner.getId()); + populateDomain(vlanResponse, owner.getDomainId()); + } + + vlanResponse.setPhysicalNetworkId(vlan.getPhysicalNetworkId()); + + vlanResponse.setObjectName("vlan"); + return vlanResponse; + } + + @Override + public IPAddressResponse createIPAddressResponse(IpAddress ipAddress) { + VlanVO vlan = ApiDBUtils.findVlanById(ipAddress.getVlanId()); + boolean forVirtualNetworks = vlan.getVlanType().equals(VlanType.VirtualNetwork); + long zoneId = ipAddress.getDataCenterId(); + + IPAddressResponse ipResponse = new IPAddressResponse(); + ipResponse.setId(ipAddress.getId()); + ipResponse.setIpAddress(ipAddress.getAddress().toString()); + if (ipAddress.getAllocatedTime() != null) { + ipResponse.setAllocated(ipAddress.getAllocatedTime()); + } + ipResponse.setZoneId(zoneId); + ipResponse.setZoneName(ApiDBUtils.findZoneById(ipAddress.getDataCenterId()).getName()); + ipResponse.setSourceNat(ipAddress.isSourceNat()); + ipResponse.setIsSystem(ipAddress.getSystem()); + + // get account information + populateOwner(ipResponse, ipAddress); + + ipResponse.setForVirtualNetwork(forVirtualNetworks); + ipResponse.setStaticNat(ipAddress.isOneToOneNat()); + + if (ipAddress.getAssociatedWithVmId() != null) { + UserVm vm = ApiDBUtils.findUserVmById(ipAddress.getAssociatedWithVmId()); + ipResponse.setVirtualMachineId(vm.getId()); + ipResponse.setVirtualMachineName(vm.getHostName()); + if (vm.getDisplayName() != null) { + ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); + } else { + ipResponse.setVirtualMachineDisplayName(vm.getHostName()); + } + } + + ipResponse.setAssociatedNetworkId(ipAddress.getAssociatedWithNetworkId()); + + // Network id the ip is associated withif associated networkId is null, try to get this information from vlan + Long associatedNetworkId = ipAddress.getAssociatedWithNetworkId(); + Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddress.getVlanId()); + if (associatedNetworkId == null) { + associatedNetworkId = vlanNetworkId; + } + + ipResponse.setAssociatedNetworkId(associatedNetworkId); + + // Network id the ip belongs to + Long networkId; + if (vlanNetworkId != null) { + networkId = vlanNetworkId; + } else { + networkId = ApiDBUtils.getPublicNetworkIdByZone(zoneId); + } + + ipResponse.setNetworkId(networkId); + ipResponse.setState(ipAddress.getState().toString()); + ipResponse.setPhysicalNetworkId(ipAddress.getPhysicalNetworkId()); + + // show this info to admin only + Account account = UserContext.current().getCaller(); + if ((account == null) || account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + ipResponse.setVlanId(ipAddress.getVlanId()); + ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddress.getVlanId()).getVlanTag()); + } + + if (ipAddress.getSystem()) { + if (ipAddress.isOneToOneNat()) { + ipResponse.setPurpose(IpAddress.Purpose.StaticNat.toString()); + } else { + ipResponse.setPurpose(IpAddress.Purpose.Lb.toString()); + } + } + + ipResponse.setObjectName("ipaddress"); + return ipResponse; + } + + @Override + public LoadBalancerResponse createLoadBalancerResponse(LoadBalancer loadBalancer) { + LoadBalancerResponse lbResponse = new LoadBalancerResponse(); + lbResponse.setId(loadBalancer.getId()); + lbResponse.setName(loadBalancer.getName()); + lbResponse.setDescription(loadBalancer.getDescription()); + List cidrs = ApiDBUtils.findFirewallSourceCidrs(loadBalancer.getId()); + lbResponse.setCidrList(StringUtils.join(cidrs, ",")); + + IPAddressVO publicIp = ApiDBUtils.findIpAddressById(loadBalancer.getSourceIpAddressId()); + lbResponse.setPublicIpId(publicIp.getId()); + lbResponse.setPublicIp(publicIp.getAddress().addr()); + lbResponse.setPublicPort(Integer.toString(loadBalancer.getSourcePortStart())); + lbResponse.setPrivatePort(Integer.toString(loadBalancer.getDefaultPortStart())); + lbResponse.setAlgorithm(loadBalancer.getAlgorithm()); + FirewallRule.State state = loadBalancer.getState(); + String stateToSet = state.toString(); + if (state.equals(FirewallRule.State.Revoke)) { + stateToSet = "Deleting"; + } + lbResponse.setState(stateToSet); + populateOwner(lbResponse, loadBalancer); + lbResponse.setZoneId(publicIp.getDataCenterId()); + + lbResponse.setObjectName("loadbalancer"); + return lbResponse; + } + + @Override + public PodResponse createPodResponse(Pod pod, Boolean showCapacities) { + String[] ipRange = new String[2]; + if (pod.getDescription() != null && pod.getDescription().length() > 0) { + ipRange = pod.getDescription().split("-"); + } else { + ipRange[0] = pod.getDescription(); + } + + PodResponse podResponse = new PodResponse(); + podResponse.setId(pod.getId()); + podResponse.setName(pod.getName()); + podResponse.setZoneId(pod.getDataCenterId()); + podResponse.setZoneName(PodZoneConfig.getZoneName(pod.getDataCenterId())); + podResponse.setNetmask(NetUtils.getCidrNetmask(pod.getCidrSize())); + podResponse.setStartIp(ipRange[0]); + podResponse.setEndIp(((ipRange.length > 1) && (ipRange[1] != null)) ? ipRange[1] : ""); + podResponse.setGateway(pod.getGateway()); + podResponse.setAllocationState(pod.getAllocationState().toString()); + if (showCapacities != null && showCapacities) { + List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, pod.getId(), null); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId(), null); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, null, pod.getId(), pod.getDataCenterId())); + podResponse.setCapacitites(new ArrayList(capacityResponses)); + } + podResponse.setObjectName("pod"); + return podResponse; + } + + @Override + public ZoneResponse createZoneResponse(DataCenter dataCenter, Boolean showCapacities) { + Account account = UserContext.current().getCaller(); + ZoneResponse zoneResponse = new ZoneResponse(); + zoneResponse.setId(dataCenter.getId()); + zoneResponse.setName(dataCenter.getName()); + zoneResponse.setSecurityGroupsEnabled(ApiDBUtils.isSecurityGroupEnabledInZone(dataCenter.getId())); + + if ((dataCenter.getDescription() != null) && !dataCenter.getDescription().equalsIgnoreCase("null")) { + zoneResponse.setDescription(dataCenter.getDescription()); + } + + if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { + zoneResponse.setDns1(dataCenter.getDns1()); + zoneResponse.setDns2(dataCenter.getDns2()); + zoneResponse.setInternalDns1(dataCenter.getInternalDns1()); + zoneResponse.setInternalDns2(dataCenter.getInternalDns2()); + // FIXME zoneResponse.setVlan(dataCenter.get.getVnet()); + zoneResponse.setGuestCidrAddress(dataCenter.getGuestNetworkCidr()); + } + + if (showCapacities != null && showCapacities) { + List capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(), null, null); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null, null); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, null, null, dataCenter.getId())); + + zoneResponse.setCapacitites(new ArrayList(capacityResponses)); + } + + // set network domain info + zoneResponse.setDomain(dataCenter.getDomain()); + + // set domain info + Long domainId = dataCenter.getDomainId(); + if (domainId != null) { + Domain domain = ApiDBUtils.findDomainById(domainId); + zoneResponse.setDomainId(domain.getId()); + zoneResponse.setDomainName(domain.getName()); + } + + zoneResponse.setType(dataCenter.getNetworkType().toString()); + zoneResponse.setAllocationState(dataCenter.getAllocationState().toString()); + zoneResponse.setZoneToken(dataCenter.getZoneToken()); + zoneResponse.setDhcpProvider(dataCenter.getDhcpProvider()); + zoneResponse.setObjectName("zone"); + return zoneResponse; + } + + private List getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId) { + List capacities = new ArrayList(); + capacities.add(ApiDBUtils.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId)); + if (clusterId == null && podId == null) { + capacities.add(ApiDBUtils.getSecondaryStorageUsedStats(poolId, zoneId)); + } + + List capacityResponses = new ArrayList(); + for (CapacityVO capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + + return capacityResponses; + } + + @Override + public VolumeResponse createVolumeResponse(Volume volume) { + VolumeResponse volResponse = new VolumeResponse(); + volResponse.setId(volume.getId()); + + if (volume.getName() != null) { + volResponse.setName(volume.getName()); + } else { + volResponse.setName(""); + } + + volResponse.setZoneId(volume.getDataCenterId()); + volResponse.setZoneName(ApiDBUtils.findZoneById(volume.getDataCenterId()).getName()); + + volResponse.setVolumeType(volume.getVolumeType().toString()); + volResponse.setDeviceId(volume.getDeviceId()); + + Long instanceId = volume.getInstanceId(); + if (instanceId != null && volume.getState() != Volume.State.Destroy) { + VMInstanceVO vm = ApiDBUtils.findVMInstanceById(instanceId); + if (vm != null) { + volResponse.setVirtualMachineId(vm.getId()); + volResponse.setVirtualMachineName(vm.getHostName()); + UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); + if (userVm != null) { + if (userVm.getDisplayName() != null) { + volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); + } else { + volResponse.setVirtualMachineDisplayName(userVm.getHostName()); + } + volResponse.setVirtualMachineState(vm.getState().toString()); + } else { + s_logger.error("User Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); + } + } else { + s_logger.error("Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); + } + } + + // Show the virtual size of the volume + volResponse.setSize(volume.getSize()); + + volResponse.setCreated(volume.getCreated()); + volResponse.setState(volume.getState().toString()); + + populateOwner(volResponse, volume); + + String storageType; + try { + if (volume.getPoolId() == null) { + if (volume.getState() == Volume.State.Allocated) { + /* set it as shared, so the UI can attach it to VM */ + storageType = "shared"; + } else { + storageType = "unknown"; + } + } else { + storageType = ApiDBUtils.volumeIsOnSharedStorage(volume.getId()) ? ServiceOffering.StorageType.shared.toString() : ServiceOffering.StorageType.local.toString(); + } + } catch (InvalidParameterValueException e) { + s_logger.error(e.getMessage(), e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Volume " + volume.getName() + " does not have a valid ID"); + } + + volResponse.setStorageType(storageType); + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + volResponse.setServiceOfferingId(volume.getDiskOfferingId()); + } else { + volResponse.setDiskOfferingId(volume.getDiskOfferingId()); + } + + DiskOfferingVO diskOffering = ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId()); + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + volResponse.setServiceOfferingName(diskOffering.getName()); + volResponse.setServiceOfferingDisplayText(diskOffering.getDisplayText()); + } else { + volResponse.setDiskOfferingName(diskOffering.getName()); + volResponse.setDiskOfferingDisplayText(diskOffering.getDisplayText()); + } + + Long poolId = volume.getPoolId(); + String poolName = (poolId == null) ? "none" : ApiDBUtils.findStoragePoolById(poolId).getName(); + volResponse.setStoragePoolName(poolName); + // volResponse.setSourceId(volume.getSourceId()); + // if (volume.getSourceType() != null) { + // volResponse.setSourceType(volume.getSourceType().toString()); + // } + + // return hypervisor for ROOT and Resource domain only + Account caller = UserContext.current().getCaller(); + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString()); + } + + volResponse.setAttached(volume.getAttached()); + volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); + VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); + boolean isExtractable = template != null && template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM); + volResponse.setExtractable(isExtractable); + volResponse.setObjectName("volume"); + return volResponse; + } + + @Override + public InstanceGroupResponse createInstanceGroupResponse(InstanceGroup group) { + InstanceGroupResponse groupResponse = new InstanceGroupResponse(); + groupResponse.setId(group.getId()); + groupResponse.setName(group.getName()); + groupResponse.setCreated(group.getCreated()); + + populateOwner(groupResponse, group); + + groupResponse.setObjectName("instancegroup"); + return groupResponse; + } + + @Override + public StoragePoolResponse createStoragePoolResponse(StoragePool pool) { + StoragePoolResponse poolResponse = new StoragePoolResponse(); + poolResponse.setId(pool.getId()); + poolResponse.setName(pool.getName()); + poolResponse.setState(pool.getStatus()); + poolResponse.setPath(pool.getPath()); + poolResponse.setIpAddress(pool.getHostAddress()); + poolResponse.setZoneId(pool.getDataCenterId()); + poolResponse.setZoneName(ApiDBUtils.findZoneById(pool.getDataCenterId()).getName()); + if (pool.getPoolType() != null) { + poolResponse.setType(pool.getPoolType().toString()); + } + if (pool.getPodId() != null) { + poolResponse.setPodId(pool.getPodId()); + HostPodVO pod = ApiDBUtils.findPodById(pool.getPodId()); + if (pod != null) { + poolResponse.setPodName(pod.getName()); + } + } + if (pool.getCreated() != null) { + poolResponse.setCreated(pool.getCreated()); + } + + StorageStats stats = ApiDBUtils.getStoragePoolStatistics(pool.getId()); + long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(), Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); + poolResponse.setDiskSizeTotal(pool.getCapacityBytes()); + poolResponse.setDiskSizeAllocated(allocatedSize); + + if (stats != null) { + Long used = stats.getByteUsed(); + poolResponse.setDiskSizeUsed(used); + } + + if (pool.getClusterId() != null) { + ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); + poolResponse.setClusterId(cluster.getId()); + poolResponse.setClusterName(cluster.getName()); + } + poolResponse.setTags(ApiDBUtils.getStoragePoolTags(pool.getId())); + poolResponse.setObjectName("storagepool"); + return poolResponse; + } + + @Override + public ClusterResponse createClusterResponse(Cluster cluster, Boolean showCapacities) { + ClusterResponse clusterResponse = new ClusterResponse(); + clusterResponse.setId(cluster.getId()); + clusterResponse.setName(cluster.getName()); + clusterResponse.setPodId(cluster.getPodId()); + clusterResponse.setZoneId(cluster.getDataCenterId()); + clusterResponse.setHypervisorType(cluster.getHypervisorType().toString()); + clusterResponse.setClusterType(cluster.getClusterType().toString()); + clusterResponse.setAllocationState(cluster.getAllocationState().toString()); + clusterResponse.setManagedState(cluster.getManagedState().toString()); + HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); + if (pod != null) { + clusterResponse.setPodName(pod.getName()); + } + DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); + clusterResponse.setZoneName(zone.getName()); + if (showCapacities != null && showCapacities) { + List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, null, cluster.getId()); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, null, cluster.getId()); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, cluster.getId(), pod.getId(), pod.getDataCenterId())); + clusterResponse.setCapacitites(new ArrayList(capacityResponses)); + } + clusterResponse.setObjectName("cluster"); + return clusterResponse; + } + + @Override + public FirewallRuleResponse createPortForwardingRuleResponse(PortForwardingRule fwRule) { + FirewallRuleResponse response = new FirewallRuleResponse(); + response.setId(fwRule.getId()); + response.setPrivateStartPort(Integer.toString(fwRule.getDestinationPortStart())); + response.setPrivateEndPort(Integer.toString(fwRule.getDestinationPortEnd())); + response.setProtocol(fwRule.getProtocol()); + response.setPublicStartPort(Integer.toString(fwRule.getSourcePortStart())); + response.setPublicEndPort(Integer.toString(fwRule.getSourcePortEnd())); + List cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId()); + response.setCidrList(StringUtils.join(cidrs, ",")); + + IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); + response.setPublicIpAddressId(ip.getId()); + response.setPublicIpAddress(ip.getAddress().addr()); + + if (ip != null && fwRule.getDestinationIpAddress() != null) { + UserVm vm = ApiDBUtils.findUserVmById(fwRule.getVirtualMachineId()); + if (vm != null) { + response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineName(vm.getHostName()); + + if (vm.getDisplayName() != null) { + response.setVirtualMachineDisplayName(vm.getDisplayName()); + } else { + response.setVirtualMachineDisplayName(vm.getHostName()); + } + } + } + FirewallRule.State state = fwRule.getState(); + String stateToSet = state.toString(); + if (state.equals(FirewallRule.State.Revoke)) { + stateToSet = "Deleting"; + } + response.setState(stateToSet); + response.setObjectName("portforwardingrule"); + return response; + } + + @Override + public IpForwardingRuleResponse createIpForwardingRuleResponse(StaticNatRule fwRule) { + IpForwardingRuleResponse response = new IpForwardingRuleResponse(); + response.setId(fwRule.getId()); + response.setProtocol(fwRule.getProtocol()); + + IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); + response.setPublicIpAddressId(ip.getId()); + response.setPublicIpAddress(ip.getAddress().addr()); + + if (ip != null && fwRule.getDestIpAddress() != null) { + UserVm vm = ApiDBUtils.findUserVmById(ip.getAssociatedWithVmId()); + if (vm != null) {// vm might be destroyed + response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineName(vm.getHostName()); + if (vm.getDisplayName() != null) { + response.setVirtualMachineDisplayName(vm.getDisplayName()); + } else { + response.setVirtualMachineDisplayName(vm.getHostName()); + } + } + } + FirewallRule.State state = fwRule.getState(); + String stateToSet = state.toString(); + if (state.equals(FirewallRule.State.Revoke)) { + stateToSet = "Deleting"; + } + + response.setStartPort(fwRule.getSourcePortStart()); + response.setEndPort(fwRule.getSourcePortEnd()); + response.setProtocol(fwRule.getProtocol()); + response.setState(stateToSet); + response.setObjectName("ipforwardingrule"); + return response; + } + + @Override + public List createUserVmResponse(String objectName, EnumSet details, UserVm... userVms) { + Account caller = UserContext.current().getCaller(); + Map dataCenters = new HashMap(); + Map hosts = new HashMap(); + Map templates = new HashMap(); + Map serviceOfferings = new HashMap(); + Map networks = new HashMap(); + + List vmResponses = new ArrayList(); + + for (UserVm userVm : userVms) { + UserVmResponse userVmResponse = new UserVmResponse(); + Account acct = ApiDBUtils.findAccountById(Long.valueOf(userVm.getAccountId())); + if (acct != null) { + userVmResponse.setAccountName(acct.getAccountName()); + userVmResponse.setDomainId(acct.getDomainId()); + userVmResponse.setDomainName(ApiDBUtils.findDomainById(acct.getDomainId()).getName()); + } + + userVmResponse.setId(userVm.getId()); + userVmResponse.setName(userVm.getHostName()); + userVmResponse.setCreated(userVm.getCreated()); + + userVmResponse.setHaEnable(userVm.isHaEnabled()); + + if (userVm.getDisplayName() != null) { + userVmResponse.setDisplayName(userVm.getDisplayName()); + } else { + userVmResponse.setDisplayName(userVm.getHostName()); + } + + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { + userVmResponse.setInstanceName(userVm.getInstanceName()); + } + + + if (userVm.getPassword() != null) { + userVmResponse.setPassword(userVm.getPassword()); + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { + InstanceGroupVO group = ApiDBUtils.findInstanceGroupForVM(userVm.getId()); + if (group != null) { + userVmResponse.setGroup(group.getName()); + userVmResponse.setGroupId(group.getId()); + } + + } + + // Data Center Info + DataCenter zone = dataCenters.get(userVm.getDataCenterIdToDeployIn()); + if (zone == null) { + zone = ApiDBUtils.findZoneById(userVm.getDataCenterIdToDeployIn()); + dataCenters.put(zone.getId(), zone); + } + + userVmResponse.setZoneId(zone.getId()); + userVmResponse.setZoneName(zone.getName()); + + // if user is an admin, display host id + if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { + Host host = hosts.get(userVm.getHostId()); + + if (host == null) { + host = ApiDBUtils.findHostById(userVm.getHostId()); + hosts.put(host.getId(), host); + } + + userVmResponse.setHostId(host.getId()); + userVmResponse.setHostName(host.getName()); + } + + if (userVm.getState() != null) { + if (userVm.getHostId() != null) { + Host host = hosts.get(userVm.getHostId()); + + if (host == null) { + host = ApiDBUtils.findHostById(userVm.getHostId()); + hosts.put(host.getId(), host); + } + if (host.getStatus() != com.cloud.host.Status.Up) { + userVmResponse.setState(VirtualMachine.State.Unknown.toString()); + } else { + userVmResponse.setState(userVm.getState().toString()); + } + } else { + userVmResponse.setState(userVm.getState().toString()); + } + } + + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + if (userVm.getHypervisorType() != null) { + userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { + // Template Info + VMTemplateVO template = templates.get(userVm.getTemplateId()); + if (template == null) { + template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); + if (template != null) { + templates.put(template.getId(), template); + } + } + + if (template != null) { + userVmResponse.setTemplateId(userVm.getTemplateId()); + userVmResponse.setTemplateName(template.getName()); + userVmResponse.setTemplateDisplayText(template.getDisplayText()); + userVmResponse.setPasswordEnabled(template.getEnablePassword()); + } else { + userVmResponse.setTemplateId(-1L); + userVmResponse.setTemplateName("ISO Boot"); + userVmResponse.setTemplateDisplayText("ISO Boot"); + userVmResponse.setPasswordEnabled(false); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { + // ISO Info + VMTemplateVO iso = templates.get(userVm.getIsoId()); + if (iso == null) { + iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); + if (iso != null) { + templates.put(iso.getId(), iso); + } + } + + if (iso != null) { + userVmResponse.setIsoId(iso.getId()); + userVmResponse.setIsoName(iso.getName()); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { + // Service Offering Info + ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); + + if (offering == null) { + offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); + serviceOfferings.put(offering.getId(), offering); + } + + userVmResponse.setServiceOfferingId(offering.getId()); + userVmResponse.setServiceOfferingName(offering.getName()); + userVmResponse.setCpuNumber(offering.getCpu()); + userVmResponse.setCpuSpeed(offering.getSpeed()); + userVmResponse.setMemory(offering.getRamSize()); + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { + VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId()); + if (rootVolume != null) { + userVmResponse.setRootDeviceId(rootVolume.getDeviceId()); + String rootDeviceType = "Not created"; + if (rootVolume.getPoolId() != null) { + StoragePoolVO storagePool = ApiDBUtils.findStoragePoolById(rootVolume.getPoolId()); + rootDeviceType = storagePool.getPoolType().toString(); + } + userVmResponse.setRootDeviceType(rootDeviceType); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { + // stats calculation + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + String cpuUsed = null; + VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); + if (vmStats != null) { + float cpuUtil = (float) vmStats.getCPUUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + userVmResponse.setCpuUsed(cpuUsed); + + Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); + userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); + + Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); + userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); + } + } + + userVmResponse.setGuestOsId(userVm.getGuestOSId()); + + if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { + // security groups - list only when zone is security group enabled + if (zone.isSecurityGroupEnabled()) { + List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); + List securityGroupResponse = new ArrayList(); + for (SecurityGroupVO grp : securityGroups) { + SecurityGroupResponse resp = new SecurityGroupResponse(); + resp.setId(grp.getId()); + resp.setName(grp.getName()); + resp.setDescription(grp.getDescription()); + resp.setObjectName("securitygroup"); + securityGroupResponse.add(resp); + } + userVmResponse.setSecurityGroupList(securityGroupResponse); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { + List nicProfiles = ApiDBUtils.getNics(userVm); + List nicResponses = new ArrayList(); + for (NicProfile singleNicProfile : nicProfiles) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(singleNicProfile.getId()); + nicResponse.setIpaddress(singleNicProfile.getIp4Address()); + nicResponse.setGateway(singleNicProfile.getGateway()); + nicResponse.setNetmask(singleNicProfile.getNetmask()); + nicResponse.setNetworkid(singleNicProfile.getNetworkId()); + if (acct.getType() == Account.ACCOUNT_TYPE_ADMIN) { + if (singleNicProfile.getBroadCastUri() != null) { + nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); + } + if (singleNicProfile.getIsolationUri() != null) { + nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); + } + } + + // Long networkId = singleNicProfile.getNetworkId(); + Network network = networks.get(singleNicProfile.getNetworkId()); + if (network == null) { + network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); + networks.put(singleNicProfile.getNetworkId(), network); + } + + nicResponse.setTrafficType(network.getTrafficType().toString()); + nicResponse.setType(network.getGuestType().toString()); + nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); + nicResponse.setObjectName("nic"); + nicResponses.add(nicResponse); + } + userVmResponse.setNics(nicResponses); + } + + IpAddress ip = ApiDBUtils.findIpByAssociatedVmId(userVm.getId()); + if (ip != null) { + userVmResponse.setPublicIpId(ip.getId()); + userVmResponse.setPublicIp(ip.getAddress().addr()); + } + + userVmResponse.setObjectName(objectName); + vmResponses.add(userVmResponse); + } + + return vmResponses; + } + + @Override + public List createUserVmResponse(String objectName, UserVm... userVms) { + Account caller = UserContext.current().getCaller(); + boolean caller_is_admin = ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)); + + Hashtable vmDataList = new Hashtable(); + // Initialise the vmdatalist with the input data + for (UserVm userVm : userVms) { + UserVmData userVmData = newUserVmData(userVm); + vmDataList.put(userVm.getId(), userVmData); + } + + vmDataList = ApiDBUtils.listVmDetails(vmDataList); + + // initialize vmresponse from vmdatalist + List vmResponses = new ArrayList(); + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + for (UserVmData uvd : vmDataList.values()) { + UserVmResponse userVmResponse = newUserVmResponse(uvd, caller_is_admin); + + // stats calculation + String cpuUsed = null; + // VmStats vmStats = ApiDBUtils.getVmStatistics(userVmResponse.getId()); + VmStats vmStats = ApiDBUtils.getVmStatistics(uvd.getId()); + if (vmStats != null) { + float cpuUtil = (float) vmStats.getCPUUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + userVmResponse.setCpuUsed(cpuUsed); + + Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); + userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); + + Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); + userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); + } + userVmResponse.setObjectName(objectName); + + vmResponses.add(userVmResponse); + } + return vmResponses; + } + + @Override + public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) { + Account caller = UserContext.current().getCaller(); + Map serviceOfferings = new HashMap(); + + DomainRouterResponse routerResponse = new DomainRouterResponse(); + routerResponse.setId(router.getId()); + routerResponse.setZoneId(router.getDataCenterIdToDeployIn()); + routerResponse.setName(router.getHostName()); + routerResponse.setTemplateId(router.getTemplateId()); + routerResponse.setCreated(router.getCreated()); + routerResponse.setState(router.getState()); + routerResponse.setIsRedundantRouter(router.getIsRedundantRouter()); + routerResponse.setRedundantState(router.getRedundantState().toString()); + + if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { + if (router.getHostId() != null) { + routerResponse.setHostId(router.getHostId()); + routerResponse.setHostName(ApiDBUtils.findHostById(router.getHostId()).getName()); + } + routerResponse.setPodId(router.getPodIdToDeployIn()); + List nicProfiles = ApiDBUtils.getNics(router); + for (NicProfile singleNicProfile : nicProfiles) { + Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); + if (network != null) { + if (network.getTrafficType() == TrafficType.Public) { + routerResponse.setPublicIp(singleNicProfile.getIp4Address()); + routerResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); + routerResponse.setPublicNetmask(singleNicProfile.getNetmask()); + routerResponse.setGateway(singleNicProfile.getGateway()); + routerResponse.setPublicNetworkId(singleNicProfile.getNetworkId()); + } else if (network.getTrafficType() == TrafficType.Control) { + routerResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); + routerResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); + routerResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); + routerResponse.setLinkLocalNetworkId(singleNicProfile.getNetworkId()); + } else if (network.getTrafficType() == TrafficType.Guest) { + routerResponse.setGuestIpAddress(singleNicProfile.getIp4Address()); + routerResponse.setGuestMacAddress(singleNicProfile.getMacAddress()); + routerResponse.setGuestNetmask(singleNicProfile.getNetmask()); + routerResponse.setGuestNetworkId(singleNicProfile.getNetworkId()); + routerResponse.setNetworkDomain(network.getNetworkDomain()); + } + } + } + } + + // Service Offering Info + ServiceOffering offering = serviceOfferings.get(router.getServiceOfferingId()); + + if (offering == null) { + offering = ApiDBUtils.findServiceOfferingById(router.getServiceOfferingId()); + serviceOfferings.put(offering.getId(), offering); + } + routerResponse.setServiceOfferingId(offering.getId()); + routerResponse.setServiceOfferingName(offering.getName()); + + populateOwner(routerResponse, router); + + DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn()); + if (zone != null) { + routerResponse.setZoneName(zone.getName()); + routerResponse.setDns1(zone.getDns1()); + routerResponse.setDns2(zone.getDns2()); + } + + routerResponse.setObjectName("domainrouter"); + return routerResponse; + } + + @Override + public SystemVmResponse createSystemVmResponse(VirtualMachine vm) { + SystemVmResponse vmResponse = new SystemVmResponse(); + if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy) { + // SystemVm vm = (SystemVm) systemVM; + vmResponse.setId(vm.getId()); + vmResponse.setObjectId(vm.getId()); + vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); + vmResponse.setZoneId(vm.getDataCenterIdToDeployIn()); + + vmResponse.setName(vm.getHostName()); + vmResponse.setPodId(vm.getPodIdToDeployIn()); + vmResponse.setTemplateId(vm.getTemplateId()); + vmResponse.setCreated(vm.getCreated()); + + if (vm.getHostId() != null) { + vmResponse.setHostId(vm.getHostId()); + vmResponse.setHostName(ApiDBUtils.findHostById(vm.getHostId()).getName()); + } + + if (vm.getState() != null) { + vmResponse.setState(vm.getState().toString()); + } + + // for console proxies, add the active sessions + if (vm.getType() == Type.ConsoleProxy) { + ConsoleProxyVO proxy = ApiDBUtils.findConsoleProxy(vm.getId()); + // proxy can be already destroyed + if (proxy != null) { + vmResponse.setActiveViewerSessions(proxy.getActiveSession()); + } + } + + DataCenter zone = ApiDBUtils.findZoneById(vm.getDataCenterIdToDeployIn()); + if (zone != null) { + vmResponse.setZoneName(zone.getName()); + vmResponse.setDns1(zone.getDns1()); + vmResponse.setDns2(zone.getDns2()); + } + + List nicProfiles = ApiDBUtils.getNics(vm); + for (NicProfile singleNicProfile : nicProfiles) { + Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); + if (network != null) { + if (network.getTrafficType() == TrafficType.Management) { + vmResponse.setPrivateIp(singleNicProfile.getIp4Address()); + vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress()); + vmResponse.setPrivateNetmask(singleNicProfile.getNetmask()); + } else if (network.getTrafficType() == TrafficType.Control) { + vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); + vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); vmResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); } else if (network.getTrafficType() == TrafficType.Public || network.getTrafficType() == TrafficType.Guest) { - /*In basic zone, public ip has TrafficType.Guest*/ - vmResponse.setPublicIp(singleNicProfile.getIp4Address()); - vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); - vmResponse.setGateway(singleNicProfile.getGateway()); - } - } - } - } - vmResponse.setObjectName("systemvm"); - return vmResponse; - } - - @Override - public Host findHostById(Long hostId) { - return ApiDBUtils.findHostById(hostId); - } - - @Override - public User findUserById(Long userId) { - return ApiDBUtils.findUserById(userId); - } - - @Override - public UserVm findUserVmById(Long vmId) { - return ApiDBUtils.findUserVmById(vmId); - - } - - @Override - public VolumeVO findVolumeById(Long volumeId) { - return ApiDBUtils.findVolumeById(volumeId); - } - - @Override - public Account findAccountByNameDomain(String accountName, Long domainId) { - return ApiDBUtils.findAccountByNameDomain(accountName, domainId); - } - - @Override - public VirtualMachineTemplate findTemplateById(Long templateId) { - return ApiDBUtils.findTemplateById(templateId); - } - - @Override - public VpnUsersResponse createVpnUserResponse(VpnUser vpnUser) { - VpnUsersResponse vpnResponse = new VpnUsersResponse(); - vpnResponse.setId(vpnUser.getId()); - vpnResponse.setUserName(vpnUser.getUsername()); - - populateOwner(vpnResponse, vpnUser); - - vpnResponse.setObjectName("vpnuser"); - return vpnResponse; - } - - @Override - public RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn) { - RemoteAccessVpnResponse vpnResponse = new RemoteAccessVpnResponse(); - vpnResponse.setPublicIpId(vpn.getServerAddressId()); - vpnResponse.setPublicIp(ApiDBUtils.findIpAddressById(vpn.getServerAddressId()).getAddress().addr()); - vpnResponse.setIpRange(vpn.getIpRange()); - vpnResponse.setPresharedKey(vpn.getIpsecPresharedKey()); - vpnResponse.setDomainId(vpn.getDomainId()); - - populateOwner(vpnResponse, vpn); - - vpnResponse.setState(vpn.getState().toString()); - vpnResponse.setObjectName("remoteaccessvpn"); - - return vpnResponse; - } - - @Override - public TemplateResponse createIsoResponse(VirtualMachineTemplate result) { - TemplateResponse response = new TemplateResponse(); - response.setId(result.getId()); - response.setName(result.getName()); - response.setDisplayText(result.getDisplayText()); - response.setPublic(result.isPublicTemplate()); - response.setCreated(result.getCreated()); - response.setFormat(result.getFormat()); - response.setOsTypeId(result.getGuestOSId()); - response.setOsTypeName(ApiDBUtils.findGuestOSById(result.getGuestOSId()).getDisplayName()); - response.setDetails(result.getDetails()); - Account caller = UserContext.current().getCaller(); - - if (result.getFormat() == ImageFormat.ISO) { // Templates are always bootable - response.setBootable(result.isBootable()); - } else if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - response.setHypervisor(result.getHypervisorType().toString());// hypervisors are associated with templates - } - - // add account ID and name - Account owner = ApiDBUtils.findAccountById(result.getAccountId()); - populateAccount(response, owner.getId()); - populateDomain(response, owner.getDomainId()); - - response.setObjectName("iso"); - return response; - } - - @Override - public List createTemplateResponses(long templateId, Long zoneId, boolean readyOnly) { - if (zoneId == null || zoneId == -1) { - List responses = new ArrayList(); - List dcs = new ArrayList(); - responses = createSwiftTemplateResponses(templateId); - if (!responses.isEmpty()) { - return responses; - } - dcs.addAll(ApiDBUtils.listZones()); - for (DataCenterVO dc : dcs) { - responses.addAll(createTemplateResponses(templateId, dc.getId(), readyOnly)); - } - return responses; - } else { - return createTemplateResponses(templateId, zoneId.longValue(), readyOnly); - } - } - - private List createSwiftTemplateResponses(long templateId) { - VirtualMachineTemplate template = findTemplateById(templateId); - List responses = new ArrayList(); - VMTemplateSwiftVO templateSwiftRef = ApiDBUtils.findTemplateSwiftRef(templateId); - if (templateSwiftRef == null) { - return responses; - } - - TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(template.getId()); - templateResponse.setName(template.getName()); - templateResponse.setDisplayText(template.getDisplayText()); - templateResponse.setPublic(template.isPublicTemplate()); - templateResponse.setCreated(templateSwiftRef.getCreated()); - - templateResponse.setReady(true); - templateResponse.setFeatured(template.isFeatured()); - templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); - templateResponse.setPasswordEnabled(template.getEnablePassword()); - templateResponse.setCrossZones(template.isCrossZones()); - templateResponse.setFormat(template.getFormat()); - templateResponse.setDetails(template.getDetails()); - if (template.getTemplateType() != null) { - templateResponse.setTemplateType(template.getTemplateType().toString()); - } - - Account caller = UserContext.current().getCaller(); - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - templateResponse.setHypervisor(template.getHypervisorType().toString()); - } - - GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); - if (os != null) { - templateResponse.setOsTypeId(os.getId()); - templateResponse.setOsTypeName(os.getDisplayName()); - } else { - templateResponse.setOsTypeId(-1L); - templateResponse.setOsTypeName(""); - } - - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(template.getAccountId()); - populateAccount(templateResponse, account.getId()); - populateDomain(templateResponse, account.getDomainId()); - - boolean isAdmin = false; - if (BaseCmd.isAdmin(caller.getType())) { - isAdmin = true; - } - - // If the user is an Admin, add the template download status - if (isAdmin || caller.getId() == template.getAccountId()) { - // add download status - templateResponse.setStatus("Successfully Installed"); - } - - Long templateSize = templateSwiftRef.getSize(); - if (templateSize > 0) { - templateResponse.setSize(templateSize); - } - - templateResponse.setChecksum(template.getChecksum()); - templateResponse.setSourceTemplateId(template.getSourceTemplateId()); - - templateResponse.setChecksum(template.getChecksum()); - - templateResponse.setTemplateTag(template.getTemplateTag()); - - templateResponse.setObjectName("template"); - responses.add(templateResponse); - return responses; - } - - @Override - public List createTemplateResponses(long templateId, long zoneId, boolean readyOnly) { - VirtualMachineTemplate template = findTemplateById(templateId); - List responses = new ArrayList(); - VMTemplateHostVO templateHostRef = ApiDBUtils.findTemplateHostRef(templateId, zoneId, readyOnly); - if (templateHostRef == null) { - return responses; - } - - HostVO host = ApiDBUtils.findHostById(templateHostRef.getHostId()); - if (host.getType() == Host.Type.LocalSecondaryStorage && host.getStatus() != com.cloud.host.Status.Up) { - return responses; - } - - TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(template.getId()); - templateResponse.setName(template.getName()); - templateResponse.setDisplayText(template.getDisplayText()); - templateResponse.setPublic(template.isPublicTemplate()); - templateResponse.setCreated(templateHostRef.getCreated()); - - templateResponse.setReady(templateHostRef.getDownloadState() == Status.DOWNLOADED); - templateResponse.setFeatured(template.isFeatured()); - templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); - templateResponse.setPasswordEnabled(template.getEnablePassword()); - templateResponse.setCrossZones(template.isCrossZones()); - templateResponse.setFormat(template.getFormat()); - if (template.getTemplateType() != null) { - templateResponse.setTemplateType(template.getTemplateType().toString()); - } - - Account caller = UserContext.current().getCaller(); - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - templateResponse.setHypervisor(template.getHypervisorType().toString()); - } - - templateResponse.setDetails(template.getDetails()); - - GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); - if (os != null) { - templateResponse.setOsTypeId(os.getId()); - templateResponse.setOsTypeName(os.getDisplayName()); - } else { - templateResponse.setOsTypeId(-1L); - templateResponse.setOsTypeName(""); - } - - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(template.getAccountId()); - populateAccount(templateResponse, account.getId()); - populateDomain(templateResponse, account.getDomainId()); - - DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); - - // Add the zone ID - templateResponse.setZoneId(zoneId); - templateResponse.setZoneName(datacenter.getName()); - - boolean isAdmin = false; - if ((caller == null) || BaseCmd.isAdmin(caller.getType())) { - isAdmin = true; - } - - // If the user is an Admin, add the template download status - if (isAdmin || caller.getId() == template.getAccountId()) { - // add download status - if (templateHostRef.getDownloadState() != Status.DOWNLOADED) { - String templateStatus = "Processing"; - if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { - if (templateHostRef.getDownloadPercent() == 100) { - templateStatus = "Installing Template"; - } else { - templateStatus = templateHostRef.getDownloadPercent() + "% Downloaded"; - } - } else { - templateStatus = templateHostRef.getErrorString(); - } - templateResponse.setStatus(templateStatus); - } else if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { - templateResponse.setStatus("Download Complete"); - } else { - templateResponse.setStatus("Successfully Installed"); - } - } - - Long templateSize = templateHostRef.getSize(); - if (templateSize > 0) { - templateResponse.setSize(templateSize); - } - - templateResponse.setChecksum(template.getChecksum()); - templateResponse.setSourceTemplateId(template.getSourceTemplateId()); - - templateResponse.setChecksum(template.getChecksum()); - - templateResponse.setTemplateTag(template.getTemplateTag()); - - templateResponse.setObjectName("template"); - responses.add(templateResponse); - return responses; - } - - @Override - public List createIsoResponses(long isoId, Long zoneId, boolean readyOnly) { - - List isoResponses = new ArrayList(); - VirtualMachineTemplate iso = findTemplateById(isoId); - if (iso.getTemplateType() == TemplateType.PERHOST) { - TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); - isoResponse.setName(iso.getName()); - isoResponse.setDisplayText(iso.getDisplayText()); - isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); - isoResponse.setReady(true); - isoResponse.setBootable(iso.isBootable()); - isoResponse.setFeatured(iso.isFeatured()); - isoResponse.setCrossZones(iso.isCrossZones()); - isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setCreated(iso.getCreated()); - isoResponse.setChecksum(iso.getChecksum()); - isoResponse.setPasswordEnabled(false); - isoResponse.setDetails(iso.getDetails()); - - // add account ID and name - Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); - populateAccount(isoResponse, owner.getId()); - populateDomain(isoResponse, owner.getDomainId()); - - isoResponse.setObjectName("iso"); - isoResponses.add(isoResponse); - return isoResponses; - } else { - if (zoneId == null || zoneId == -1) { - isoResponses = createSwiftIsoResponses(iso); - if (!isoResponses.isEmpty()) { - return isoResponses; - } - List dcs = new ArrayList(); - dcs.addAll(ApiDBUtils.listZones()); - for (DataCenterVO dc : dcs) { - isoResponses.addAll(createIsoResponses(iso, dc.getId(), readyOnly)); - } - return isoResponses; - } else { - return createIsoResponses(iso, zoneId, readyOnly); - } - } - } - - private List createSwiftIsoResponses(VirtualMachineTemplate iso) { - long isoId = iso.getId(); - List isoResponses = new ArrayList(); - VMTemplateSwiftVO isoSwift = ApiDBUtils.findTemplateSwiftRef(isoId); - if (isoSwift == null) { - return isoResponses; - } - TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); - isoResponse.setName(iso.getName()); - isoResponse.setDisplayText(iso.getDisplayText()); - isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); - isoResponse.setCreated(isoSwift.getCreated()); - isoResponse.setReady(true); - isoResponse.setBootable(iso.isBootable()); - isoResponse.setFeatured(iso.isFeatured()); - isoResponse.setCrossZones(iso.isCrossZones()); - isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setChecksum(iso.getChecksum()); - isoResponse.setDetails(iso.getDetails()); - - // TODO: implement - GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); - if (os != null) { - isoResponse.setOsTypeId(os.getId()); - isoResponse.setOsTypeName(os.getDisplayName()); - } else { - isoResponse.setOsTypeId(-1L); - isoResponse.setOsTypeName(""); - } - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); - populateAccount(isoResponse, account.getId()); - populateDomain(isoResponse, account.getDomainId()); - boolean isAdmin = false; - if ((account == null) || BaseCmd.isAdmin(account.getType())) { - isAdmin = true; - } - - // If the user is an admin, add the template download status - if (isAdmin || account.getId() == iso.getAccountId()) { - // add download status - isoResponse.setStatus("Successfully Installed"); - } - Long isoSize = isoSwift.getSize(); - if (isoSize > 0) { - isoResponse.setSize(isoSize); - } - isoResponse.setObjectName("iso"); - isoResponses.add(isoResponse); - return isoResponses; - } - - @Override - public List createIsoResponses(VirtualMachineTemplate iso, long zoneId, boolean readyOnly) { - long isoId = iso.getId(); - List isoResponses = new ArrayList(); - VMTemplateHostVO isoHost = ApiDBUtils.findTemplateHostRef(isoId, zoneId, readyOnly); - if (isoHost == null) { - return isoResponses; - } - TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); - isoResponse.setName(iso.getName()); - isoResponse.setDisplayText(iso.getDisplayText()); - isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); - isoResponse.setCreated(isoHost.getCreated()); - isoResponse.setReady(isoHost.getDownloadState() == Status.DOWNLOADED); - isoResponse.setBootable(iso.isBootable()); - isoResponse.setFeatured(iso.isFeatured()); - isoResponse.setCrossZones(iso.isCrossZones()); - isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setChecksum(iso.getChecksum()); - isoResponse.setDetails(iso.getDetails()); - - // TODO: implement - GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); - if (os != null) { - isoResponse.setOsTypeId(os.getId()); - isoResponse.setOsTypeName(os.getDisplayName()); - } else { - isoResponse.setOsTypeId(-1L); - isoResponse.setOsTypeName(""); - } - - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); - populateAccount(isoResponse, account.getId()); - populateDomain(isoResponse, account.getDomainId()); - - Account caller = UserContext.current().getCaller(); - boolean isAdmin = false; - if ((caller == null) || BaseCmd.isAdmin(caller.getType())) { - isAdmin = true; - } - // Add the zone ID - DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); - isoResponse.setZoneId(zoneId); - isoResponse.setZoneName(datacenter.getName()); - - // If the user is an admin, add the template download status - if (isAdmin || caller.getId() == iso.getAccountId()) { - // add download status - if (isoHost.getDownloadState() != Status.DOWNLOADED) { - String isoStatus = "Processing"; - if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { - isoStatus = "Download Complete"; - } else if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { - if (isoHost.getDownloadPercent() == 100) { - isoStatus = "Installing ISO"; - } else { - isoStatus = isoHost.getDownloadPercent() + "% Downloaded"; - } - } else { - isoStatus = isoHost.getErrorString(); - } - isoResponse.setStatus(isoStatus); - } else { - isoResponse.setStatus("Successfully Installed"); - } - } - - Long isoSize = isoHost.getSize(); - if (isoSize > 0) { - isoResponse.setSize(isoSize); - } - - isoResponse.setObjectName("iso"); - isoResponses.add(isoResponse); - return isoResponses; - } - - @Override - public ListResponse createSecurityGroupResponses( - List networkGroups) { - List groupResultObjs = SecurityGroupResultObject - .transposeNetworkGroups(networkGroups); - - ListResponse response = new ListResponse(); - List netGrpResponses = new ArrayList(); - for (SecurityGroupResultObject networkGroup : groupResultObjs) { - SecurityGroupResponse netGrpResponse = new SecurityGroupResponse(); - netGrpResponse.setId(networkGroup.getId()); - netGrpResponse.setName(networkGroup.getName()); - netGrpResponse.setDescription(networkGroup.getDescription()); - - populateOwner(netGrpResponse, networkGroup); - - List securityGroupRules = networkGroup - .getSecurityGroupRules(); - if ((securityGroupRules != null) && !securityGroupRules.isEmpty()) { - List ingressRulesResponse = new ArrayList(); - List egressRulesResponse = new ArrayList(); - for (SecurityGroupRuleResultObject securityGroupRule : securityGroupRules) { - SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); - ruleData.setRuleId(securityGroupRule.getId()); - ruleData.setProtocol(securityGroupRule.getProtocol()); - - if ("icmp".equalsIgnoreCase(securityGroupRule.getProtocol())) { - ruleData.setIcmpType(securityGroupRule.getStartPort()); - ruleData.setIcmpCode(securityGroupRule.getEndPort()); - } else { - ruleData.setStartPort(securityGroupRule.getStartPort()); - ruleData.setEndPort(securityGroupRule.getEndPort()); - } - - if (securityGroupRule.getAllowedSecurityGroup() != null) { - ruleData.setSecurityGroupName(securityGroupRule - .getAllowedSecurityGroup()); - ruleData.setAccountName(securityGroupRule - .getAllowedSecGroupAcct()); - } else { - ruleData.setCidr(securityGroupRule - .getAllowedSourceIpCidr()); - } - - if (securityGroupRule.getRuleType() == SecurityRuleType.IngressRule) { - ruleData.setObjectName("ingressrule"); - ingressRulesResponse.add(ruleData); - } else { - ruleData.setObjectName("egressrule"); - egressRulesResponse.add(ruleData); - } - } - netGrpResponse - .setSecurityGroupIngressRules(ingressRulesResponse); - netGrpResponse.setSecurityGroupEgressRules(egressRulesResponse); - } - netGrpResponse.setObjectName("securitygroup"); - netGrpResponses.add(netGrpResponse); - } - - response.setResponses(netGrpResponses); - return response; - } - - @Override - public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { - SecurityGroupResponse response = new SecurityGroupResponse(); - - populateOwner(response, group); - - response.setDescription(group.getDescription()); - response.setId(group.getId()); - response.setName(group.getName()); - - response.setObjectName("securitygroup"); - return response; - - } - - @Override - public ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode) { - UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId); - ExtractResponse response = new ExtractResponse(); - response.setObjectName("template"); - response.setId(id); - response.setName(ApiDBUtils.findTemplateById(id).getName()); - if (zoneId != null) { - response.setZoneId(zoneId); - response.setZoneName(ApiDBUtils.findZoneById(zoneId).getName()); - } - response.setMode(mode); - response.setUploadId(uploadId); - response.setState(uploadInfo.getUploadState().toString()); - response.setAccountId(accountId); - response.setUrl(uploadInfo.getUploadUrl()); - return response; - - } - - @Override - public String toSerializedString(CreateCmdResponse response, String responseType) { - return ApiResponseSerializer.toSerializedString(response, responseType); - } - - @Override - public AsyncJobResponse createAsyncJobResponse(AsyncJob job) { - AsyncJobResponse jobResponse = new AsyncJobResponse(); - jobResponse.setAccountId(job.getAccountId()); - jobResponse.setUserId(job.getUserId()); - jobResponse.setCmd(job.getCmd()); - jobResponse.setCreated(job.getCreated()); - jobResponse.setJobId(job.getId()); - jobResponse.setJobStatus(job.getStatus()); - jobResponse.setJobProcStatus(job.getProcessStatus()); - - if (job.getInstanceType() != null && job.getInstanceId() != null) { - jobResponse.setJobInstanceType(job.getInstanceType().toString()); - jobResponse.setJobInstanceId(job.getInstanceId()); - } - jobResponse.setJobResultCode(job.getResultCode()); - - boolean savedValue = SerializationContext.current().getUuidTranslation(); - SerializationContext.current().setUuidTranslation(false); - jobResponse.setJobResult((ResponseObject) ApiSerializerHelper.fromSerializedString(job.getResult())); - SerializationContext.current().setUuidTranslation(savedValue); - - Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); - if (resultObject != null) { - Class clz = resultObject.getClass(); - if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { - jobResponse.setJobResultType("text"); - } else { - jobResponse.setJobResultType("object"); - } - } - - jobResponse.setObjectName("asyncjobs"); - return jobResponse; - } - - @Override - public List createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly) { - VolumeVO volume = null; - if (snapshotId != null) { - Snapshot snapshot = ApiDBUtils.findSnapshotById(snapshotId); - volume = findVolumeById(snapshot.getVolumeId()); - } else { - volume = findVolumeById(volumeId); - } - return createTemplateResponses(templateId, volume.getDataCenterId(), readyOnly); - } - - @Override - public List createTemplateResponses(long templateId, Long vmId) { - UserVm vm = findUserVmById(vmId); - Long hostId = (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()); - Host host = findHostById(hostId); - return createTemplateResponses(templateId, host.getDataCenterId(), true); - } - - @Override - public EventResponse createEventResponse(Event event) { - EventResponse responseEvent = new EventResponse(); - responseEvent.setCreated(event.getCreateDate()); - responseEvent.setDescription(event.getDescription()); - responseEvent.setEventType(event.getType()); - responseEvent.setId(event.getId()); - responseEvent.setLevel(event.getLevel()); - responseEvent.setParentId(event.getStartId()); - responseEvent.setState(event.getState()); - - populateOwner(responseEvent, event); - - User user = ApiDBUtils.findUserById(event.getUserId()); - if (user != null) { - responseEvent.setUsername(user.getUsername()); - } - - responseEvent.setObjectName("event"); - return responseEvent; - } - - private List sumCapacities(List hostCapacities) { - Map totalCapacityMap = new HashMap(); - Map usedCapacityMap = new HashMap(); - - Set poolIdsToIgnore = new HashSet(); - Criteria c = new Criteria(); - // TODO: implement - List allStoragePools = ApiDBUtils.searchForStoragePools(c); - for (StoragePoolVO pool : allStoragePools) { - StoragePoolType poolType = pool.getPoolType(); - if (!(poolType.isShared())) {// All the non shared storages shouldn't show up in the capacity calculation - poolIdsToIgnore.add(pool.getId()); - } - } - - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - // collect all the capacity types, sum allocated/used and sum total...get one capacity number for each - for (Capacity capacity : hostCapacities) { - - // check if zone exist - DataCenter zone = ApiDBUtils.findZoneById(capacity.getDataCenterId()); - if (zone == null) { - continue; - } - - short capacityType = capacity.getCapacityType(); - - // If local storage then ignore - if ((capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE) - && poolIdsToIgnore.contains(capacity.getHostOrPoolId())) { - continue; - } - - String key = capacity.getCapacityType() + "_" + capacity.getDataCenterId(); - String keyForPodTotal = key + "_-1"; - - boolean sumPodCapacity = false; - if (capacity.getPodId() != null) { - key += "_" + capacity.getPodId(); - sumPodCapacity = true; - } - - Long totalCapacity = totalCapacityMap.get(key); - Long usedCapacity = usedCapacityMap.get(key); - - // reset overprovisioning factor to 1 - float overprovisioningFactor = 1; - if (capacityType == Capacity.CAPACITY_TYPE_CPU) { - overprovisioningFactor = cpuOverprovisioningFactor; - } - - if (totalCapacity == null) { - totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)); - } else { - totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)) + totalCapacity; - } - - if (usedCapacity == null) { - usedCapacity = new Long(capacity.getUsedCapacity()); - } else { - usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); - } - - if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved - // Capacity - // accounts -// for - // stopped -// vms - // that -// have been - // stopped -// within - // an -// interval - usedCapacity += capacity.getReservedCapacity(); - } - - totalCapacityMap.put(key, totalCapacity); - usedCapacityMap.put(key, usedCapacity); - - if (sumPodCapacity) { - totalCapacity = totalCapacityMap.get(keyForPodTotal); - usedCapacity = usedCapacityMap.get(keyForPodTotal); - - overprovisioningFactor = 1; - if (capacityType == Capacity.CAPACITY_TYPE_CPU) { - overprovisioningFactor = cpuOverprovisioningFactor; - } - - if (totalCapacity == null) { - totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)); - } else { - totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)) + totalCapacity; - } - - if (usedCapacity == null) { - usedCapacity = new Long(capacity.getUsedCapacity()); - } else { - usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); - } - - if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved - // Capacity - // accounts - // for - // stopped - // vms -// that - // have -// been - // stopped - // within -// an - // interval - usedCapacity += capacity.getReservedCapacity(); - } - - totalCapacityMap.put(keyForPodTotal, totalCapacity); - usedCapacityMap.put(keyForPodTotal, usedCapacity); - } - } - - List summedCapacities = new ArrayList(); - for (String key : totalCapacityMap.keySet()) { - CapacityVO summedCapacity = new CapacityVO(); - - StringTokenizer st = new StringTokenizer(key, "_"); - summedCapacity.setCapacityType(Short.parseShort(st.nextToken())); - summedCapacity.setDataCenterId(Long.parseLong(st.nextToken())); - if (st.hasMoreTokens()) { - summedCapacity.setPodId(Long.parseLong(st.nextToken())); - } - - summedCapacity.setTotalCapacity(totalCapacityMap.get(key)); - summedCapacity.setUsedCapacity(usedCapacityMap.get(key)); - - summedCapacities.add(summedCapacity); - } - return summedCapacities; - } - - @Override - public List createCapacityResponse(List result, DecimalFormat format) { - List capacityResponses = new ArrayList(); - - for (Capacity summedCapacity : result) { - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityTotal(summedCapacity.getTotalCapacity()); - capacityResponse.setCapacityType(summedCapacity.getCapacityType()); - capacityResponse.setCapacityUsed(summedCapacity.getUsedCapacity()); - if (summedCapacity.getPodId() != null) { - capacityResponse.setPodId(summedCapacity.getPodId()); - HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); - if (pod != null) { - capacityResponse.setPodName(pod.getName()); - } - } - if (summedCapacity.getClusterId() != null) { - capacityResponse.setClusterId(summedCapacity.getClusterId()); - ClusterVO cluster = ApiDBUtils.findClusterById(summedCapacity.getClusterId()); - if (cluster != null) { - capacityResponse.setClusterName(cluster.getName()); - if (summedCapacity.getPodId() == null) { - long podId = cluster.getPodId(); - capacityResponse.setPodId(podId); - capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName()); - } - } - } - capacityResponse.setZoneId(summedCapacity.getDataCenterId()); - capacityResponse.setZoneName(ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()).getName()); - if (summedCapacity.getUsedPercentage() != null){ - capacityResponse.setPercentUsed(format.format(summedCapacity.getUsedPercentage() * 100f)); - } else if (summedCapacity.getTotalCapacity() != 0) { - capacityResponse.setPercentUsed(format.format((float) summedCapacity.getUsedCapacity() / (float) summedCapacity.getTotalCapacity() * 100f)); - } else { - capacityResponse.setPercentUsed(format.format(0L)); - } - - capacityResponse.setObjectName("capacity"); - capacityResponses.add(capacityResponse); - } - - return capacityResponses; - } - - @Override - public TemplatePermissionsResponse createTemplatePermissionsResponse(List accountNames, Long id, boolean isAdmin) { - Long templateOwnerDomain = null; - VirtualMachineTemplate template = ApiDBUtils.findTemplateById(id); - Account templateOwner = ApiDBUtils.findAccountById(template.getAccountId()); - if (isAdmin) { - // FIXME: we have just template id and need to get template owner from that - if (templateOwner != null) { - templateOwnerDomain = templateOwner.getDomainId(); - } - } - - TemplatePermissionsResponse response = new TemplatePermissionsResponse(); - response.setId(template.getId()); - response.setPublicTemplate(template.isPublicTemplate()); - if (isAdmin && (templateOwnerDomain != null)) { - response.setDomainId(templateOwnerDomain); - } - - // Set accounts - List projectIds = new ArrayList(); - List regularAccounts = new ArrayList(); - for (String accountName : accountNames) { - Account account = ApiDBUtils.findAccountByNameDomain(accountName, templateOwner.getDomainId()); - if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) { - regularAccounts.add(accountName); - } else { - // convert account to projectIds - Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); - - if (project.getUuid() != null && !project.getUuid().isEmpty()) - projectIds.add(project.getUuid()); - else - projectIds.add(String.valueOf(project.getId())); - } - } - - if (!projectIds.isEmpty()) { - response.setProjectIds(projectIds); - } - - if (!regularAccounts.isEmpty()) { - response.setAccountNames(regularAccounts); - } - - response.setObjectName("templatepermission"); - return response; - } - - @Override - public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) { - AsyncJob result = ApiDBUtils._asyncMgr.queryAsyncJobResult(cmd); - return createAsyncJobResponse(result); - } - - @Override - public SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List securityRules) { - SecurityGroupResponse response = new SecurityGroupResponse(); - Map securiytGroupAccounts = new HashMap(); - Map allowedSecurityGroups = new HashMap(); - Map allowedSecuriytGroupAccounts = new HashMap(); - - if ((securityRules != null) && !securityRules.isEmpty()) { - SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(securityRules.get(0).getSecurityGroupId()); - response.setId(securityGroup.getId()); - response.setName(securityGroup.getName()); - response.setDescription(securityGroup.getDescription()); - - Account account = securiytGroupAccounts.get(securityGroup.getAccountId()); - - if (account == null) { - account = ApiDBUtils.findAccountById(securityGroup.getAccountId()); - securiytGroupAccounts.put(securityGroup.getAccountId(), account); - } - - populateAccount(response, account.getId()); - populateDomain(response, account.getDomainId()); - - List egressResponses = new ArrayList(); - List ingressResponses = new ArrayList(); - for (SecurityRule securityRule : securityRules) { - SecurityGroupRuleResponse securityGroupData = new SecurityGroupRuleResponse(); - - securityGroupData.setRuleId(securityRule.getId()); - securityGroupData.setProtocol(securityRule.getProtocol()); - if ("icmp".equalsIgnoreCase(securityRule.getProtocol())) { - securityGroupData.setIcmpType(securityRule.getStartPort()); - securityGroupData.setIcmpCode(securityRule.getEndPort()); - } else { - securityGroupData.setStartPort(securityRule.getStartPort()); - securityGroupData.setEndPort(securityRule.getEndPort()); - } - - Long allowedSecurityGroupId = securityRule.getAllowedNetworkId(); - if (allowedSecurityGroupId != null) { - SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId); - if (allowedSecurityGroup == null) { - allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId); - allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup); - } - - securityGroupData.setSecurityGroupName(allowedSecurityGroup.getName()); - - Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId()); - if (allowedAccount == null) { - allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId()); - allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount); - } - - securityGroupData.setAccountName(allowedAccount.getAccountName()); - } else { - securityGroupData.setCidr(securityRule.getAllowedSourceIpCidr()); - } - if (securityRule.getRuleType() == SecurityRuleType.IngressRule) { - securityGroupData.setObjectName("ingressrule"); - ingressResponses.add(securityGroupData); - } else { - securityGroupData.setObjectName("egressrule"); - egressResponses.add(securityGroupData); - } - - } - response.setSecurityGroupIngressRules(ingressResponses); - response.setSecurityGroupEgressRules(egressResponses); - response.setObjectName("securitygroup"); - - } - return response; - } - - @Override - public NetworkOfferingResponse createNetworkOfferingResponse(NetworkOffering offering) { - NetworkOfferingResponse response = new NetworkOfferingResponse(); - response.setId(offering.getId()); - response.setName(offering.getName()); - response.setDisplayText(offering.getDisplayText()); - response.setTags(offering.getTags()); - response.setTrafficType(offering.getTrafficType().toString()); - response.setIsDefault(offering.isDefault()); - response.setSpecifyVlan(offering.getSpecifyVlan()); - response.setConserveMode(offering.isConserveMode()); - response.setSpecifyIpRanges(offering.getSpecifyIpRanges()); - response.setAvailability(offering.getAvailability().toString()); - response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); - if (offering.getServiceOfferingId() != null) { - response.setServiceOfferingId(offering.getServiceOfferingId()); - } else { - response.setServiceOfferingId(ApiDBUtils.findDefaultRouterServiceOffering()); - } - if (offering.getGuestType() != null) { - response.setGuestIpType(offering.getGuestType().toString()); - } - - response.setState(offering.getState().name()); - - Map> serviceProviderMap = ApiDBUtils.listNetworkOfferingServices(offering.getId()); - List serviceResponses = new ArrayList(); - for (Service service : serviceProviderMap.keySet()) { - ServiceResponse svcRsp = new ServiceResponse(); - // skip gateway service - if (service == Service.Gateway) { - continue; - } - svcRsp.setName(service.getName()); - List providers = new ArrayList(); - for (Provider provider : serviceProviderMap.get(service)) { - if (provider != null) { - ProviderResponse providerRsp = new ProviderResponse(); - providerRsp.setName(provider.getName()); - providers.add(providerRsp); - } - } - svcRsp.setProviders(providers); - - if (Service.Lb == service) { - List lbCapResponse = new ArrayList(); - - CapabilityResponse lbIsoaltion = new CapabilityResponse(); - lbIsoaltion.setName(Capability.SupportedLBIsolation.getName()); - lbIsoaltion.setValue(offering.getDedicatedLB() ? "dedicated" : "shared"); - lbCapResponse.add(lbIsoaltion); - - CapabilityResponse eLb = new CapabilityResponse(); - eLb.setName(Capability.ElasticLb.getName()); - eLb.setValue(offering.getElasticLb() ? "true" : "false"); - lbCapResponse.add(eLb); - - svcRsp.setCapabilities(lbCapResponse); - } else if (Service.SourceNat == service) { - List capabilities = new ArrayList(); - CapabilityResponse sharedSourceNat = new CapabilityResponse(); - sharedSourceNat.setName(Capability.SupportedSourceNatTypes.getName()); - sharedSourceNat.setValue(offering.getSharedSourceNat() ? "perzone" : "peraccount"); - capabilities.add(sharedSourceNat); - - CapabilityResponse redundantRouter = new CapabilityResponse(); - redundantRouter.setName(Capability.RedundantRouter.getName()); - redundantRouter.setValue(offering.getRedundantRouter() ? "true" : "false"); - capabilities.add(redundantRouter); - - svcRsp.setCapabilities(capabilities); - } else if (service == Service.StaticNat) { - List staticNatCapResponse = new ArrayList(); - - CapabilityResponse eIp = new CapabilityResponse(); - eIp.setName(Capability.ElasticIp.getName()); - eIp.setValue(offering.getElasticLb() ? "true" : "false"); - staticNatCapResponse.add(eIp); - - svcRsp.setCapabilities(staticNatCapResponse); - } - - serviceResponses.add(svcRsp); - } - response.setServices(serviceResponses); - response.setObjectName("networkoffering"); - return response; - } - - @Override - public NetworkResponse createNetworkResponse(Network network) { - // need to get network profile in order to retrieve dns information from there - NetworkProfile profile = ApiDBUtils.getNetworkProfile(network.getId()); - NetworkResponse response = new NetworkResponse(); - response.setId(network.getId()); - response.setName(network.getName()); - response.setDisplaytext(network.getDisplayText()); - if (network.getBroadcastDomainType() != null) { - response.setBroadcastDomainType(network.getBroadcastDomainType().toString()); - } - - if (network.getTrafficType() != null) { - response.setTrafficType(network.getTrafficType().name()); - } - - if (network.getGuestType() != null) { - response.setType(network.getGuestType().toString()); - } - - response.setGateway(network.getGateway()); - - // FIXME - either set netmask or cidr - response.setCidr(network.getCidr()); - if (network.getCidr() != null) { - response.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); - } - - // FIXME - either set broadcast URI or vlan - if (network.getBroadcastUri() != null) { - String broadcastUri = network.getBroadcastUri().toString(); - response.setBroadcastUri(broadcastUri); - String vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); - response.setVlan(vlan); - } - - DataCenter zone = ApiDBUtils.findZoneById(network.getDataCenterId()); - response.setZoneId(network.getDataCenterId()); - response.setZoneName(zone.getName()); - response.setPhysicalNetworkId(network.getPhysicalNetworkId()); - - // populate network offering information - NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); - if (networkOffering != null) { - response.setNetworkOfferingId(networkOffering.getId()); - response.setNetworkOfferingName(networkOffering.getName()); - response.setNetworkOfferingDisplayText(networkOffering.getDisplayText()); - response.setIsSystem(networkOffering.isSystemOnly()); - response.setNetworkOfferingAvailability(networkOffering.getAvailability().toString()); - } - - if (network.getAclType() != null) { - response.setAclType(network.getAclType().toString()); - } - response.setState(network.getState().toString()); - response.setRestartRequired(network.isRestartRequired()); - response.setRelated(network.getRelated()); - response.setNetworkDomain(network.getNetworkDomain()); - - response.setDns1(profile.getDns1()); - response.setDns2(profile.getDns2()); - // populate capability - Map> serviceCapabilitiesMap = ApiDBUtils.getNetworkCapabilities(network.getId(), network.getDataCenterId()); - List serviceResponses = new ArrayList(); - if (serviceCapabilitiesMap != null) { - for (Service service : serviceCapabilitiesMap.keySet()) { - ServiceResponse serviceResponse = new ServiceResponse(); - // skip gateway service - if (service == Service.Gateway) { - continue; - } - serviceResponse.setName(service.getName()); - - // set list of capabilities for the service - List capabilityResponses = new ArrayList(); - Map serviceCapabilities = serviceCapabilitiesMap.get(service); - if (serviceCapabilities != null) { - for (Capability capability : serviceCapabilities.keySet()) { - CapabilityResponse capabilityResponse = new CapabilityResponse(); - String capabilityValue = serviceCapabilities.get(capability); - capabilityResponse.setName(capability.getName()); - capabilityResponse.setValue(capabilityValue); - capabilityResponse.setObjectName("capability"); - capabilityResponses.add(capabilityResponse); - } - serviceResponse.setCapabilities(capabilityResponses); - } - - serviceResponse.setObjectName("service"); - serviceResponses.add(serviceResponse); - } - } - response.setServices(serviceResponses); - - if (network.getAclType() == null || network.getAclType() == ACLType.Account) { - populateOwner(response, network); - } else { - // get domain from network_domain table - Pair domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId()); - response.setDomainId(domainNetworkDetails.first()); - response.setSubdomainAccess(domainNetworkDetails.second()); - } - - Long dedicatedDomainId = ApiDBUtils.getDedicatedNetworkDomain(network.getId()); - if (dedicatedDomainId != null) { - Domain domain = ApiDBUtils.findDomainById(dedicatedDomainId); - response.setDomainId(dedicatedDomainId); - response.setDomainName(domain.getName()); - } - - response.setSpecifyIpRanges(network.getSpecifyIpRanges()); - - response.setObjectName("network"); - return response; - } - - @Override - public Long getSecurityGroupId(String groupName, long accountId) { - SecurityGroup sg = ApiDBUtils.getSecurityGroup(groupName, accountId); - if (sg == null) { - return null; - } else { - return sg.getId(); - } - } - - @Override - public ProjectResponse createProjectResponse(Project project) { - ProjectResponse response = new ProjectResponse(); - response.setId(project.getId()); - response.setName(project.getName()); - response.setDisplaytext(project.getDisplayText()); - response.setState(project.getState().toString()); - - Domain domain = ApiDBUtils.findDomainById(project.getDomainId()); - response.setDomainId(domain.getId()); - response.setDomain(domain.getName()); - - response.setOwner(ApiDBUtils.getProjectOwner(project.getId()).getAccountName()); - - response.setObjectName("project"); - return response; - } - - @Override - public FirewallResponse createFirewallResponse(FirewallRule fwRule) { - FirewallResponse response = new FirewallResponse(); - - response.setId(fwRule.getId()); - response.setProtocol(fwRule.getProtocol()); - if (fwRule.getSourcePortStart() != null) { - response.setStartPort(Integer.toString(fwRule.getSourcePortStart())); - } - - if (fwRule.getSourcePortEnd() != null) { - response.setEndPort(Integer.toString(fwRule.getSourcePortEnd())); - } - - List cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId()); - response.setCidrList(StringUtils.join(cidrs, ",")); - - IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); - response.setPublicIpAddressId(ip.getId()); - response.setPublicIpAddress(ip.getAddress().addr()); - - FirewallRule.State state = fwRule.getState(); - String stateToSet = state.toString(); - if (state.equals(FirewallRule.State.Revoke)) { - stateToSet = "Deleting"; - } - - response.setIcmpCode(fwRule.getIcmpCode()); - response.setIcmpType(fwRule.getIcmpType()); - - response.setState(stateToSet); - response.setObjectName("firewallrule"); - return response; - } - - public UserVmData newUserVmData(UserVm userVm) { - UserVmData userVmData = new UserVmData(); - userVmData.setId(userVm.getId()); - userVmData.setName(userVm.getHostName()); - userVmData.setCreated(userVm.getCreated()); - userVmData.setGuestOsId(userVm.getGuestOSId()); - userVmData.setHaEnable(userVm.isHaEnabled()); - if (userVm.getState() != null) { - userVmData.setState(userVm.getState().toString()); - } - if (userVm.getDisplayName() != null) { - userVmData.setDisplayName(userVm.getDisplayName()); - } else { - userVmData.setDisplayName(userVm.getHostName()); - } - userVmData.setInstanceName(userVm.getInstanceName()); - - userVmData.setDomainId(userVm.getDomainId()); - - Account caller = UserContext.current().getCaller(); - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - if (userVm.getHypervisorType() != null) { - userVmData.setHypervisor(userVm.getHypervisorType().toString()); - } - } - - if (userVm.getPassword() != null) { - userVmData.setPassword(userVm.getPassword()); - } - return userVmData; - } - - public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin) { - UserVmResponse userVmResponse = new UserVmResponse(); - - userVmResponse.setHypervisor(userVmData.getHypervisor()); - userVmResponse.setId(userVmData.getId()); - userVmResponse.setName(userVmData.getName()); - - userVmResponse.setDisplayName(userVmData.getDisplayName()); - - populateAccount(userVmResponse, userVmData.getAccountId()); - populateDomain(userVmResponse, userVmData.getDomainId()); - - userVmResponse.setCreated(userVmData.getCreated()); - userVmResponse.setState(userVmData.getState()); - userVmResponse.setHaEnable(userVmData.getHaEnable()); - userVmResponse.setGroupId(userVmData.getGroupId()); - userVmResponse.setGroup(userVmData.getGroup()); - userVmResponse.setZoneId(userVmData.getZoneId()); - userVmResponse.setZoneName(userVmData.getZoneName()); - if (caller_is_admin) { - userVmResponse.setInstanceName(userVmData.getInstanceName()); - userVmResponse.setHostId(userVmData.getHostId()); - userVmResponse.setHostName(userVmData.getHostName()); - } - userVmResponse.setTemplateId(userVmData.getTemplateId()); - userVmResponse.setTemplateName(userVmData.getTemplateName()); - userVmResponse.setTemplateDisplayText(userVmData.getTemplateDisplayText()); - userVmResponse.setPasswordEnabled(userVmData.getPasswordEnabled()); - userVmResponse.setIsoId(userVmData.getIsoId()); - userVmResponse.setIsoName(userVmData.getIsoName()); - userVmResponse.setIsoDisplayText(userVmData.getIsoDisplayText()); - userVmResponse.setServiceOfferingId(userVmData.getServiceOfferingId()); - userVmResponse.setServiceOfferingName(userVmData.getServiceOfferingName()); - userVmResponse.setCpuNumber(userVmData.getCpuNumber()); - userVmResponse.setCpuSpeed(userVmData.getCpuSpeed()); - userVmResponse.setMemory(userVmData.getMemory()); - userVmResponse.setCpuUsed(userVmData.getCpuUsed()); - userVmResponse.setNetworkKbsRead(userVmData.getNetworkKbsRead()); - userVmResponse.setNetworkKbsWrite(userVmData.getNetworkKbsWrite()); - userVmResponse.setGuestOsId(userVmData.getGuestOsId()); - userVmResponse.setRootDeviceId(userVmData.getRootDeviceId()); - userVmResponse.setRootDeviceType(userVmData.getRootDeviceType()); - userVmResponse.setPassword(userVmData.getPassword()); - userVmResponse.setJobId(userVmData.getJobId()); - userVmResponse.setJobStatus(userVmData.getJobStatus()); - userVmResponse.setForVirtualNetwork(userVmData.getForVirtualNetwork()); - - Set securityGroupResponse = new HashSet(); - for (SecurityGroupData sgd : userVmData.getSecurityGroupList()) { - if (sgd.getId() != null) { - SecurityGroupResponse sgr = new SecurityGroupResponse(); - sgr.setId(sgd.getId()); - sgr.setName(sgd.getName()); - sgr.setDescription(sgd.getDescription()); - - Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); - if (account != null) { - populateAccount(sgr, account.getId()); - populateDomain(sgr, account.getDomainId()); - } - - sgr.setObjectName(sgd.getObjectName()); - securityGroupResponse.add(sgr); - } - } - userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse)); - - Set nicResponses = new HashSet(); - for (NicData nd : userVmData.getNics()) { - NicResponse nr = new NicResponse(); - nr.setId(nd.getId()); - nr.setNetworkid(nd.getNetworkid()); - nr.setNetmask(nd.getNetmask()); - nr.setGateway(nd.getGateway()); - nr.setIpaddress(nd.getIpaddress()); - nr.setIsolationUri(nd.getIsolationUri()); - nr.setBroadcastUri(nd.getBroadcastUri()); - nr.setTrafficType(nd.getTrafficType()); - nr.setType(nd.getType()); - nr.setIsDefault(nd.getIsDefault()); - nr.setMacAddress(nd.getMacAddress()); - nr.setObjectName(nd.getObjectName()); - nicResponses.add(nr); - } - userVmResponse.setNics(new ArrayList(nicResponses)); - userVmResponse.setPublicIpId(userVmData.getPublicIpId()); - userVmResponse.setPublicIp(userVmData.getPublicIp()); - - return userVmResponse; - } - - @Override - public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities) { - HypervisorCapabilitiesResponse hpvCapabilitiesResponse = new HypervisorCapabilitiesResponse(); - hpvCapabilitiesResponse.setId(hpvCapabilities.getId()); - hpvCapabilitiesResponse.setHypervisor(hpvCapabilities.getHypervisorType()); - hpvCapabilitiesResponse.setHypervisorVersion(hpvCapabilities.getHypervisorVersion()); - hpvCapabilitiesResponse.setIsSecurityGroupEnabled(hpvCapabilities.isSecurityGroupEnabled()); - hpvCapabilitiesResponse.setMaxGuestsLimit(hpvCapabilities.getMaxGuestsLimit()); - return hpvCapabilitiesResponse; - } - - private void populateOwner(ControlledEntityResponse response, ControlledEntity object) { - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId()); - - if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - // find the project - Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); - response.setProjectId(project.getId()); - response.setProjectName(project.getName()); - } else { - response.setAccountName(account.getAccountName()); - } - - Domain domain = ApiDBUtils.findDomainById(object.getDomainId()); - response.setDomainId(domain.getId()); - response.setDomainName(domain.getName()); - } - - private void populateAccount(ControlledEntityResponse response, long accountId) { - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId); - if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - // find the project - Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); - response.setProjectId(project.getId()); - response.setProjectName(project.getName()); - } else { - response.setAccountName(account.getAccountName()); - } - } - - private void populateDomain(ControlledEntityResponse response, long domainId) { - Domain domain = ApiDBUtils.findDomainById(domainId); - - response.setDomainId(domain.getId()); - response.setDomainName(domain.getName()); - } - - @Override - public ProjectAccountResponse createProjectAccountResponse(ProjectAccount projectAccount) { - Account account = ApiDBUtils.findAccountById(projectAccount.getAccountId()); - ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); - - long projectId = projectAccount.getProjectId(); - projectAccountResponse.setProjectId(projectId); - projectAccountResponse.setProjectName(ApiDBUtils.findProjectById(projectId).getName()); - - projectAccountResponse.setId(account.getId()); - projectAccountResponse.setAccountName(account.getAccountName()); - projectAccountResponse.setAccountType(account.getType()); - projectAccountResponse.setRole(projectAccount.getAccountRole().toString()); - populateDomain(projectAccountResponse, account.getDomainId()); - - // add all the users for an account as part of the response obj - List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); - List userResponseList = new ArrayList(); - for (UserVO user : usersForAccount) { - UserResponse userResponse = createUserResponse(user); - userResponseList.add(userResponse); - } - - projectAccountResponse.setUsers(userResponseList); - projectAccountResponse.setObjectName("projectaccount"); - - return projectAccountResponse; - } - - @Override - public ProjectInvitationResponse createProjectInvitationResponse(ProjectInvitation invite) { - ProjectInvitationResponse response = new ProjectInvitationResponse(); - response.setId(invite.getId()); - response.setProjectId(invite.getProjectId()); - response.setProjectName(ApiDBUtils.findProjectById(invite.getProjectId()).getName()); - response.setInvitationState(invite.getState().toString()); - - if (invite.getForAccountId() != null) { - Account account = ApiDBUtils.findAccountById(invite.getForAccountId()); - response.setAccountName(account.getAccountName()); - - } else { - response.setEmail(invite.getEmail()); - } - - populateDomain(response, invite.getInDomainId()); - - response.setObjectName("projectinvitation"); - return response; - } - - @Override - public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) { - SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse(); - vmResponse.setId(vm.getId()); - vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); - vmResponse.setName(vm.getHostName()); - if (vm.getHostId() != null) { - vmResponse.setHostId(vm.getHostId()); - } - if (vm.getState() != null) { - vmResponse.setState(vm.getState().toString()); - } - if (vm.getType() == Type.DomainRouter) { - VirtualRouter router = (VirtualRouter) vm; - if (router.getRole() != null) { - vmResponse.setRole(router.getRole().toString()); - } - } - vmResponse.setObjectName("systemvminstance"); - return vmResponse; - } - - @Override - public PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result) { - PhysicalNetworkResponse response = new PhysicalNetworkResponse(); - - response.setZoneId(result.getDataCenterId()); - response.setNetworkSpeed(result.getSpeed()); - response.setVlan(result.getVnet()); - response.setDomainId(result.getDomainId()); - response.setId(result.getUuid()); - if (result.getBroadcastDomainRange() != null) { - response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString()); - } - response.setIsolationMethods(result.getIsolationMethods()); - response.setTags(result.getTags()); - if (result.getState() != null) { - response.setState(result.getState().toString()); - } - - response.setName(result.getName()); - - response.setObjectName("physicalnetwork"); - return response; - } - - @Override - public ServiceResponse createNetworkServiceResponse(Service service) { - ServiceResponse response = new ServiceResponse(); - response.setName(service.getName()); - - // set list of capabilities required for the service - List capabilityResponses = new ArrayList(); - Capability[] capabilities = service.getCapabilities(); - for (Capability cap : capabilities) { - CapabilityResponse capabilityResponse = new CapabilityResponse(); - capabilityResponse.setName(cap.getName()); - capabilityResponse.setObjectName("capability"); - if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) || - cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) || - cap.getName().equals(Capability.RedundantRouter.getName())) { - capabilityResponse.setCanChoose(true); - } else { - capabilityResponse.setCanChoose(false); - } - capabilityResponses.add(capabilityResponse); - } - response.setCapabilities(capabilityResponses); - - // set list of providers providing this service - List serviceProviders = ApiDBUtils.getProvidersForService(service); - List serviceProvidersResponses = new ArrayList(); - for (Network.Provider serviceProvider : serviceProviders) { - // return only Virtual Router/JuniperSRX as a provider for the firewall - if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX)) { - continue; - } - - ProviderResponse serviceProviderResponse = createServiceProviderResponse(serviceProvider); - serviceProvidersResponses.add(serviceProviderResponse); - } - response.setProviders(serviceProvidersResponses); - - response.setObjectName("networkservice"); - return response; - - } - - private ProviderResponse createServiceProviderResponse(Provider serviceProvider) { - ProviderResponse response = new ProviderResponse(); - response.setName(serviceProvider.getName()); - boolean canEnableIndividualServices = ApiDBUtils.canElementEnableIndividualServices(serviceProvider); - response.setCanEnableIndividualServices(canEnableIndividualServices); - return response; - } - - @Override - public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result) { - ProviderResponse response = new ProviderResponse(); - response.setId(result.getUuid()); - response.setName(result.getProviderName()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId()); - response.setState(result.getState().toString()); - - // set enabled services - List services = new ArrayList(); - for (Service service : result.getEnabledServices()) { - services.add(service.getName()); - } - response.setServices(services); - - response.setObjectName("networkserviceprovider"); - return response; - } - - @Override - public TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType result) { - TrafficTypeResponse response = new TrafficTypeResponse(); - response.setId(result.getUuid()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - response.setTrafficType(result.getTrafficType().toString()); - response.setXenLabel(result.getXenNetworkLabel()); - response.setKvmLabel(result.getKvmNetworkLabel()); - response.setVmwareLabel(result.getVmwareNetworkLabel()); - - response.setObjectName("traffictype"); - return response; - } - - @Override - public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { - VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); - response.setId(result.getId()); - response.setNspId(result.getNspId()); - response.setEnabled(result.isEnabled()); - - response.setObjectName("virtualrouterelement"); - return response; - } - - @Override - public LBStickinessResponse createLBStickinessPolicyResponse( - StickinessPolicy stickinessPolicy, LoadBalancer lb) { - LBStickinessResponse spResponse = new LBStickinessResponse(); - - spResponse.setlbRuleId(lb.getId()); - Account accountTemp = ApiDBUtils.findAccountById(lb.getAccountId()); - if (accountTemp != null) { - spResponse.setAccountName(accountTemp.getAccountName()); - spResponse.setDomainId(accountTemp.getDomainId()); - spResponse.setDomainName(ApiDBUtils.findDomainById( - accountTemp.getDomainId()).getName()); - } - - List responses = new ArrayList(); - LBStickinessPolicyResponse ruleResponse = new LBStickinessPolicyResponse( - stickinessPolicy); - responses.add(ruleResponse); - - spResponse.setRules(responses); - - spResponse.setObjectName("stickinesspolicies"); - return spResponse; - } - - @Override - public LBStickinessResponse createLBStickinessPolicyResponse( - List stickinessPolicies, LoadBalancer lb) { - LBStickinessResponse spResponse = new LBStickinessResponse(); - - if (lb == null) - return spResponse; - spResponse.setlbRuleId(lb.getId()); - Account account = ApiDBUtils.findAccountById(lb.getAccountId()); - if (account != null) { - spResponse.setAccountName(account.getAccountName()); - spResponse.setDomainId(account.getDomainId()); - spResponse.setDomainName(ApiDBUtils.findDomainById( - account.getDomainId()).getName()); - } - - List responses = new ArrayList(); - for (StickinessPolicy stickinessPolicy : stickinessPolicies) { - LBStickinessPolicyResponse ruleResponse = new LBStickinessPolicyResponse(stickinessPolicy); - responses.add(ruleResponse); - } - spResponse.setRules(responses); - - spResponse.setObjectName("stickinesspolicies"); - return spResponse; - } - - @Override - public LDAPConfigResponse createLDAPConfigResponse(String hostname, - Integer port, Boolean useSSL, String queryFilter, - String searchBase, String bindDN) { - LDAPConfigResponse lr = new LDAPConfigResponse(); - lr.setHostname(hostname); - lr.setPort(port.toString()); - lr.setUseSSL(useSSL.toString()); - lr.setQueryFilter(queryFilter); - lr.setBindDN(bindDN); - lr.setSearchBase(searchBase); - lr.setObjectName("ldapconfig"); - return lr; - } - - @Override - public StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result) { - StorageNetworkIpRangeResponse response = new StorageNetworkIpRangeResponse(); - response.setUuid(result.getUuid()); - response.setVlan(result.getVlan()); - response.setEndIp(result.getEndIp()); - response.setStartIp(result.getStartIp()); - response.setPodUuid(result.getPodUuid()); - response.setZoneUuid(result.getZoneUuid()); - response.setNetworkUuid(result.getNetworkUuid()); - response.setNetmask(result.getNetmask()); - response.setGateway(result.getGateway()); + /*In basic zone, public ip has TrafficType.Guest*/ + vmResponse.setPublicIp(singleNicProfile.getIp4Address()); + vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); + vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); + vmResponse.setGateway(singleNicProfile.getGateway()); + } + } + } + } + vmResponse.setObjectName("systemvm"); + return vmResponse; + } + + @Override + public Host findHostById(Long hostId) { + return ApiDBUtils.findHostById(hostId); + } + + @Override + public User findUserById(Long userId) { + return ApiDBUtils.findUserById(userId); + } + + @Override + public UserVm findUserVmById(Long vmId) { + return ApiDBUtils.findUserVmById(vmId); + + } + + @Override + public VolumeVO findVolumeById(Long volumeId) { + return ApiDBUtils.findVolumeById(volumeId); + } + + @Override + public Account findAccountByNameDomain(String accountName, Long domainId) { + return ApiDBUtils.findAccountByNameDomain(accountName, domainId); + } + + @Override + public VirtualMachineTemplate findTemplateById(Long templateId) { + return ApiDBUtils.findTemplateById(templateId); + } + + @Override + public VpnUsersResponse createVpnUserResponse(VpnUser vpnUser) { + VpnUsersResponse vpnResponse = new VpnUsersResponse(); + vpnResponse.setId(vpnUser.getId()); + vpnResponse.setUserName(vpnUser.getUsername()); + + populateOwner(vpnResponse, vpnUser); + + vpnResponse.setObjectName("vpnuser"); + return vpnResponse; + } + + @Override + public RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn) { + RemoteAccessVpnResponse vpnResponse = new RemoteAccessVpnResponse(); + vpnResponse.setPublicIpId(vpn.getServerAddressId()); + vpnResponse.setPublicIp(ApiDBUtils.findIpAddressById(vpn.getServerAddressId()).getAddress().addr()); + vpnResponse.setIpRange(vpn.getIpRange()); + vpnResponse.setPresharedKey(vpn.getIpsecPresharedKey()); + vpnResponse.setDomainId(vpn.getDomainId()); + + populateOwner(vpnResponse, vpn); + + vpnResponse.setState(vpn.getState().toString()); + vpnResponse.setObjectName("remoteaccessvpn"); + + return vpnResponse; + } + + @Override + public TemplateResponse createIsoResponse(VirtualMachineTemplate result) { + TemplateResponse response = new TemplateResponse(); + response.setId(result.getId()); + response.setName(result.getName()); + response.setDisplayText(result.getDisplayText()); + response.setPublic(result.isPublicTemplate()); + response.setCreated(result.getCreated()); + response.setFormat(result.getFormat()); + response.setOsTypeId(result.getGuestOSId()); + response.setOsTypeName(ApiDBUtils.findGuestOSById(result.getGuestOSId()).getDisplayName()); + response.setDetails(result.getDetails()); + Account caller = UserContext.current().getCaller(); + + if (result.getFormat() == ImageFormat.ISO) { // Templates are always bootable + response.setBootable(result.isBootable()); + } else if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + response.setHypervisor(result.getHypervisorType().toString());// hypervisors are associated with templates + } + + // add account ID and name + Account owner = ApiDBUtils.findAccountById(result.getAccountId()); + populateAccount(response, owner.getId()); + populateDomain(response, owner.getDomainId()); + + response.setObjectName("iso"); + return response; + } + + @Override + public List createTemplateResponses(long templateId, Long zoneId, boolean readyOnly) { + if (zoneId == null || zoneId == -1) { + List responses = new ArrayList(); + List dcs = new ArrayList(); + responses = createSwiftTemplateResponses(templateId); + if (!responses.isEmpty()) { + return responses; + } + dcs.addAll(ApiDBUtils.listZones()); + for (DataCenterVO dc : dcs) { + responses.addAll(createTemplateResponses(templateId, dc.getId(), readyOnly)); + } + return responses; + } else { + return createTemplateResponses(templateId, zoneId.longValue(), readyOnly); + } + } + + private List createSwiftTemplateResponses(long templateId) { + VirtualMachineTemplate template = findTemplateById(templateId); + List responses = new ArrayList(); + VMTemplateSwiftVO templateSwiftRef = ApiDBUtils.findTemplateSwiftRef(templateId); + if (templateSwiftRef == null) { + return responses; + } + + TemplateResponse templateResponse = new TemplateResponse(); + templateResponse.setId(template.getId()); + templateResponse.setName(template.getName()); + templateResponse.setDisplayText(template.getDisplayText()); + templateResponse.setPublic(template.isPublicTemplate()); + templateResponse.setCreated(templateSwiftRef.getCreated()); + + templateResponse.setReady(true); + templateResponse.setFeatured(template.isFeatured()); + templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); + templateResponse.setPasswordEnabled(template.getEnablePassword()); + templateResponse.setCrossZones(template.isCrossZones()); + templateResponse.setFormat(template.getFormat()); + templateResponse.setDetails(template.getDetails()); + if (template.getTemplateType() != null) { + templateResponse.setTemplateType(template.getTemplateType().toString()); + } + + Account caller = UserContext.current().getCaller(); + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + templateResponse.setHypervisor(template.getHypervisorType().toString()); + } + + GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); + if (os != null) { + templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeName(os.getDisplayName()); + } else { + templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeName(""); + } + + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(template.getAccountId()); + populateAccount(templateResponse, account.getId()); + populateDomain(templateResponse, account.getDomainId()); + + boolean isAdmin = false; + if (BaseCmd.isAdmin(caller.getType())) { + isAdmin = true; + } + + // If the user is an Admin, add the template download status + if (isAdmin || caller.getId() == template.getAccountId()) { + // add download status + templateResponse.setStatus("Successfully Installed"); + } + + Long templateSize = templateSwiftRef.getSize(); + if (templateSize > 0) { + templateResponse.setSize(templateSize); + } + + templateResponse.setChecksum(template.getChecksum()); + templateResponse.setSourceTemplateId(template.getSourceTemplateId()); + + templateResponse.setChecksum(template.getChecksum()); + + templateResponse.setTemplateTag(template.getTemplateTag()); + + templateResponse.setObjectName("template"); + responses.add(templateResponse); + return responses; + } + + @Override + public List createTemplateResponses(long templateId, long zoneId, boolean readyOnly) { + VirtualMachineTemplate template = findTemplateById(templateId); + List responses = new ArrayList(); + VMTemplateHostVO templateHostRef = ApiDBUtils.findTemplateHostRef(templateId, zoneId, readyOnly); + if (templateHostRef == null) { + return responses; + } + + HostVO host = ApiDBUtils.findHostById(templateHostRef.getHostId()); + if (host.getType() == Host.Type.LocalSecondaryStorage && host.getStatus() != com.cloud.host.Status.Up) { + return responses; + } + + TemplateResponse templateResponse = new TemplateResponse(); + templateResponse.setId(template.getId()); + templateResponse.setName(template.getName()); + templateResponse.setDisplayText(template.getDisplayText()); + templateResponse.setPublic(template.isPublicTemplate()); + templateResponse.setCreated(templateHostRef.getCreated()); + + templateResponse.setReady(templateHostRef.getDownloadState() == Status.DOWNLOADED); + templateResponse.setFeatured(template.isFeatured()); + templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); + templateResponse.setPasswordEnabled(template.getEnablePassword()); + templateResponse.setCrossZones(template.isCrossZones()); + templateResponse.setFormat(template.getFormat()); + if (template.getTemplateType() != null) { + templateResponse.setTemplateType(template.getTemplateType().toString()); + } + + Account caller = UserContext.current().getCaller(); + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + templateResponse.setHypervisor(template.getHypervisorType().toString()); + } + + templateResponse.setDetails(template.getDetails()); + + GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); + if (os != null) { + templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeName(os.getDisplayName()); + } else { + templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeName(""); + } + + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(template.getAccountId()); + populateAccount(templateResponse, account.getId()); + populateDomain(templateResponse, account.getDomainId()); + + DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); + + // Add the zone ID + templateResponse.setZoneId(zoneId); + templateResponse.setZoneName(datacenter.getName()); + + boolean isAdmin = false; + if ((caller == null) || BaseCmd.isAdmin(caller.getType())) { + isAdmin = true; + } + + // If the user is an Admin, add the template download status + if (isAdmin || caller.getId() == template.getAccountId()) { + // add download status + if (templateHostRef.getDownloadState() != Status.DOWNLOADED) { + String templateStatus = "Processing"; + if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { + if (templateHostRef.getDownloadPercent() == 100) { + templateStatus = "Installing Template"; + } else { + templateStatus = templateHostRef.getDownloadPercent() + "% Downloaded"; + } + } else { + templateStatus = templateHostRef.getErrorString(); + } + templateResponse.setStatus(templateStatus); + } else if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { + templateResponse.setStatus("Download Complete"); + } else { + templateResponse.setStatus("Successfully Installed"); + } + } + + Long templateSize = templateHostRef.getSize(); + if (templateSize > 0) { + templateResponse.setSize(templateSize); + } + + templateResponse.setChecksum(template.getChecksum()); + templateResponse.setSourceTemplateId(template.getSourceTemplateId()); + + templateResponse.setChecksum(template.getChecksum()); + + templateResponse.setTemplateTag(template.getTemplateTag()); + + templateResponse.setObjectName("template"); + responses.add(templateResponse); + return responses; + } + + @Override + public List createIsoResponses(long isoId, Long zoneId, boolean readyOnly) { + + List isoResponses = new ArrayList(); + VirtualMachineTemplate iso = findTemplateById(isoId); + if (iso.getTemplateType() == TemplateType.PERHOST) { + TemplateResponse isoResponse = new TemplateResponse(); + isoResponse.setId(iso.getId()); + isoResponse.setName(iso.getName()); + isoResponse.setDisplayText(iso.getDisplayText()); + isoResponse.setPublic(iso.isPublicTemplate()); + isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); + isoResponse.setReady(true); + isoResponse.setBootable(iso.isBootable()); + isoResponse.setFeatured(iso.isFeatured()); + isoResponse.setCrossZones(iso.isCrossZones()); + isoResponse.setPublic(iso.isPublicTemplate()); + isoResponse.setCreated(iso.getCreated()); + isoResponse.setChecksum(iso.getChecksum()); + isoResponse.setPasswordEnabled(false); + isoResponse.setDetails(iso.getDetails()); + + // add account ID and name + Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); + populateAccount(isoResponse, owner.getId()); + populateDomain(isoResponse, owner.getDomainId()); + + isoResponse.setObjectName("iso"); + isoResponses.add(isoResponse); + return isoResponses; + } else { + if (zoneId == null || zoneId == -1) { + isoResponses = createSwiftIsoResponses(iso); + if (!isoResponses.isEmpty()) { + return isoResponses; + } + List dcs = new ArrayList(); + dcs.addAll(ApiDBUtils.listZones()); + for (DataCenterVO dc : dcs) { + isoResponses.addAll(createIsoResponses(iso, dc.getId(), readyOnly)); + } + return isoResponses; + } else { + return createIsoResponses(iso, zoneId, readyOnly); + } + } + } + + private List createSwiftIsoResponses(VirtualMachineTemplate iso) { + long isoId = iso.getId(); + List isoResponses = new ArrayList(); + VMTemplateSwiftVO isoSwift = ApiDBUtils.findTemplateSwiftRef(isoId); + if (isoSwift == null) { + return isoResponses; + } + TemplateResponse isoResponse = new TemplateResponse(); + isoResponse.setId(iso.getId()); + isoResponse.setName(iso.getName()); + isoResponse.setDisplayText(iso.getDisplayText()); + isoResponse.setPublic(iso.isPublicTemplate()); + isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); + isoResponse.setCreated(isoSwift.getCreated()); + isoResponse.setReady(true); + isoResponse.setBootable(iso.isBootable()); + isoResponse.setFeatured(iso.isFeatured()); + isoResponse.setCrossZones(iso.isCrossZones()); + isoResponse.setPublic(iso.isPublicTemplate()); + isoResponse.setChecksum(iso.getChecksum()); + isoResponse.setDetails(iso.getDetails()); + + // TODO: implement + GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); + if (os != null) { + isoResponse.setOsTypeId(os.getId()); + isoResponse.setOsTypeName(os.getDisplayName()); + } else { + isoResponse.setOsTypeId(-1L); + isoResponse.setOsTypeName(""); + } + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); + populateAccount(isoResponse, account.getId()); + populateDomain(isoResponse, account.getDomainId()); + boolean isAdmin = false; + if ((account == null) || BaseCmd.isAdmin(account.getType())) { + isAdmin = true; + } + + // If the user is an admin, add the template download status + if (isAdmin || account.getId() == iso.getAccountId()) { + // add download status + isoResponse.setStatus("Successfully Installed"); + } + Long isoSize = isoSwift.getSize(); + if (isoSize > 0) { + isoResponse.setSize(isoSize); + } + isoResponse.setObjectName("iso"); + isoResponses.add(isoResponse); + return isoResponses; + } + + @Override + public List createIsoResponses(VirtualMachineTemplate iso, long zoneId, boolean readyOnly) { + long isoId = iso.getId(); + List isoResponses = new ArrayList(); + VMTemplateHostVO isoHost = ApiDBUtils.findTemplateHostRef(isoId, zoneId, readyOnly); + if (isoHost == null) { + return isoResponses; + } + TemplateResponse isoResponse = new TemplateResponse(); + isoResponse.setId(iso.getId()); + isoResponse.setName(iso.getName()); + isoResponse.setDisplayText(iso.getDisplayText()); + isoResponse.setPublic(iso.isPublicTemplate()); + isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); + isoResponse.setCreated(isoHost.getCreated()); + isoResponse.setReady(isoHost.getDownloadState() == Status.DOWNLOADED); + isoResponse.setBootable(iso.isBootable()); + isoResponse.setFeatured(iso.isFeatured()); + isoResponse.setCrossZones(iso.isCrossZones()); + isoResponse.setPublic(iso.isPublicTemplate()); + isoResponse.setChecksum(iso.getChecksum()); + isoResponse.setDetails(iso.getDetails()); + + // TODO: implement + GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); + if (os != null) { + isoResponse.setOsTypeId(os.getId()); + isoResponse.setOsTypeName(os.getDisplayName()); + } else { + isoResponse.setOsTypeId(-1L); + isoResponse.setOsTypeName(""); + } + + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); + populateAccount(isoResponse, account.getId()); + populateDomain(isoResponse, account.getDomainId()); + + Account caller = UserContext.current().getCaller(); + boolean isAdmin = false; + if ((caller == null) || BaseCmd.isAdmin(caller.getType())) { + isAdmin = true; + } + // Add the zone ID + DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); + isoResponse.setZoneId(zoneId); + isoResponse.setZoneName(datacenter.getName()); + + // If the user is an admin, add the template download status + if (isAdmin || caller.getId() == iso.getAccountId()) { + // add download status + if (isoHost.getDownloadState() != Status.DOWNLOADED) { + String isoStatus = "Processing"; + if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { + isoStatus = "Download Complete"; + } else if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { + if (isoHost.getDownloadPercent() == 100) { + isoStatus = "Installing ISO"; + } else { + isoStatus = isoHost.getDownloadPercent() + "% Downloaded"; + } + } else { + isoStatus = isoHost.getErrorString(); + } + isoResponse.setStatus(isoStatus); + } else { + isoResponse.setStatus("Successfully Installed"); + } + } + + Long isoSize = isoHost.getSize(); + if (isoSize > 0) { + isoResponse.setSize(isoSize); + } + + isoResponse.setObjectName("iso"); + isoResponses.add(isoResponse); + return isoResponses; + } + + @Override + public ListResponse createSecurityGroupResponses( + List networkGroups) { + List groupResultObjs = SecurityGroupResultObject + .transposeNetworkGroups(networkGroups); + + ListResponse response = new ListResponse(); + List netGrpResponses = new ArrayList(); + for (SecurityGroupResultObject networkGroup : groupResultObjs) { + SecurityGroupResponse netGrpResponse = new SecurityGroupResponse(); + netGrpResponse.setId(networkGroup.getId()); + netGrpResponse.setName(networkGroup.getName()); + netGrpResponse.setDescription(networkGroup.getDescription()); + + populateOwner(netGrpResponse, networkGroup); + + List securityGroupRules = networkGroup + .getSecurityGroupRules(); + if ((securityGroupRules != null) && !securityGroupRules.isEmpty()) { + List ingressRulesResponse = new ArrayList(); + List egressRulesResponse = new ArrayList(); + for (SecurityGroupRuleResultObject securityGroupRule : securityGroupRules) { + SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); + ruleData.setRuleId(securityGroupRule.getId()); + ruleData.setProtocol(securityGroupRule.getProtocol()); + + if ("icmp".equalsIgnoreCase(securityGroupRule.getProtocol())) { + ruleData.setIcmpType(securityGroupRule.getStartPort()); + ruleData.setIcmpCode(securityGroupRule.getEndPort()); + } else { + ruleData.setStartPort(securityGroupRule.getStartPort()); + ruleData.setEndPort(securityGroupRule.getEndPort()); + } + + if (securityGroupRule.getAllowedSecurityGroup() != null) { + ruleData.setSecurityGroupName(securityGroupRule + .getAllowedSecurityGroup()); + ruleData.setAccountName(securityGroupRule + .getAllowedSecGroupAcct()); + } else { + ruleData.setCidr(securityGroupRule + .getAllowedSourceIpCidr()); + } + + if (securityGroupRule.getRuleType() == SecurityRuleType.IngressRule) { + ruleData.setObjectName("ingressrule"); + ingressRulesResponse.add(ruleData); + } else { + ruleData.setObjectName("egressrule"); + egressRulesResponse.add(ruleData); + } + } + netGrpResponse + .setSecurityGroupIngressRules(ingressRulesResponse); + netGrpResponse.setSecurityGroupEgressRules(egressRulesResponse); + } + netGrpResponse.setObjectName("securitygroup"); + netGrpResponses.add(netGrpResponse); + } + + response.setResponses(netGrpResponses); + return response; + } + + @Override + public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { + SecurityGroupResponse response = new SecurityGroupResponse(); + + populateOwner(response, group); + + response.setDescription(group.getDescription()); + response.setId(group.getId()); + response.setName(group.getName()); + + response.setObjectName("securitygroup"); + return response; + + } + + @Override + public ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode) { + UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId); + ExtractResponse response = new ExtractResponse(); + response.setObjectName("template"); + response.setId(id); + response.setName(ApiDBUtils.findTemplateById(id).getName()); + if (zoneId != null) { + response.setZoneId(zoneId); + response.setZoneName(ApiDBUtils.findZoneById(zoneId).getName()); + } + response.setMode(mode); + response.setUploadId(uploadId); + response.setState(uploadInfo.getUploadState().toString()); + response.setAccountId(accountId); + response.setUrl(uploadInfo.getUploadUrl()); + return response; + + } + + @Override + public String toSerializedString(CreateCmdResponse response, String responseType) { + return ApiResponseSerializer.toSerializedString(response, responseType); + } + + @Override + public AsyncJobResponse createAsyncJobResponse(AsyncJob job) { + AsyncJobResponse jobResponse = new AsyncJobResponse(); + jobResponse.setAccountId(job.getAccountId()); + jobResponse.setUserId(job.getUserId()); + jobResponse.setCmd(job.getCmd()); + jobResponse.setCreated(job.getCreated()); + jobResponse.setJobId(job.getId()); + jobResponse.setJobStatus(job.getStatus()); + jobResponse.setJobProcStatus(job.getProcessStatus()); + + if (job.getInstanceType() != null && job.getInstanceId() != null) { + jobResponse.setJobInstanceType(job.getInstanceType().toString()); + jobResponse.setJobInstanceId(job.getInstanceId()); + } + jobResponse.setJobResultCode(job.getResultCode()); + + boolean savedValue = SerializationContext.current().getUuidTranslation(); + SerializationContext.current().setUuidTranslation(false); + jobResponse.setJobResult((ResponseObject) ApiSerializerHelper.fromSerializedString(job.getResult())); + SerializationContext.current().setUuidTranslation(savedValue); + + Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); + if (resultObject != null) { + Class clz = resultObject.getClass(); + if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { + jobResponse.setJobResultType("text"); + } else { + jobResponse.setJobResultType("object"); + } + } + + jobResponse.setObjectName("asyncjobs"); + return jobResponse; + } + + @Override + public List createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly) { + VolumeVO volume = null; + if (snapshotId != null) { + Snapshot snapshot = ApiDBUtils.findSnapshotById(snapshotId); + volume = findVolumeById(snapshot.getVolumeId()); + } else { + volume = findVolumeById(volumeId); + } + return createTemplateResponses(templateId, volume.getDataCenterId(), readyOnly); + } + + @Override + public List createTemplateResponses(long templateId, Long vmId) { + UserVm vm = findUserVmById(vmId); + Long hostId = (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()); + Host host = findHostById(hostId); + return createTemplateResponses(templateId, host.getDataCenterId(), true); + } + + @Override + public EventResponse createEventResponse(Event event) { + EventResponse responseEvent = new EventResponse(); + responseEvent.setCreated(event.getCreateDate()); + responseEvent.setDescription(event.getDescription()); + responseEvent.setEventType(event.getType()); + responseEvent.setId(event.getId()); + responseEvent.setLevel(event.getLevel()); + responseEvent.setParentId(event.getStartId()); + responseEvent.setState(event.getState()); + + populateOwner(responseEvent, event); + + User user = ApiDBUtils.findUserById(event.getUserId()); + if (user != null) { + responseEvent.setUsername(user.getUsername()); + } + + responseEvent.setObjectName("event"); + return responseEvent; + } + + private List sumCapacities(List hostCapacities) { + Map totalCapacityMap = new HashMap(); + Map usedCapacityMap = new HashMap(); + + Set poolIdsToIgnore = new HashSet(); + Criteria c = new Criteria(); + // TODO: implement + List allStoragePools = ApiDBUtils.searchForStoragePools(c); + for (StoragePoolVO pool : allStoragePools) { + StoragePoolType poolType = pool.getPoolType(); + if (!(poolType.isShared())) {// All the non shared storages shouldn't show up in the capacity calculation + poolIdsToIgnore.add(pool.getId()); + } + } + + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + // collect all the capacity types, sum allocated/used and sum total...get one capacity number for each + for (Capacity capacity : hostCapacities) { + + // check if zone exist + DataCenter zone = ApiDBUtils.findZoneById(capacity.getDataCenterId()); + if (zone == null) { + continue; + } + + short capacityType = capacity.getCapacityType(); + + // If local storage then ignore + if ((capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE) + && poolIdsToIgnore.contains(capacity.getHostOrPoolId())) { + continue; + } + + String key = capacity.getCapacityType() + "_" + capacity.getDataCenterId(); + String keyForPodTotal = key + "_-1"; + + boolean sumPodCapacity = false; + if (capacity.getPodId() != null) { + key += "_" + capacity.getPodId(); + sumPodCapacity = true; + } + + Long totalCapacity = totalCapacityMap.get(key); + Long usedCapacity = usedCapacityMap.get(key); + + // reset overprovisioning factor to 1 + float overprovisioningFactor = 1; + if (capacityType == Capacity.CAPACITY_TYPE_CPU) { + overprovisioningFactor = cpuOverprovisioningFactor; + } + + if (totalCapacity == null) { + totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)); + } else { + totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)) + totalCapacity; + } + + if (usedCapacity == null) { + usedCapacity = new Long(capacity.getUsedCapacity()); + } else { + usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); + } + + if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved + // Capacity + // accounts +// for + // stopped +// vms + // that +// have been + // stopped +// within + // an +// interval + usedCapacity += capacity.getReservedCapacity(); + } + + totalCapacityMap.put(key, totalCapacity); + usedCapacityMap.put(key, usedCapacity); + + if (sumPodCapacity) { + totalCapacity = totalCapacityMap.get(keyForPodTotal); + usedCapacity = usedCapacityMap.get(keyForPodTotal); + + overprovisioningFactor = 1; + if (capacityType == Capacity.CAPACITY_TYPE_CPU) { + overprovisioningFactor = cpuOverprovisioningFactor; + } + + if (totalCapacity == null) { + totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)); + } else { + totalCapacity = new Long((long) (capacity.getTotalCapacity() * overprovisioningFactor)) + totalCapacity; + } + + if (usedCapacity == null) { + usedCapacity = new Long(capacity.getUsedCapacity()); + } else { + usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); + } + + if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved + // Capacity + // accounts + // for + // stopped + // vms +// that + // have +// been + // stopped + // within +// an + // interval + usedCapacity += capacity.getReservedCapacity(); + } + + totalCapacityMap.put(keyForPodTotal, totalCapacity); + usedCapacityMap.put(keyForPodTotal, usedCapacity); + } + } + + List summedCapacities = new ArrayList(); + for (String key : totalCapacityMap.keySet()) { + CapacityVO summedCapacity = new CapacityVO(); + + StringTokenizer st = new StringTokenizer(key, "_"); + summedCapacity.setCapacityType(Short.parseShort(st.nextToken())); + summedCapacity.setDataCenterId(Long.parseLong(st.nextToken())); + if (st.hasMoreTokens()) { + summedCapacity.setPodId(Long.parseLong(st.nextToken())); + } + + summedCapacity.setTotalCapacity(totalCapacityMap.get(key)); + summedCapacity.setUsedCapacity(usedCapacityMap.get(key)); + + summedCapacities.add(summedCapacity); + } + return summedCapacities; + } + + @Override + public List createCapacityResponse(List result, DecimalFormat format) { + List capacityResponses = new ArrayList(); + + for (Capacity summedCapacity : result) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityTotal(summedCapacity.getTotalCapacity()); + capacityResponse.setCapacityType(summedCapacity.getCapacityType()); + capacityResponse.setCapacityUsed(summedCapacity.getUsedCapacity()); + if (summedCapacity.getPodId() != null) { + capacityResponse.setPodId(summedCapacity.getPodId()); + HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); + if (pod != null) { + capacityResponse.setPodName(pod.getName()); + } + } + if (summedCapacity.getClusterId() != null) { + capacityResponse.setClusterId(summedCapacity.getClusterId()); + ClusterVO cluster = ApiDBUtils.findClusterById(summedCapacity.getClusterId()); + if (cluster != null) { + capacityResponse.setClusterName(cluster.getName()); + if (summedCapacity.getPodId() == null) { + long podId = cluster.getPodId(); + capacityResponse.setPodId(podId); + capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName()); + } + } + } + capacityResponse.setZoneId(summedCapacity.getDataCenterId()); + capacityResponse.setZoneName(ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()).getName()); + if (summedCapacity.getUsedPercentage() != null){ + capacityResponse.setPercentUsed(format.format(summedCapacity.getUsedPercentage() * 100f)); + } else if (summedCapacity.getTotalCapacity() != 0) { + capacityResponse.setPercentUsed(format.format((float) summedCapacity.getUsedCapacity() / (float) summedCapacity.getTotalCapacity() * 100f)); + } else { + capacityResponse.setPercentUsed(format.format(0L)); + } + + capacityResponse.setObjectName("capacity"); + capacityResponses.add(capacityResponse); + } + + return capacityResponses; + } + + @Override + public TemplatePermissionsResponse createTemplatePermissionsResponse(List accountNames, Long id, boolean isAdmin) { + Long templateOwnerDomain = null; + VirtualMachineTemplate template = ApiDBUtils.findTemplateById(id); + Account templateOwner = ApiDBUtils.findAccountById(template.getAccountId()); + if (isAdmin) { + // FIXME: we have just template id and need to get template owner from that + if (templateOwner != null) { + templateOwnerDomain = templateOwner.getDomainId(); + } + } + + TemplatePermissionsResponse response = new TemplatePermissionsResponse(); + response.setId(template.getId()); + response.setPublicTemplate(template.isPublicTemplate()); + if (isAdmin && (templateOwnerDomain != null)) { + response.setDomainId(templateOwnerDomain); + } + + // Set accounts + List projectIds = new ArrayList(); + List regularAccounts = new ArrayList(); + for (String accountName : accountNames) { + Account account = ApiDBUtils.findAccountByNameDomain(accountName, templateOwner.getDomainId()); + if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) { + regularAccounts.add(accountName); + } else { + // convert account to projectIds + Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); + + if (project.getUuid() != null && !project.getUuid().isEmpty()) + projectIds.add(project.getUuid()); + else + projectIds.add(String.valueOf(project.getId())); + } + } + + if (!projectIds.isEmpty()) { + response.setProjectIds(projectIds); + } + + if (!regularAccounts.isEmpty()) { + response.setAccountNames(regularAccounts); + } + + response.setObjectName("templatepermission"); + return response; + } + + @Override + public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) { + AsyncJob result = ApiDBUtils._asyncMgr.queryAsyncJobResult(cmd); + return createAsyncJobResponse(result); + } + + @Override + public SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List securityRules) { + SecurityGroupResponse response = new SecurityGroupResponse(); + Map securiytGroupAccounts = new HashMap(); + Map allowedSecurityGroups = new HashMap(); + Map allowedSecuriytGroupAccounts = new HashMap(); + + if ((securityRules != null) && !securityRules.isEmpty()) { + SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(securityRules.get(0).getSecurityGroupId()); + response.setId(securityGroup.getId()); + response.setName(securityGroup.getName()); + response.setDescription(securityGroup.getDescription()); + + Account account = securiytGroupAccounts.get(securityGroup.getAccountId()); + + if (account == null) { + account = ApiDBUtils.findAccountById(securityGroup.getAccountId()); + securiytGroupAccounts.put(securityGroup.getAccountId(), account); + } + + populateAccount(response, account.getId()); + populateDomain(response, account.getDomainId()); + + List egressResponses = new ArrayList(); + List ingressResponses = new ArrayList(); + for (SecurityRule securityRule : securityRules) { + SecurityGroupRuleResponse securityGroupData = new SecurityGroupRuleResponse(); + + securityGroupData.setRuleId(securityRule.getId()); + securityGroupData.setProtocol(securityRule.getProtocol()); + if ("icmp".equalsIgnoreCase(securityRule.getProtocol())) { + securityGroupData.setIcmpType(securityRule.getStartPort()); + securityGroupData.setIcmpCode(securityRule.getEndPort()); + } else { + securityGroupData.setStartPort(securityRule.getStartPort()); + securityGroupData.setEndPort(securityRule.getEndPort()); + } + + Long allowedSecurityGroupId = securityRule.getAllowedNetworkId(); + if (allowedSecurityGroupId != null) { + SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId); + if (allowedSecurityGroup == null) { + allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId); + allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup); + } + + securityGroupData.setSecurityGroupName(allowedSecurityGroup.getName()); + + Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId()); + if (allowedAccount == null) { + allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId()); + allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount); + } + + securityGroupData.setAccountName(allowedAccount.getAccountName()); + } else { + securityGroupData.setCidr(securityRule.getAllowedSourceIpCidr()); + } + if (securityRule.getRuleType() == SecurityRuleType.IngressRule) { + securityGroupData.setObjectName("ingressrule"); + ingressResponses.add(securityGroupData); + } else { + securityGroupData.setObjectName("egressrule"); + egressResponses.add(securityGroupData); + } + + } + response.setSecurityGroupIngressRules(ingressResponses); + response.setSecurityGroupEgressRules(egressResponses); + response.setObjectName("securitygroup"); + + } + return response; + } + + @Override + public NetworkOfferingResponse createNetworkOfferingResponse(NetworkOffering offering) { + NetworkOfferingResponse response = new NetworkOfferingResponse(); + response.setId(offering.getId()); + response.setName(offering.getName()); + response.setDisplayText(offering.getDisplayText()); + response.setTags(offering.getTags()); + response.setTrafficType(offering.getTrafficType().toString()); + response.setIsDefault(offering.isDefault()); + response.setSpecifyVlan(offering.getSpecifyVlan()); + response.setConserveMode(offering.isConserveMode()); + response.setSpecifyIpRanges(offering.getSpecifyIpRanges()); + response.setAvailability(offering.getAvailability().toString()); + response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); + if (offering.getServiceOfferingId() != null) { + response.setServiceOfferingId(offering.getServiceOfferingId()); + } else { + response.setServiceOfferingId(ApiDBUtils.findDefaultRouterServiceOffering()); + } + if (offering.getGuestType() != null) { + response.setGuestIpType(offering.getGuestType().toString()); + } + + response.setState(offering.getState().name()); + + Map> serviceProviderMap = ApiDBUtils.listNetworkOfferingServices(offering.getId()); + List serviceResponses = new ArrayList(); + for (Service service : serviceProviderMap.keySet()) { + ServiceResponse svcRsp = new ServiceResponse(); + // skip gateway service + if (service == Service.Gateway) { + continue; + } + svcRsp.setName(service.getName()); + List providers = new ArrayList(); + for (Provider provider : serviceProviderMap.get(service)) { + if (provider != null) { + ProviderResponse providerRsp = new ProviderResponse(); + providerRsp.setName(provider.getName()); + providers.add(providerRsp); + } + } + svcRsp.setProviders(providers); + + if (Service.Lb == service) { + List lbCapResponse = new ArrayList(); + + CapabilityResponse lbIsoaltion = new CapabilityResponse(); + lbIsoaltion.setName(Capability.SupportedLBIsolation.getName()); + lbIsoaltion.setValue(offering.getDedicatedLB() ? "dedicated" : "shared"); + lbCapResponse.add(lbIsoaltion); + + CapabilityResponse eLb = new CapabilityResponse(); + eLb.setName(Capability.ElasticLb.getName()); + eLb.setValue(offering.getElasticLb() ? "true" : "false"); + lbCapResponse.add(eLb); + + svcRsp.setCapabilities(lbCapResponse); + } else if (Service.SourceNat == service) { + List capabilities = new ArrayList(); + CapabilityResponse sharedSourceNat = new CapabilityResponse(); + sharedSourceNat.setName(Capability.SupportedSourceNatTypes.getName()); + sharedSourceNat.setValue(offering.getSharedSourceNat() ? "perzone" : "peraccount"); + capabilities.add(sharedSourceNat); + + CapabilityResponse redundantRouter = new CapabilityResponse(); + redundantRouter.setName(Capability.RedundantRouter.getName()); + redundantRouter.setValue(offering.getRedundantRouter() ? "true" : "false"); + capabilities.add(redundantRouter); + + svcRsp.setCapabilities(capabilities); + } else if (service == Service.StaticNat) { + List staticNatCapResponse = new ArrayList(); + + CapabilityResponse eIp = new CapabilityResponse(); + eIp.setName(Capability.ElasticIp.getName()); + eIp.setValue(offering.getElasticLb() ? "true" : "false"); + staticNatCapResponse.add(eIp); + + svcRsp.setCapabilities(staticNatCapResponse); + } + + serviceResponses.add(svcRsp); + } + response.setServices(serviceResponses); + response.setObjectName("networkoffering"); + return response; + } + + @Override + public NetworkResponse createNetworkResponse(Network network) { + // need to get network profile in order to retrieve dns information from there + NetworkProfile profile = ApiDBUtils.getNetworkProfile(network.getId()); + NetworkResponse response = new NetworkResponse(); + response.setId(network.getId()); + response.setName(network.getName()); + response.setDisplaytext(network.getDisplayText()); + if (network.getBroadcastDomainType() != null) { + response.setBroadcastDomainType(network.getBroadcastDomainType().toString()); + } + + if (network.getTrafficType() != null) { + response.setTrafficType(network.getTrafficType().name()); + } + + if (network.getGuestType() != null) { + response.setType(network.getGuestType().toString()); + } + + response.setGateway(network.getGateway()); + + // FIXME - either set netmask or cidr + response.setCidr(network.getCidr()); + if (network.getCidr() != null) { + response.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); + } + + // FIXME - either set broadcast URI or vlan + if (network.getBroadcastUri() != null) { + String broadcastUri = network.getBroadcastUri().toString(); + response.setBroadcastUri(broadcastUri); + String vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); + response.setVlan(vlan); + } + + DataCenter zone = ApiDBUtils.findZoneById(network.getDataCenterId()); + response.setZoneId(network.getDataCenterId()); + response.setZoneName(zone.getName()); + response.setPhysicalNetworkId(network.getPhysicalNetworkId()); + + // populate network offering information + NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); + if (networkOffering != null) { + response.setNetworkOfferingId(networkOffering.getId()); + response.setNetworkOfferingName(networkOffering.getName()); + response.setNetworkOfferingDisplayText(networkOffering.getDisplayText()); + response.setIsSystem(networkOffering.isSystemOnly()); + response.setNetworkOfferingAvailability(networkOffering.getAvailability().toString()); + } + + if (network.getAclType() != null) { + response.setAclType(network.getAclType().toString()); + } + response.setState(network.getState().toString()); + response.setRestartRequired(network.isRestartRequired()); + response.setRelated(network.getRelated()); + response.setNetworkDomain(network.getNetworkDomain()); + + response.setDns1(profile.getDns1()); + response.setDns2(profile.getDns2()); + // populate capability + Map> serviceCapabilitiesMap = ApiDBUtils.getNetworkCapabilities(network.getId(), network.getDataCenterId()); + List serviceResponses = new ArrayList(); + if (serviceCapabilitiesMap != null) { + for (Service service : serviceCapabilitiesMap.keySet()) { + ServiceResponse serviceResponse = new ServiceResponse(); + // skip gateway service + if (service == Service.Gateway) { + continue; + } + serviceResponse.setName(service.getName()); + + // set list of capabilities for the service + List capabilityResponses = new ArrayList(); + Map serviceCapabilities = serviceCapabilitiesMap.get(service); + if (serviceCapabilities != null) { + for (Capability capability : serviceCapabilities.keySet()) { + CapabilityResponse capabilityResponse = new CapabilityResponse(); + String capabilityValue = serviceCapabilities.get(capability); + capabilityResponse.setName(capability.getName()); + capabilityResponse.setValue(capabilityValue); + capabilityResponse.setObjectName("capability"); + capabilityResponses.add(capabilityResponse); + } + serviceResponse.setCapabilities(capabilityResponses); + } + + serviceResponse.setObjectName("service"); + serviceResponses.add(serviceResponse); + } + } + response.setServices(serviceResponses); + + if (network.getAclType() == null || network.getAclType() == ACLType.Account) { + populateOwner(response, network); + } else { + // get domain from network_domain table + Pair domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId()); + response.setDomainId(domainNetworkDetails.first()); + response.setSubdomainAccess(domainNetworkDetails.second()); + } + + Long dedicatedDomainId = ApiDBUtils.getDedicatedNetworkDomain(network.getId()); + if (dedicatedDomainId != null) { + Domain domain = ApiDBUtils.findDomainById(dedicatedDomainId); + response.setDomainId(dedicatedDomainId); + response.setDomainName(domain.getName()); + } + + response.setSpecifyIpRanges(network.getSpecifyIpRanges()); + + response.setObjectName("network"); + return response; + } + + @Override + public Long getSecurityGroupId(String groupName, long accountId) { + SecurityGroup sg = ApiDBUtils.getSecurityGroup(groupName, accountId); + if (sg == null) { + return null; + } else { + return sg.getId(); + } + } + + @Override + public ProjectResponse createProjectResponse(Project project) { + ProjectResponse response = new ProjectResponse(); + response.setId(project.getId()); + response.setName(project.getName()); + response.setDisplaytext(project.getDisplayText()); + response.setState(project.getState().toString()); + + Domain domain = ApiDBUtils.findDomainById(project.getDomainId()); + response.setDomainId(domain.getId()); + response.setDomain(domain.getName()); + + response.setOwner(ApiDBUtils.getProjectOwner(project.getId()).getAccountName()); + + response.setObjectName("project"); + return response; + } + + @Override + public FirewallResponse createFirewallResponse(FirewallRule fwRule) { + FirewallResponse response = new FirewallResponse(); + + response.setId(fwRule.getId()); + response.setProtocol(fwRule.getProtocol()); + if (fwRule.getSourcePortStart() != null) { + response.setStartPort(Integer.toString(fwRule.getSourcePortStart())); + } + + if (fwRule.getSourcePortEnd() != null) { + response.setEndPort(Integer.toString(fwRule.getSourcePortEnd())); + } + + List cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId()); + response.setCidrList(StringUtils.join(cidrs, ",")); + + IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); + response.setPublicIpAddressId(ip.getId()); + response.setPublicIpAddress(ip.getAddress().addr()); + + FirewallRule.State state = fwRule.getState(); + String stateToSet = state.toString(); + if (state.equals(FirewallRule.State.Revoke)) { + stateToSet = "Deleting"; + } + + response.setIcmpCode(fwRule.getIcmpCode()); + response.setIcmpType(fwRule.getIcmpType()); + + response.setState(stateToSet); + response.setObjectName("firewallrule"); + return response; + } + + public UserVmData newUserVmData(UserVm userVm) { + UserVmData userVmData = new UserVmData(); + userVmData.setId(userVm.getId()); + userVmData.setName(userVm.getHostName()); + userVmData.setCreated(userVm.getCreated()); + userVmData.setGuestOsId(userVm.getGuestOSId()); + userVmData.setHaEnable(userVm.isHaEnabled()); + if (userVm.getState() != null) { + userVmData.setState(userVm.getState().toString()); + } + if (userVm.getDisplayName() != null) { + userVmData.setDisplayName(userVm.getDisplayName()); + } else { + userVmData.setDisplayName(userVm.getHostName()); + } + userVmData.setInstanceName(userVm.getInstanceName()); + + userVmData.setDomainId(userVm.getDomainId()); + + Account caller = UserContext.current().getCaller(); + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + if (userVm.getHypervisorType() != null) { + userVmData.setHypervisor(userVm.getHypervisorType().toString()); + } + } + + if (userVm.getPassword() != null) { + userVmData.setPassword(userVm.getPassword()); + } + return userVmData; + } + + public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin) { + UserVmResponse userVmResponse = new UserVmResponse(); + + userVmResponse.setHypervisor(userVmData.getHypervisor()); + userVmResponse.setId(userVmData.getId()); + userVmResponse.setName(userVmData.getName()); + + userVmResponse.setDisplayName(userVmData.getDisplayName()); + + populateAccount(userVmResponse, userVmData.getAccountId()); + populateDomain(userVmResponse, userVmData.getDomainId()); + + userVmResponse.setCreated(userVmData.getCreated()); + userVmResponse.setState(userVmData.getState()); + userVmResponse.setHaEnable(userVmData.getHaEnable()); + userVmResponse.setGroupId(userVmData.getGroupId()); + userVmResponse.setGroup(userVmData.getGroup()); + userVmResponse.setZoneId(userVmData.getZoneId()); + userVmResponse.setZoneName(userVmData.getZoneName()); + if (caller_is_admin) { + userVmResponse.setInstanceName(userVmData.getInstanceName()); + userVmResponse.setHostId(userVmData.getHostId()); + userVmResponse.setHostName(userVmData.getHostName()); + } + userVmResponse.setTemplateId(userVmData.getTemplateId()); + userVmResponse.setTemplateName(userVmData.getTemplateName()); + userVmResponse.setTemplateDisplayText(userVmData.getTemplateDisplayText()); + userVmResponse.setPasswordEnabled(userVmData.getPasswordEnabled()); + userVmResponse.setIsoId(userVmData.getIsoId()); + userVmResponse.setIsoName(userVmData.getIsoName()); + userVmResponse.setIsoDisplayText(userVmData.getIsoDisplayText()); + userVmResponse.setServiceOfferingId(userVmData.getServiceOfferingId()); + userVmResponse.setServiceOfferingName(userVmData.getServiceOfferingName()); + userVmResponse.setCpuNumber(userVmData.getCpuNumber()); + userVmResponse.setCpuSpeed(userVmData.getCpuSpeed()); + userVmResponse.setMemory(userVmData.getMemory()); + userVmResponse.setCpuUsed(userVmData.getCpuUsed()); + userVmResponse.setNetworkKbsRead(userVmData.getNetworkKbsRead()); + userVmResponse.setNetworkKbsWrite(userVmData.getNetworkKbsWrite()); + userVmResponse.setGuestOsId(userVmData.getGuestOsId()); + userVmResponse.setRootDeviceId(userVmData.getRootDeviceId()); + userVmResponse.setRootDeviceType(userVmData.getRootDeviceType()); + userVmResponse.setPassword(userVmData.getPassword()); + userVmResponse.setJobId(userVmData.getJobId()); + userVmResponse.setJobStatus(userVmData.getJobStatus()); + userVmResponse.setForVirtualNetwork(userVmData.getForVirtualNetwork()); + + Set securityGroupResponse = new HashSet(); + for (SecurityGroupData sgd : userVmData.getSecurityGroupList()) { + if (sgd.getId() != null) { + SecurityGroupResponse sgr = new SecurityGroupResponse(); + sgr.setId(sgd.getId()); + sgr.setName(sgd.getName()); + sgr.setDescription(sgd.getDescription()); + + Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); + if (account != null) { + populateAccount(sgr, account.getId()); + populateDomain(sgr, account.getDomainId()); + } + + sgr.setObjectName(sgd.getObjectName()); + securityGroupResponse.add(sgr); + } + } + userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse)); + + Set nicResponses = new HashSet(); + for (NicData nd : userVmData.getNics()) { + NicResponse nr = new NicResponse(); + nr.setId(nd.getId()); + nr.setNetworkid(nd.getNetworkid()); + nr.setNetmask(nd.getNetmask()); + nr.setGateway(nd.getGateway()); + nr.setIpaddress(nd.getIpaddress()); + nr.setIsolationUri(nd.getIsolationUri()); + nr.setBroadcastUri(nd.getBroadcastUri()); + nr.setTrafficType(nd.getTrafficType()); + nr.setType(nd.getType()); + nr.setIsDefault(nd.getIsDefault()); + nr.setMacAddress(nd.getMacAddress()); + nr.setObjectName(nd.getObjectName()); + nicResponses.add(nr); + } + userVmResponse.setNics(new ArrayList(nicResponses)); + userVmResponse.setPublicIpId(userVmData.getPublicIpId()); + userVmResponse.setPublicIp(userVmData.getPublicIp()); + + return userVmResponse; + } + + @Override + public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities) { + HypervisorCapabilitiesResponse hpvCapabilitiesResponse = new HypervisorCapabilitiesResponse(); + hpvCapabilitiesResponse.setId(hpvCapabilities.getId()); + hpvCapabilitiesResponse.setHypervisor(hpvCapabilities.getHypervisorType()); + hpvCapabilitiesResponse.setHypervisorVersion(hpvCapabilities.getHypervisorVersion()); + hpvCapabilitiesResponse.setIsSecurityGroupEnabled(hpvCapabilities.isSecurityGroupEnabled()); + hpvCapabilitiesResponse.setMaxGuestsLimit(hpvCapabilities.getMaxGuestsLimit()); + return hpvCapabilitiesResponse; + } + + private void populateOwner(ControlledEntityResponse response, ControlledEntity object) { + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId()); + + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + // find the project + Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); + response.setProjectId(project.getId()); + response.setProjectName(project.getName()); + } else { + response.setAccountName(account.getAccountName()); + } + + Domain domain = ApiDBUtils.findDomainById(object.getDomainId()); + response.setDomainId(domain.getId()); + response.setDomainName(domain.getName()); + } + + private void populateAccount(ControlledEntityResponse response, long accountId) { + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId); + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + // find the project + Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); + response.setProjectId(project.getId()); + response.setProjectName(project.getName()); + } else { + response.setAccountName(account.getAccountName()); + } + } + + private void populateDomain(ControlledEntityResponse response, long domainId) { + Domain domain = ApiDBUtils.findDomainById(domainId); + + response.setDomainId(domain.getId()); + response.setDomainName(domain.getName()); + } + + @Override + public ProjectAccountResponse createProjectAccountResponse(ProjectAccount projectAccount) { + Account account = ApiDBUtils.findAccountById(projectAccount.getAccountId()); + ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); + + long projectId = projectAccount.getProjectId(); + projectAccountResponse.setProjectId(projectId); + projectAccountResponse.setProjectName(ApiDBUtils.findProjectById(projectId).getName()); + + projectAccountResponse.setId(account.getId()); + projectAccountResponse.setAccountName(account.getAccountName()); + projectAccountResponse.setAccountType(account.getType()); + projectAccountResponse.setRole(projectAccount.getAccountRole().toString()); + populateDomain(projectAccountResponse, account.getDomainId()); + + // add all the users for an account as part of the response obj + List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); + List userResponseList = new ArrayList(); + for (UserVO user : usersForAccount) { + UserResponse userResponse = createUserResponse(user); + userResponseList.add(userResponse); + } + + projectAccountResponse.setUsers(userResponseList); + projectAccountResponse.setObjectName("projectaccount"); + + return projectAccountResponse; + } + + @Override + public ProjectInvitationResponse createProjectInvitationResponse(ProjectInvitation invite) { + ProjectInvitationResponse response = new ProjectInvitationResponse(); + response.setId(invite.getId()); + response.setProjectId(invite.getProjectId()); + response.setProjectName(ApiDBUtils.findProjectById(invite.getProjectId()).getName()); + response.setInvitationState(invite.getState().toString()); + + if (invite.getForAccountId() != null) { + Account account = ApiDBUtils.findAccountById(invite.getForAccountId()); + response.setAccountName(account.getAccountName()); + + } else { + response.setEmail(invite.getEmail()); + } + + populateDomain(response, invite.getInDomainId()); + + response.setObjectName("projectinvitation"); + return response; + } + + @Override + public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) { + SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse(); + vmResponse.setId(vm.getId()); + vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); + vmResponse.setName(vm.getHostName()); + if (vm.getHostId() != null) { + vmResponse.setHostId(vm.getHostId()); + } + if (vm.getState() != null) { + vmResponse.setState(vm.getState().toString()); + } + if (vm.getType() == Type.DomainRouter) { + VirtualRouter router = (VirtualRouter) vm; + if (router.getRole() != null) { + vmResponse.setRole(router.getRole().toString()); + } + } + vmResponse.setObjectName("systemvminstance"); + return vmResponse; + } + + @Override + public PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result) { + PhysicalNetworkResponse response = new PhysicalNetworkResponse(); + + response.setZoneId(result.getDataCenterId()); + response.setNetworkSpeed(result.getSpeed()); + response.setVlan(result.getVnet()); + response.setDomainId(result.getDomainId()); + response.setId(result.getUuid()); + if (result.getBroadcastDomainRange() != null) { + response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString()); + } + response.setIsolationMethods(result.getIsolationMethods()); + response.setTags(result.getTags()); + if (result.getState() != null) { + response.setState(result.getState().toString()); + } + + response.setName(result.getName()); + + response.setObjectName("physicalnetwork"); + return response; + } + + @Override + public ServiceResponse createNetworkServiceResponse(Service service) { + ServiceResponse response = new ServiceResponse(); + response.setName(service.getName()); + + // set list of capabilities required for the service + List capabilityResponses = new ArrayList(); + Capability[] capabilities = service.getCapabilities(); + for (Capability cap : capabilities) { + CapabilityResponse capabilityResponse = new CapabilityResponse(); + capabilityResponse.setName(cap.getName()); + capabilityResponse.setObjectName("capability"); + if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) || + cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) || + cap.getName().equals(Capability.RedundantRouter.getName())) { + capabilityResponse.setCanChoose(true); + } else { + capabilityResponse.setCanChoose(false); + } + capabilityResponses.add(capabilityResponse); + } + response.setCapabilities(capabilityResponses); + + // set list of providers providing this service + List serviceProviders = ApiDBUtils.getProvidersForService(service); + List serviceProvidersResponses = new ArrayList(); + for (Network.Provider serviceProvider : serviceProviders) { + // return only Virtual Router/JuniperSRX as a provider for the firewall + if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX)) { + continue; + } + + ProviderResponse serviceProviderResponse = createServiceProviderResponse(serviceProvider); + serviceProvidersResponses.add(serviceProviderResponse); + } + response.setProviders(serviceProvidersResponses); + + response.setObjectName("networkservice"); + return response; + + } + + private ProviderResponse createServiceProviderResponse(Provider serviceProvider) { + ProviderResponse response = new ProviderResponse(); + response.setName(serviceProvider.getName()); + boolean canEnableIndividualServices = ApiDBUtils.canElementEnableIndividualServices(serviceProvider); + response.setCanEnableIndividualServices(canEnableIndividualServices); + return response; + } + + @Override + public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result) { + ProviderResponse response = new ProviderResponse(); + response.setId(result.getUuid()); + response.setName(result.getProviderName()); + response.setPhysicalNetworkId(result.getPhysicalNetworkId()); + response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId()); + response.setState(result.getState().toString()); + + // set enabled services + List services = new ArrayList(); + for (Service service : result.getEnabledServices()) { + services.add(service.getName()); + } + response.setServices(services); + + response.setObjectName("networkserviceprovider"); + return response; + } + + @Override + public TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType result) { + TrafficTypeResponse response = new TrafficTypeResponse(); + response.setId(result.getUuid()); + response.setPhysicalNetworkId(result.getPhysicalNetworkId()); + response.setTrafficType(result.getTrafficType().toString()); + response.setXenLabel(result.getXenNetworkLabel()); + response.setKvmLabel(result.getKvmNetworkLabel()); + response.setVmwareLabel(result.getVmwareNetworkLabel()); + + response.setObjectName("traffictype"); + return response; + } + + @Override + public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { + VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); + response.setId(result.getId()); + response.setNspId(result.getNspId()); + response.setEnabled(result.isEnabled()); + + response.setObjectName("virtualrouterelement"); + return response; + } + + @Override + public LBStickinessResponse createLBStickinessPolicyResponse( + StickinessPolicy stickinessPolicy, LoadBalancer lb) { + LBStickinessResponse spResponse = new LBStickinessResponse(); + + spResponse.setlbRuleId(lb.getId()); + Account accountTemp = ApiDBUtils.findAccountById(lb.getAccountId()); + if (accountTemp != null) { + spResponse.setAccountName(accountTemp.getAccountName()); + spResponse.setDomainId(accountTemp.getDomainId()); + spResponse.setDomainName(ApiDBUtils.findDomainById( + accountTemp.getDomainId()).getName()); + } + + List responses = new ArrayList(); + LBStickinessPolicyResponse ruleResponse = new LBStickinessPolicyResponse( + stickinessPolicy); + responses.add(ruleResponse); + + spResponse.setRules(responses); + + spResponse.setObjectName("stickinesspolicies"); + return spResponse; + } + + @Override + public LBStickinessResponse createLBStickinessPolicyResponse( + List stickinessPolicies, LoadBalancer lb) { + LBStickinessResponse spResponse = new LBStickinessResponse(); + + if (lb == null) + return spResponse; + spResponse.setlbRuleId(lb.getId()); + Account account = ApiDBUtils.findAccountById(lb.getAccountId()); + if (account != null) { + spResponse.setAccountName(account.getAccountName()); + spResponse.setDomainId(account.getDomainId()); + spResponse.setDomainName(ApiDBUtils.findDomainById( + account.getDomainId()).getName()); + } + + List responses = new ArrayList(); + for (StickinessPolicy stickinessPolicy : stickinessPolicies) { + LBStickinessPolicyResponse ruleResponse = new LBStickinessPolicyResponse(stickinessPolicy); + responses.add(ruleResponse); + } + spResponse.setRules(responses); + + spResponse.setObjectName("stickinesspolicies"); + return spResponse; + } + + @Override + public LDAPConfigResponse createLDAPConfigResponse(String hostname, + Integer port, Boolean useSSL, String queryFilter, + String searchBase, String bindDN) { + LDAPConfigResponse lr = new LDAPConfigResponse(); + lr.setHostname(hostname); + lr.setPort(port.toString()); + lr.setUseSSL(useSSL.toString()); + lr.setQueryFilter(queryFilter); + lr.setBindDN(bindDN); + lr.setSearchBase(searchBase); + lr.setObjectName("ldapconfig"); + return lr; + } + + @Override + public StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result) { + StorageNetworkIpRangeResponse response = new StorageNetworkIpRangeResponse(); + response.setUuid(result.getUuid()); + response.setVlan(result.getVlan()); + response.setEndIp(result.getEndIp()); + response.setStartIp(result.getStartIp()); + response.setPodUuid(result.getPodUuid()); + response.setZoneUuid(result.getZoneUuid()); + response.setNetworkUuid(result.getNetworkUuid()); + response.setNetmask(result.getNetmask()); + response.setGateway(result.getGateway()); response.setObjectName("storagenetworkiprange"); - return response; - } - -} + return response; + } + +} diff --git a/server/src/com/cloud/api/ApiSerializerHelper.java b/server/src/com/cloud/api/ApiSerializerHelper.java index 232cbd7d547..bd7fd015837 100644 --- a/server/src/com/cloud/api/ApiSerializerHelper.java +++ b/server/src/com/cloud/api/ApiSerializerHelper.java @@ -10,68 +10,68 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -public class ApiSerializerHelper { - public static final Logger s_logger = Logger.getLogger(ApiSerializerHelper.class.getName()); - public static String token = "/"; - - public static String toSerializedStringOld(Object result) { - if (result != null) { - Class clz = result.getClass(); - Gson gson = ApiGsonHelper.getBuilder().create(); - - if (result instanceof ResponseObject) { - return clz.getName() + token + ((ResponseObject) result).getObjectName() + token + gson.toJson(result); - } else { - return clz.getName() + token + gson.toJson(result); - } - } - return null; - } - - public static Object fromSerializedString(String result) { - try { - if (result != null && !result.isEmpty()) { - - String[] serializedParts = result.split(token); - - if (serializedParts.length < 2) { - return null; - } - String clzName = serializedParts[0]; - String nameField = null; - String content = null; - if (serializedParts.length == 2) { - content = serializedParts[1]; - } else { - nameField = serializedParts[1]; - int index = result.indexOf(token + nameField + token); - content = result.substring(index + nameField.length() + 2); - } - - Class clz; - try { - clz = Class.forName(clzName); - } catch (ClassNotFoundException e) { - return null; - } - - Gson gson = ApiGsonHelper.getBuilder().create(); - Object obj = gson.fromJson(content, clz); - if (nameField != null) { - ((ResponseObject) obj).setObjectName(nameField); - } - return obj; - } - return null; - } catch (RuntimeException e) { - s_logger.error("Caught runtime exception when doing GSON deserialization on: " + result); - throw e; - } - } -} +package com.cloud.api; + +import org.apache.log4j.Logger; + +import com.google.gson.Gson; + +public class ApiSerializerHelper { + public static final Logger s_logger = Logger.getLogger(ApiSerializerHelper.class.getName()); + public static String token = "/"; + + public static String toSerializedStringOld(Object result) { + if (result != null) { + Class clz = result.getClass(); + Gson gson = ApiGsonHelper.getBuilder().create(); + + if (result instanceof ResponseObject) { + return clz.getName() + token + ((ResponseObject) result).getObjectName() + token + gson.toJson(result); + } else { + return clz.getName() + token + gson.toJson(result); + } + } + return null; + } + + public static Object fromSerializedString(String result) { + try { + if (result != null && !result.isEmpty()) { + + String[] serializedParts = result.split(token); + + if (serializedParts.length < 2) { + return null; + } + String clzName = serializedParts[0]; + String nameField = null; + String content = null; + if (serializedParts.length == 2) { + content = serializedParts[1]; + } else { + nameField = serializedParts[1]; + int index = result.indexOf(token + nameField + token); + content = result.substring(index + nameField.length() + 2); + } + + Class clz; + try { + clz = Class.forName(clzName); + } catch (ClassNotFoundException e) { + return null; + } + + Gson gson = ApiGsonHelper.getBuilder().create(); + Object obj = gson.fromJson(content, clz); + if (nameField != null) { + ((ResponseObject) obj).setObjectName(nameField); + } + return obj; + } + return null; + } catch (RuntimeException e) { + s_logger.error("Caught runtime exception when doing GSON deserialization on: " + result); + throw e; + } + } +} diff --git a/server/src/com/cloud/api/IdentityTypeAdapter.java b/server/src/com/cloud/api/IdentityTypeAdapter.java index 21b3e5385bf..e1fb80f09a8 100644 --- a/server/src/com/cloud/api/IdentityTypeAdapter.java +++ b/server/src/com/cloud/api/IdentityTypeAdapter.java @@ -10,68 +10,68 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api; - -import java.lang.reflect.Type; -import java.util.ArrayList; - -import com.cloud.uuididentity.dao.IdentityDao; -import com.cloud.uuididentity.dao.IdentityDaoImpl; -import com.google.gson.Gson; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.cloud.utils.IdentityProxy; - - -public class IdentityTypeAdapter implements JsonSerializer, JsonDeserializer { - - @Override - public JsonElement serialize(IdentityProxy src, Type srcType, JsonSerializationContext context) { - if(SerializationContext.current().getUuidTranslation()) { - assert(src != null); - if(src.getValue() == null) - return context.serialize(null); - - IdentityDao identityDao = new IdentityDaoImpl(); - if(src.getTableName() != null) { - String uuid = identityDao.getIdentityUuid(src.getTableName(), String.valueOf(src.getValue())); - if(uuid == null) - return context.serialize(null); - - // Exceptions set the _idFieldName in the IdentityProxy structure. So if this field is not - // null, prepare a structure of uuid and idFieldName and return the json representation of that. - String idName = src.getidFieldName(); - if (idName != null) { - // Prepare a structure. - JsonObject jsonObj = new JsonObject(); - jsonObj.add("uuid", new JsonPrimitive(uuid)); - jsonObj.add("uuidProperty", new JsonPrimitive(idName)); - return jsonObj; - } - return new JsonPrimitive(uuid); - } else { - return new JsonPrimitive(String.valueOf(src.getValue())); - } - } else { - return new Gson().toJsonTree(src); - } - } - - @Override - public IdentityProxy deserialize(JsonElement src, Type srcType, - JsonDeserializationContext context) throws JsonParseException { - - IdentityProxy obj = new IdentityProxy(); - JsonObject json = src.getAsJsonObject(); - obj.setTableName(json.get("_tableName").getAsString()); - if(json.get("_value") != null) - obj.setValue(json.get("_value").getAsLong()); - return obj; - } -} +package com.cloud.api; + +import java.lang.reflect.Type; +import java.util.ArrayList; + +import com.cloud.uuididentity.dao.IdentityDao; +import com.cloud.uuididentity.dao.IdentityDaoImpl; +import com.google.gson.Gson; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.cloud.utils.IdentityProxy; + + +public class IdentityTypeAdapter implements JsonSerializer, JsonDeserializer { + + @Override + public JsonElement serialize(IdentityProxy src, Type srcType, JsonSerializationContext context) { + if(SerializationContext.current().getUuidTranslation()) { + assert(src != null); + if(src.getValue() == null) + return context.serialize(null); + + IdentityDao identityDao = new IdentityDaoImpl(); + if(src.getTableName() != null) { + String uuid = identityDao.getIdentityUuid(src.getTableName(), String.valueOf(src.getValue())); + if(uuid == null) + return context.serialize(null); + + // Exceptions set the _idFieldName in the IdentityProxy structure. So if this field is not + // null, prepare a structure of uuid and idFieldName and return the json representation of that. + String idName = src.getidFieldName(); + if (idName != null) { + // Prepare a structure. + JsonObject jsonObj = new JsonObject(); + jsonObj.add("uuid", new JsonPrimitive(uuid)); + jsonObj.add("uuidProperty", new JsonPrimitive(idName)); + return jsonObj; + } + return new JsonPrimitive(uuid); + } else { + return new JsonPrimitive(String.valueOf(src.getValue())); + } + } else { + return new Gson().toJsonTree(src); + } + } + + @Override + public IdentityProxy deserialize(JsonElement src, Type srcType, + JsonDeserializationContext context) throws JsonParseException { + + IdentityProxy obj = new IdentityProxy(); + JsonObject json = src.getAsJsonObject(); + obj.setTableName(json.get("_tableName").getAsString()); + if(json.get("_value") != null) + obj.setValue(json.get("_value").getAsLong()); + return obj; + } +} diff --git a/server/src/com/cloud/api/SerializationContext.java b/server/src/com/cloud/api/SerializationContext.java index 749f69ed2eb..7fe8aa4f3b9 100644 --- a/server/src/com/cloud/api/SerializationContext.java +++ b/server/src/com/cloud/api/SerializationContext.java @@ -10,30 +10,30 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api; - -public class SerializationContext { - private static ThreadLocal s_currentContext = new ThreadLocal(); - - private boolean _doUuidTranslation = false; - - public SerializationContext() { - } - - public static SerializationContext current() { - SerializationContext context = s_currentContext.get(); - if(context == null) { - context = new SerializationContext(); - s_currentContext.set(context); - } - return context; - } - - public boolean getUuidTranslation() { - return _doUuidTranslation; - } - - public void setUuidTranslation(boolean value) { - _doUuidTranslation = value; - } -} +package com.cloud.api; + +public class SerializationContext { + private static ThreadLocal s_currentContext = new ThreadLocal(); + + private boolean _doUuidTranslation = false; + + public SerializationContext() { + } + + public static SerializationContext current() { + SerializationContext context = s_currentContext.get(); + if(context == null) { + context = new SerializationContext(); + s_currentContext.set(context); + } + return context; + } + + public boolean getUuidTranslation() { + return _doUuidTranslation; + } + + public void setUuidTranslation(boolean value) { + _doUuidTranslation = value; + } +} diff --git a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java index fd6b2c4e0fa..3a506dc7613 100644 --- a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java @@ -10,81 +10,81 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api.commands; - -import java.util.Date; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; +package com.cloud.api.commands; + +import java.util.Date; + +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.SuccessResponse; -import com.cloud.server.ManagementServerExt; -import com.cloud.user.Account; - -@Implementation(description="Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed", responseObject=SuccessResponse.class) -public class GenerateUsageRecordsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GenerateUsageRecordsCmd.class.getName()); - - private static final String s_name = "generateusagerecordsresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.server.ManagementServerExt; +import com.cloud.user.Account; + +@Implementation(description="Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed", responseObject=SuccessResponse.class) +public class GenerateUsageRecordsCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(GenerateUsageRecordsCmd.class.getName()); + + private static final String s_name = "generateusagerecordsresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List events for the specified domain.") - private Long domainId; - - @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") - private Date endDate; - - @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") - private Date startDate; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getDomainId() { - return domainId; - } - - public Date getEndDate() { - return endDate; - } - - public Date getStartDate() { - return startDate; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - @Override - public void execute(){ - ManagementServerExt _mgrExt = (ManagementServerExt)_mgr; - boolean result = _mgrExt.generateUsageRecords(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to generate usage records"); - } - } -} + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List events for the specified domain.") + private Long domainId; + + @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") + private Date endDate; + + @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") + private Date startDate; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getDomainId() { + return domainId; + } + + public Date getEndDate() { + return endDate; + } + + public Date getStartDate() { + return startDate; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + ManagementServerExt _mgrExt = (ManagementServerExt)_mgr; + boolean result = _mgrExt.generateUsageRecords(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to generate usage records"); + } + } +} diff --git a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java index 559fbd12609..918b5c45bfa 100644 --- a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api.commands; - +package com.cloud.api.commands; + import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; @@ -36,32 +36,32 @@ import com.cloud.usage.UsageVO; import com.cloud.user.Account; import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDaoImpl; - -@Implementation(description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) -public class GetUsageRecordsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(GetUsageRecordsCmd.class.getName()); - + +@Implementation(description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) +public class GetUsageRecordsCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(GetUsageRecordsCmd.class.getName()); + private static final String s_name = "listusagerecordsresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="List usage records for the specified user.") - private String accountName; - + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="List usage records for the specified user.") + private String accountName; + @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List usage records for the specified domain.") - private Long domainId; - - @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") - private Date endDate; - - @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") - private Date startDate; - + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List usage records for the specified domain.") + private Long domainId; + + @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") + private Date endDate; + + @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") + private Date startDate; + @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, description="List usage records for the specified account") + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, description="List usage records for the specified account") private Long accountId; @IdentityMapper(entityTableName="projects") @@ -69,30 +69,30 @@ public class GetUsageRecordsCmd extends BaseListCmd { private Long projectId; @Parameter(name=ApiConstants.TYPE, type=CommandType.LONG, description="List usage records for the specified usage type") - private Long usageType; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getAccountName() { - return accountName; - } - - public Long getDomainId() { - return domainId; - } - - public Date getEndDate() { - return endDate; - } + private Long usageType; - public Date getStartDate() { - return startDate; - } - - public Long getAccountId() { - return accountId; + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public String getAccountName() { + return accountName; + } + + public Long getDomainId() { + return domainId; + } + + public Date getEndDate() { + return endDate; + } + + public Date getStartDate() { + return startDate; + } + + public Long getAccountId() { + return accountId; } public Long getUsageType() { @@ -102,125 +102,125 @@ public class GetUsageRecordsCmd extends BaseListCmd { public Long getProjectId() { return projectId; } - - ///////////////////////////////////////////////////// - /////////////// Misc parameters /////////////////// - ///////////////////////////////////////////////////// + + ///////////////////////////////////////////////////// + /////////////// Misc parameters /////////////////// + ///////////////////////////////////////////////////// private TimeZone usageTimezone; - - public TimeZone getUsageTimezone() { - return usageTimezone; - } - - public void setUsageTimezone(TimeZone tz) { - this.usageTimezone = tz; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - public String getDateStringInternal(Date inputDate) { - if (inputDate == null) return null; - - TimeZone tz = getUsageTimezone(); - Calendar cal = Calendar.getInstance(tz); - cal.setTime(inputDate); - - StringBuffer sb = new StringBuffer(); - sb.append(cal.get(Calendar.YEAR)+"-"); - - int month = cal.get(Calendar.MONTH) + 1; - if (month < 10) { - sb.append("0" + month + "-"); - } else { - sb.append(month+"-"); - } - - int day = cal.get(Calendar.DAY_OF_MONTH); - if (day < 10) { - sb.append("0" + day); - } else { - sb.append(""+day); - } - - sb.append("'T'"); - - int hour = cal.get(Calendar.HOUR_OF_DAY); - if (hour < 10) { - sb.append("0" + hour + ":"); - } else { - sb.append(hour+":"); - } - - int minute = cal.get(Calendar.MINUTE); - if (minute < 10) { - sb.append("0" + minute + ":"); - } else { - sb.append(minute+":"); - } - - int seconds = cal.get(Calendar.SECOND); - if (seconds < 10) { - sb.append("0" + seconds); - } else { - sb.append(""+seconds); - } - - double offset = cal.get(Calendar.ZONE_OFFSET); - if (tz.inDaylightTime(inputDate)) { - offset += (1.0*tz.getDSTSavings()); // add the timezone's DST value (typically 1 hour expressed in milliseconds) - } - - offset = offset / (1000d*60d*60d); - int hourOffset = (int)offset; - double decimalVal = Math.abs(offset) - Math.abs(hourOffset); - int minuteOffset = (int)(decimalVal * 60); - - if (hourOffset < 0) { - if (hourOffset > -10) { - sb.append("-0"+Math.abs(hourOffset)); - } else { - sb.append("-"+Math.abs(hourOffset)); - } - } else { - if (hourOffset < 10) { - sb.append("+0" + hourOffset); - } else { - sb.append("+" + hourOffset); - } - } - - sb.append(":"); - - if (minuteOffset == 0) { - sb.append("00"); - } else if (minuteOffset < 10) { - sb.append("0" + minuteOffset); - } else { - sb.append("" + minuteOffset); - } - - return sb.toString(); - } - - @Override - public void execute(){ - ManagementServerExt _mgrExt = (ManagementServerExt)_mgr; + + public TimeZone getUsageTimezone() { + return usageTimezone; + } + + public void setUsageTimezone(TimeZone tz) { + this.usageTimezone = tz; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public String getDateStringInternal(Date inputDate) { + if (inputDate == null) return null; + + TimeZone tz = getUsageTimezone(); + Calendar cal = Calendar.getInstance(tz); + cal.setTime(inputDate); + + StringBuffer sb = new StringBuffer(); + sb.append(cal.get(Calendar.YEAR)+"-"); + + int month = cal.get(Calendar.MONTH) + 1; + if (month < 10) { + sb.append("0" + month + "-"); + } else { + sb.append(month+"-"); + } + + int day = cal.get(Calendar.DAY_OF_MONTH); + if (day < 10) { + sb.append("0" + day); + } else { + sb.append(""+day); + } + + sb.append("'T'"); + + int hour = cal.get(Calendar.HOUR_OF_DAY); + if (hour < 10) { + sb.append("0" + hour + ":"); + } else { + sb.append(hour+":"); + } + + int minute = cal.get(Calendar.MINUTE); + if (minute < 10) { + sb.append("0" + minute + ":"); + } else { + sb.append(minute+":"); + } + + int seconds = cal.get(Calendar.SECOND); + if (seconds < 10) { + sb.append("0" + seconds); + } else { + sb.append(""+seconds); + } + + double offset = cal.get(Calendar.ZONE_OFFSET); + if (tz.inDaylightTime(inputDate)) { + offset += (1.0*tz.getDSTSavings()); // add the timezone's DST value (typically 1 hour expressed in milliseconds) + } + + offset = offset / (1000d*60d*60d); + int hourOffset = (int)offset; + double decimalVal = Math.abs(offset) - Math.abs(hourOffset); + int minuteOffset = (int)(decimalVal * 60); + + if (hourOffset < 0) { + if (hourOffset > -10) { + sb.append("-0"+Math.abs(hourOffset)); + } else { + sb.append("-"+Math.abs(hourOffset)); + } + } else { + if (hourOffset < 10) { + sb.append("+0" + hourOffset); + } else { + sb.append("+" + hourOffset); + } + } + + sb.append(":"); + + if (minuteOffset == 0) { + sb.append("00"); + } else if (minuteOffset < 10) { + sb.append("0" + minuteOffset); + } else { + sb.append("" + minuteOffset); + } + + return sb.toString(); + } + + @Override + public void execute(){ + ManagementServerExt _mgrExt = (ManagementServerExt)_mgr; List usageRecords = _mgrExt.getUsageRecords(this); - IdentityDao identityDao = new IdentityDaoImpl(); - ListResponse response = new ListResponse(); - List usageResponses = new ArrayList(); - for (Object usageRecordGeneric : usageRecords) { - UsageRecordResponse usageRecResponse = new UsageRecordResponse(); - if (usageRecordGeneric instanceof UsageVO) { - UsageVO usageRecord = (UsageVO)usageRecordGeneric; + IdentityDao identityDao = new IdentityDaoImpl(); + ListResponse response = new ListResponse(); + List usageResponses = new ArrayList(); + for (Object usageRecordGeneric : usageRecords) { + UsageRecordResponse usageRecResponse = new UsageRecordResponse(); + if (usageRecordGeneric instanceof UsageVO) { + UsageVO usageRecord = (UsageVO)usageRecordGeneric; Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { @@ -234,12 +234,12 @@ public class GetUsageRecordsCmd extends BaseListCmd { } usageRecResponse.setDomainId(usageRecord.getDomainId()); - - usageRecResponse.setZoneId(usageRecord.getZoneId()); - usageRecResponse.setDescription(usageRecord.getDescription()); - usageRecResponse.setUsage(usageRecord.getUsageDisplay()); - usageRecResponse.setUsageType(usageRecord.getUsageType()); - usageRecResponse.setVirtualMachineId(usageRecord.getVmInstanceId()); + + usageRecResponse.setZoneId(usageRecord.getZoneId()); + usageRecResponse.setDescription(usageRecord.getDescription()); + usageRecResponse.setUsage(usageRecord.getUsageDisplay()); + usageRecResponse.setUsageType(usageRecord.getUsageType()); + usageRecResponse.setVirtualMachineId(usageRecord.getVmInstanceId()); usageRecResponse.setVmName(usageRecord.getVmName()); usageRecResponse.setTemplateId(usageRecord.getTemplateId()); @@ -317,25 +317,25 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("security_group", usageRecord.getUsageId().toString())); } - if (usageRecord.getRawUsage() != null) { - DecimalFormat decimalFormat = new DecimalFormat("###########.######"); - usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage())); - } - - if (usageRecord.getStartDate() != null) { - usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate())); - } - if (usageRecord.getEndDate() != null) { - usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate())); - } - } - - usageRecResponse.setObjectName("usagerecord"); - usageResponses.add(usageRecResponse); - } - - response.setResponses(usageResponses); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } -} + if (usageRecord.getRawUsage() != null) { + DecimalFormat decimalFormat = new DecimalFormat("###########.######"); + usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage())); + } + + if (usageRecord.getStartDate() != null) { + usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate())); + } + if (usageRecord.getEndDate() != null) { + usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate())); + } + } + + usageRecResponse.setObjectName("usagerecord"); + usageResponses.add(usageRecResponse); + } + + response.setResponses(usageResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } +} diff --git a/server/src/com/cloud/api/response/SecurityGroupRuleResultObject.java b/server/src/com/cloud/api/response/SecurityGroupRuleResultObject.java index fbe93810f95..43efac553cf 100644 --- a/server/src/com/cloud/api/response/SecurityGroupRuleResultObject.java +++ b/server/src/com/cloud/api/response/SecurityGroupRuleResultObject.java @@ -10,58 +10,58 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.api.response; +package com.cloud.api.response; import com.cloud.network.security.SecurityRule.SecurityRuleType; -import com.cloud.serializer.Param; - -public class SecurityGroupRuleResultObject { - @Param(name="id") - private Long id; - - @Param(name="startport") - private int startPort; - - @Param(name="endport") - private int endPort; - - @Param(name="protocol") - private String protocol; - - @Param(name="securitygroup") - private String allowedSecurityGroup = null; - - @Param(name="account") - private String allowedSecGroupAcct = null; - - @Param(name="cidr") +import com.cloud.serializer.Param; + +public class SecurityGroupRuleResultObject { + @Param(name="id") + private Long id; + + @Param(name="startport") + private int startPort; + + @Param(name="endport") + private int endPort; + + @Param(name="protocol") + private String protocol; + + @Param(name="securitygroup") + private String allowedSecurityGroup = null; + + @Param(name="account") + private String allowedSecGroupAcct = null; + + @Param(name="cidr") private String allowedSourceIpCidr = null; - private SecurityRuleType type; - - public SecurityGroupRuleResultObject() { } - - public SecurityGroupRuleResultObject(Long id, int startPort, int endPort, String protocol, String allowedSecurityGroup, String allowedSecGroupAcct, String allowedSourceIpCidr) { - this.id = id; - this.startPort = startPort; - this.endPort = endPort; - this.protocol = protocol; - this.allowedSecurityGroup = allowedSecurityGroup; - this.allowedSecGroupAcct = allowedSecGroupAcct; - this.allowedSourceIpCidr = allowedSourceIpCidr; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public int getStartPort() { - return startPort; - } + private SecurityRuleType type; + + public SecurityGroupRuleResultObject() { } + + public SecurityGroupRuleResultObject(Long id, int startPort, int endPort, String protocol, String allowedSecurityGroup, String allowedSecGroupAcct, String allowedSourceIpCidr) { + this.id = id; + this.startPort = startPort; + this.endPort = endPort; + this.protocol = protocol; + this.allowedSecurityGroup = allowedSecurityGroup; + this.allowedSecGroupAcct = allowedSecGroupAcct; + this.allowedSourceIpCidr = allowedSourceIpCidr; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public int getStartPort() { + return startPort; + } public void setRuleType(SecurityRuleType type) { this.type = type; @@ -71,48 +71,48 @@ public class SecurityGroupRuleResultObject { public SecurityRuleType getRuleType() { return type; } - - public void setStartPort(int startPort) { - this.startPort = startPort; - } - - public int getEndPort() { - return endPort; - } - - public void setEndPort(int endPort) { - this.endPort = endPort; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getAllowedSecurityGroup() { - return allowedSecurityGroup; - } - - public void setAllowedSecurityGroup(String allowedSecurityGroup) { - this.allowedSecurityGroup = allowedSecurityGroup; - } - - public String getAllowedSecGroupAcct() { - return allowedSecGroupAcct; - } - - public void setAllowedSecGroupAcct(String allowedSecGroupAcct) { - this.allowedSecGroupAcct = allowedSecGroupAcct; - } - - public String getAllowedSourceIpCidr() { - return allowedSourceIpCidr; - } - - public void setAllowedSourceIpCidr(String allowedSourceIpCidr) { - this.allowedSourceIpCidr = allowedSourceIpCidr; - } -} + + public void setStartPort(int startPort) { + this.startPort = startPort; + } + + public int getEndPort() { + return endPort; + } + + public void setEndPort(int endPort) { + this.endPort = endPort; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getAllowedSecurityGroup() { + return allowedSecurityGroup; + } + + public void setAllowedSecurityGroup(String allowedSecurityGroup) { + this.allowedSecurityGroup = allowedSecurityGroup; + } + + public String getAllowedSecGroupAcct() { + return allowedSecGroupAcct; + } + + public void setAllowedSecGroupAcct(String allowedSecGroupAcct) { + this.allowedSecGroupAcct = allowedSecGroupAcct; + } + + public String getAllowedSourceIpCidr() { + return allowedSourceIpCidr; + } + + public void setAllowedSourceIpCidr(String allowedSourceIpCidr) { + this.allowedSourceIpCidr = allowedSourceIpCidr; + } +} diff --git a/server/src/com/cloud/async/AsyncJobExecutor.java b/server/src/com/cloud/async/AsyncJobExecutor.java index c1846c0d2c5..f62bff60b55 100644 --- a/server/src/com/cloud/async/AsyncJobExecutor.java +++ b/server/src/com/cloud/async/AsyncJobExecutor.java @@ -10,26 +10,26 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; +package com.cloud.async; + + +public interface AsyncJobExecutor { + public AsyncJobManager getAsyncJobMgr(); + public void setAsyncJobMgr(AsyncJobManager asyncMgr); + public SyncQueueItemVO getSyncSource(); + public void setSyncSource(SyncQueueItemVO syncSource); + public AsyncJobVO getJob(); + public void setJob(AsyncJobVO job); + public void setFromPreviousSession(boolean value); + public boolean isFromPreviousSession(); + + /** + * + * otherwise return false and once the executor finally has completed with the sync source, + * it needs to call AsyncJobManager.releaseSyncSource + * + * if executor does not have a sync source, always return true + */ + public boolean execute(); +} - -public interface AsyncJobExecutor { - public AsyncJobManager getAsyncJobMgr(); - public void setAsyncJobMgr(AsyncJobManager asyncMgr); - public SyncQueueItemVO getSyncSource(); - public void setSyncSource(SyncQueueItemVO syncSource); - public AsyncJobVO getJob(); - public void setJob(AsyncJobVO job); - public void setFromPreviousSession(boolean value); - public boolean isFromPreviousSession(); - - /** - * - * otherwise return false and once the executor finally has completed with the sync source, - * it needs to call AsyncJobManager.releaseSyncSource - * - * if executor does not have a sync source, always return true - */ - public boolean execute(); -} - diff --git a/server/src/com/cloud/async/AsyncJobExecutorContext.java b/server/src/com/cloud/async/AsyncJobExecutorContext.java index b29e849acae..7d558907050 100644 --- a/server/src/com/cloud/async/AsyncJobExecutorContext.java +++ b/server/src/com/cloud/async/AsyncJobExecutorContext.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import com.cloud.agent.AgentManager; import com.cloud.async.dao.AsyncJobDao; import com.cloud.event.dao.EventDao; @@ -29,22 +29,22 @@ import com.cloud.vm.UserVmManager; import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; - -public interface AsyncJobExecutorContext extends Manager { - public ManagementServer getManagementServer(); - public AgentManager getAgentMgr(); - public NetworkManager getNetworkMgr(); - public UserVmManager getVmMgr(); - public SnapshotManager getSnapshotMgr(); + +public interface AsyncJobExecutorContext extends Manager { + public ManagementServer getManagementServer(); + public AgentManager getAgentMgr(); + public NetworkManager getNetworkMgr(); + public UserVmManager getVmMgr(); + public SnapshotManager getSnapshotMgr(); public AccountManager getAccountMgr(); - public StorageManager getStorageMgr(); - public EventDao getEventDao(); - public UserVmDao getVmDao(); - public AccountDao getAccountDao(); - public VolumeDao getVolumeDao(); - public DomainRouterDao getRouterDao(); + public StorageManager getStorageMgr(); + public EventDao getEventDao(); + public UserVmDao getVmDao(); + public AccountDao getAccountDao(); + public VolumeDao getVolumeDao(); + public DomainRouterDao getRouterDao(); public IPAddressDao getIpAddressDao(); public AsyncJobDao getJobDao(); public UserDao getUserDao(); public VirtualMachineManager getItMgr(); -} +} diff --git a/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java b/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java index 65346cf833f..d8d60151c01 100644 --- a/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java +++ b/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.Map; import javax.ejb.Local; @@ -34,97 +34,97 @@ import com.cloud.vm.UserVmManager; import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; - -@Local(value={AsyncJobExecutorContext.class}) -public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext { - private String _name; - - private AgentManager _agentMgr; - private NetworkManager _networkMgr; - private UserVmManager _vmMgr; - private SnapshotManager _snapMgr; + +@Local(value={AsyncJobExecutorContext.class}) +public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext { + private String _name; + + private AgentManager _agentMgr; + private NetworkManager _networkMgr; + private UserVmManager _vmMgr; + private SnapshotManager _snapMgr; private AccountManager _accountMgr; - private StorageManager _storageMgr; - private EventDao _eventDao; - private UserVmDao _vmDao; - private AccountDao _accountDao; - private VolumeDao _volumeDao; - private DomainRouterDao _routerDao; + private StorageManager _storageMgr; + private EventDao _eventDao; + private UserVmDao _vmDao; + private AccountDao _accountDao; + private VolumeDao _volumeDao; + private DomainRouterDao _routerDao; private IPAddressDao _ipAddressDao; private AsyncJobDao _jobDao; private UserDao _userDao; - private VirtualMachineManager _itMgr; - - private ManagementServer _managementServer; - - @Override - public ManagementServer getManagementServer() { - return _managementServer; - } - - @Override - public AgentManager getAgentMgr() { - return _agentMgr; - } - - @Override - public NetworkManager getNetworkMgr() { - return _networkMgr; - } - - @Override - public UserVmManager getVmMgr() { - return _vmMgr; + private VirtualMachineManager _itMgr; + + private ManagementServer _managementServer; + + @Override + public ManagementServer getManagementServer() { + return _managementServer; + } + + @Override + public AgentManager getAgentMgr() { + return _agentMgr; + } + + @Override + public NetworkManager getNetworkMgr() { + return _networkMgr; + } + + @Override + public UserVmManager getVmMgr() { + return _vmMgr; } @Override public StorageManager getStorageMgr() { return _storageMgr; - } - - /**server/src/com/cloud/async/AsyncJobExecutorContext.java - * @return the _snapMgr - */ - @Override - public SnapshotManager getSnapshotMgr() { - return _snapMgr; - } - - @Override - public AccountManager getAccountMgr() { - return _accountMgr; - } - - @Override - public EventDao getEventDao() { - return _eventDao; - } - - @Override - public UserVmDao getVmDao() { - return _vmDao; - } - - @Override - public AccountDao getAccountDao() { - return _accountDao; - } - - @Override - public VolumeDao getVolumeDao() { - return _volumeDao; - } - - @Override - public DomainRouterDao getRouterDao() { - return _routerDao; - } - - @Override - public IPAddressDao getIpAddressDao() { - return _ipAddressDao; + } + + /**server/src/com/cloud/async/AsyncJobExecutorContext.java + * @return the _snapMgr + */ + @Override + public SnapshotManager getSnapshotMgr() { + return _snapMgr; } - + + @Override + public AccountManager getAccountMgr() { + return _accountMgr; + } + + @Override + public EventDao getEventDao() { + return _eventDao; + } + + @Override + public UserVmDao getVmDao() { + return _vmDao; + } + + @Override + public AccountDao getAccountDao() { + return _accountDao; + } + + @Override + public VolumeDao getVolumeDao() { + return _volumeDao; + } + + @Override + public DomainRouterDao getRouterDao() { + return _routerDao; + } + + @Override + public IPAddressDao getIpAddressDao() { + return _ipAddressDao; + } + @Override public AsyncJobDao getJobDao() { return _jobDao; @@ -139,75 +139,75 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext { public VirtualMachineManager getItMgr() { return _itMgr; } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - - _managementServer = (ManagementServer)ComponentLocator.getComponent("management-server"); - if (_managementServer == null) { - throw new ConfigurationException("unable to get " + ManagementServer.class.getName()); - } - - _agentMgr = locator.getManager(AgentManager.class); - if (_agentMgr == null) { - throw new ConfigurationException("unable to get " + AgentManager.class.getName()); - } - - _networkMgr = locator.getManager(NetworkManager.class); - if (_networkMgr == null) { - throw new ConfigurationException("unable to get " + NetworkManager.class.getName()); - } - - _vmMgr = locator.getManager(UserVmManager.class); - if (_vmMgr == null) { - throw new ConfigurationException("unable to get " + UserVmManager.class.getName()); - } - - _snapMgr = locator.getManager(SnapshotManager.class); - if (_snapMgr == null) { - throw new ConfigurationException("unable to get " + SnapshotManager.class.getName()); - } - - _accountMgr = locator.getManager(AccountManager.class); - if (_accountMgr == null) { - throw new ConfigurationException("unable to get " + AccountManager.class.getName()); + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + + _managementServer = (ManagementServer)ComponentLocator.getComponent("management-server"); + if (_managementServer == null) { + throw new ConfigurationException("unable to get " + ManagementServer.class.getName()); + } + + _agentMgr = locator.getManager(AgentManager.class); + if (_agentMgr == null) { + throw new ConfigurationException("unable to get " + AgentManager.class.getName()); + } + + _networkMgr = locator.getManager(NetworkManager.class); + if (_networkMgr == null) { + throw new ConfigurationException("unable to get " + NetworkManager.class.getName()); + } + + _vmMgr = locator.getManager(UserVmManager.class); + if (_vmMgr == null) { + throw new ConfigurationException("unable to get " + UserVmManager.class.getName()); + } + + _snapMgr = locator.getManager(SnapshotManager.class); + if (_snapMgr == null) { + throw new ConfigurationException("unable to get " + SnapshotManager.class.getName()); + } + + _accountMgr = locator.getManager(AccountManager.class); + if (_accountMgr == null) { + throw new ConfigurationException("unable to get " + AccountManager.class.getName()); } _storageMgr = locator.getManager(StorageManager.class); if (_storageMgr == null) { throw new ConfigurationException("unable to get " + StorageManager.class.getName()); - } - - _eventDao = locator.getDao(EventDao.class); - if (_eventDao == null) { - throw new ConfigurationException("unable to get " + EventDao.class.getName()); - } - - _vmDao = locator.getDao(UserVmDao.class); - if (_vmDao == null) { - throw new ConfigurationException("unable to get " + UserVmDao.class.getName()); - } - - _accountDao = locator.getDao(AccountDao.class); - if (_accountDao == null) { - throw new ConfigurationException("unable to get " + AccountDao.class.getName()); - } - - _volumeDao = locator.getDao(VolumeDao.class); - if (_volumeDao == null) { - throw new ConfigurationException("unable to get " + VolumeDao.class.getName()); - } - - _routerDao = locator.getDao(DomainRouterDao.class); - if (_routerDao == null) { - throw new ConfigurationException("unable to get " + DomainRouterDao.class.getName()); - } - - _ipAddressDao = locator.getDao(IPAddressDao.class); - if (_ipAddressDao == null) { - throw new ConfigurationException("unable to get " + IPAddressDao.class.getName()); + } + + _eventDao = locator.getDao(EventDao.class); + if (_eventDao == null) { + throw new ConfigurationException("unable to get " + EventDao.class.getName()); + } + + _vmDao = locator.getDao(UserVmDao.class); + if (_vmDao == null) { + throw new ConfigurationException("unable to get " + UserVmDao.class.getName()); + } + + _accountDao = locator.getDao(AccountDao.class); + if (_accountDao == null) { + throw new ConfigurationException("unable to get " + AccountDao.class.getName()); + } + + _volumeDao = locator.getDao(VolumeDao.class); + if (_volumeDao == null) { + throw new ConfigurationException("unable to get " + VolumeDao.class.getName()); + } + + _routerDao = locator.getDao(DomainRouterDao.class); + if (_routerDao == null) { + throw new ConfigurationException("unable to get " + DomainRouterDao.class.getName()); + } + + _ipAddressDao = locator.getDao(IPAddressDao.class); + if (_ipAddressDao == null) { + throw new ConfigurationException("unable to get " + IPAddressDao.class.getName()); } _jobDao = locator.getDao(AsyncJobDao.class); @@ -223,22 +223,22 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext { _itMgr = locator.getManager(VirtualMachineManager.class); if (_itMgr == null) { throw new ConfigurationException("unable to get " + VirtualMachineManager.class.getName()); - } - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } -} + } + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } +} diff --git a/server/src/com/cloud/async/AsyncJobManager.java b/server/src/com/cloud/async/AsyncJobManager.java index 9e11d6d18c2..884f24629cc 100644 --- a/server/src/com/cloud/async/AsyncJobManager.java +++ b/server/src/com/cloud/async/AsyncJobManager.java @@ -10,29 +10,29 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.List; import com.cloud.api.commands.QueryAsyncJobResultCmd; import com.cloud.utils.component.Manager; - + public interface AsyncJobManager extends Manager { - - public AsyncJobExecutorContext getExecutorContext(); - - public AsyncJobVO getAsyncJob(long jobId); + + public AsyncJobExecutorContext getExecutorContext(); + + public AsyncJobVO getAsyncJob(long jobId); public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId); - public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId); - - public long submitAsyncJob(AsyncJobVO job); - public long submitAsyncJob(AsyncJobVO job, boolean scheduleJobExecutionInContext); + public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId); + + public long submitAsyncJob(AsyncJobVO job); + public long submitAsyncJob(AsyncJobVO job, boolean scheduleJobExecutionInContext); public AsyncJobResult queryAsyncJobResult(long jobId); - - public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject); - public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject); - public void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId); - + + public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject); + public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject); + public void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId); + public void releaseSyncSource(AsyncJobExecutor executor); public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId); @@ -42,5 +42,5 @@ public interface AsyncJobManager extends Manager { * @param cmd the command that specifies the job id * @return an async-call result object */ - public AsyncJob queryAsyncJobResult(QueryAsyncJobResultCmd cmd); -} + public AsyncJob queryAsyncJobResult(QueryAsyncJobResultCmd cmd); +} diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java index dcb744a3361..734f5bd03a8 100644 --- a/server/src/com/cloud/async/AsyncJobManagerImpl.java +++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Type; @@ -68,182 +68,182 @@ import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.net.MacAddress; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; - -@Local(value={AsyncJobManager.class}) -public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { - public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); + +@Local(value={AsyncJobManager.class}) +public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { + public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds - - private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; + + private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; private static final int HEARTBEAT_INTERVAL = 2000; private static final int GC_INTERVAL = 10000; // 10 seconds - - private String _name; - - private AsyncJobExecutorContext _context; - private SyncQueueManager _queueMgr; + + private String _name; + + private AsyncJobExecutorContext _context; + private SyncQueueManager _queueMgr; private ClusterManager _clusterMgr; - private AccountManager _accountMgr; + private AccountManager _accountMgr; private AccountDao _accountDao; private AsyncJobDao _jobDao; private long _jobExpireSeconds = 86400; // 1 day private long _jobCancelThresholdSeconds = 3600; // 1 hour - private ApiDispatcher _dispatcher; - - private final ScheduledExecutorService _heartbeatScheduler = - Executors.newScheduledThreadPool(1, new NamedThreadFactory("AsyncJobMgr-Heartbeat")); - private ExecutorService _executor; - - @Override - public AsyncJobExecutorContext getExecutorContext() { - return _context; - } - - @Override - public AsyncJobVO getAsyncJob(long jobId) { - return _jobDao.findById(jobId); - } - - @Override - public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { - return _jobDao.findInstancePendingAsyncJob(instanceType, instanceId); + private ApiDispatcher _dispatcher; + + private final ScheduledExecutorService _heartbeatScheduler = + Executors.newScheduledThreadPool(1, new NamedThreadFactory("AsyncJobMgr-Heartbeat")); + private ExecutorService _executor; + + @Override + public AsyncJobExecutorContext getExecutorContext() { + return _context; + } + + @Override + public AsyncJobVO getAsyncJob(long jobId) { + return _jobDao.findById(jobId); + } + + @Override + public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { + return _jobDao.findInstancePendingAsyncJob(instanceType, instanceId); } @Override public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId) { return _jobDao.findInstancePendingAsyncJobs(instanceType, accountId); - } - - @Override - public long submitAsyncJob(AsyncJobVO job) { - return submitAsyncJob(job, false); - } + } + + @Override + public long submitAsyncJob(AsyncJobVO job) { + return submitAsyncJob(job, false); + } - @Override @DB + @Override @DB public long submitAsyncJob(AsyncJobVO job, boolean scheduleJobExecutionInContext) { - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); job.setInitMsid(getMsid()); - _jobDao.persist(job); - txt.commit(); + _jobDao.persist(job); + txt.commit(); // no sync source originally - job.setSyncSource(null); + job.setSyncSource(null); scheduleExecution(job, scheduleJobExecutionInContext); if(s_logger.isDebugEnabled()) { s_logger.debug("submit async job-" + job.getId() + ", details: " + job.toString()); } - return job.getId(); + return job.getId(); } catch(Exception e) { txt.rollback(); String errMsg = "Unable to schedule async job for command " + job.getCmd() + ", unexpected exception."; s_logger.warn(errMsg, e); throw new CloudRuntimeException(errMsg); - } - } - - @Override @DB - public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject) { + } + } + + @Override @DB + public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + + s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + ", resultCode: " + resultCode + ", result: " + resultObject); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job == null) { + } + + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job == null) { if(s_logger.isDebugEnabled()) { - s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + + s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + ", resultCode: " + resultCode + ", result: " + resultObject); - } - - txt.rollback(); - return; - } + } + + txt.rollback(); + return; + } - job.setCompleteMsid(getMsid()); - job.setStatus(jobStatus); - job.setResultCode(resultCode); + job.setCompleteMsid(getMsid()); + job.setStatus(jobStatus); + job.setResultCode(resultCode); - // reset attached object - job.setInstanceType(null); - job.setInstanceId(null); + // reset attached object + job.setInstanceType(null); + job.setInstanceId(null); if (resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); - } + } - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while completing async job-" + jobId, e); - txt.rollback(); - } - } + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while completing async job-" + jobId, e); + txt.rollback(); + } + } - @Override @DB - public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject) { + @Override @DB + public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + + s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + ", result: " + resultObject); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job == null) { + } + + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job == null) { if(s_logger.isDebugEnabled()) { s_logger.debug("job-" + jobId + " no longer exists, we just log progress info here. progress status: " + processStatus); - } - - txt.rollback(); - return; - } - - job.setProcessStatus(processStatus); + } + + txt.rollback(); + return; + } + + job.setProcessStatus(processStatus); if(resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); - } - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while updating async job-" + jobId + " status: ", e); - txt.rollback(); - } - } + } + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while updating async job-" + jobId + " status: ", e); + txt.rollback(); + } + } - @Override @DB - public void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId) { + @Override @DB + public void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Update async-job attachment, job-" + jobId + ", instanceType: " + instanceType + + s_logger.debug("Update async-job attachment, job-" + jobId + ", instanceType: " + instanceType + ", instanceId: " + instanceId); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); + } + + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); - AsyncJobVO job = _jobDao.createForUpdate(); - //job.setInstanceType(instanceType); - job.setInstanceId(instanceId); - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); + AsyncJobVO job = _jobDao.createForUpdate(); + //job.setInstanceType(instanceType); + job.setInstanceId(instanceId); + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while updating async job-" + jobId + " attachment: ", e); - txt.rollback(); - } - } + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while updating async job-" + jobId + " attachment: ", e); + txt.rollback(); + } + } - @Override - public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId) { + @Override + public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId) { // This method is re-entrant. If an API developer wants to synchronized on an object, e.g. the router, // when executing business logic, they will call this method (actually a method in BaseAsyncCmd that calls this). // This method will get called every time their business logic executes. The first time it exectues for a job @@ -309,60 +309,60 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe return _jobDao.findById(cmd.getId()); } - @Override @DB - public AsyncJobResult queryAsyncJobResult(long jobId) { + @Override @DB + public AsyncJobResult queryAsyncJobResult(long jobId) { if(s_logger.isTraceEnabled()) { s_logger.trace("Query async-job status, job-" + jobId); - } - - Transaction txt = Transaction.currentTxn(); - AsyncJobResult jobResult = new AsyncJobResult(jobId); - - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job != null) { - jobResult.setCmdOriginator(job.getCmdOriginator()); - jobResult.setJobStatus(job.getStatus()); - jobResult.setProcessStatus(job.getProcessStatus()); - jobResult.setResult(job.getResult()); + } + + Transaction txt = Transaction.currentTxn(); + AsyncJobResult jobResult = new AsyncJobResult(jobId); + + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job != null) { + jobResult.setCmdOriginator(job.getCmdOriginator()); + jobResult.setJobStatus(job.getStatus()); + jobResult.setProcessStatus(job.getProcessStatus()); + jobResult.setResult(job.getResult()); jobResult.setResultCode(job.getResultCode()); - jobResult.setUuid(job.getUuid()); - - if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || - job.getStatus() == AsyncJobResult.STATUS_FAILED) { - + jobResult.setUuid(job.getUuid()); + + if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || + job.getStatus() == AsyncJobResult.STATUS_FAILED) { + if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " completed"); - } - } else { - job.setLastPolled(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - } - } else { + } + } else { + job.setLastPolled(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + } + } else { if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " does not exist, invalid job id?"); - } - - jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); - jobResult.setResult("job-" + jobId + " does not exist"); - } - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); - - jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); - jobResult.setResult("Exception: " + e.toString()); - txt.rollback(); - } - + } + + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); + jobResult.setResult("job-" + jobId + " does not exist"); + } + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); + + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); + jobResult.setResult("Exception: " + e.toString()); + txt.rollback(); + } + if(s_logger.isTraceEnabled()) { s_logger.trace("Job status: " + jobResult.toString()); - } - - return jobResult; + } + + return jobResult; } - + private void scheduleExecution(final AsyncJobVO job) { scheduleExecution(job, false); } @@ -500,7 +500,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } }; } - + private void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { AsyncJobVO job = _jobDao.findById(item.getContentId()); if (job != null) { @@ -530,61 +530,61 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } - @Override - public void releaseSyncSource(AsyncJobExecutor executor) { - if(executor.getSyncSource() != null) { + @Override + public void releaseSyncSource(AsyncJobExecutor executor) { + if(executor.getSyncSource() != null) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Release sync source for job-" + executor.getJob().getId() + " sync source: " - + executor.getSyncSource().getContentType() + "-" + s_logger.debug("Release sync source for job-" + executor.getJob().getId() + " sync source: " + + executor.getSyncSource().getContentType() + "-" + executor.getSyncSource().getContentId()); - } - - _queueMgr.purgeItem(executor.getSyncSource().getId()); - checkQueue(executor.getSyncSource().getQueueId()); - } - } - - private void checkQueue(long queueId) { - while(true) { - try { - SyncQueueItemVO item = _queueMgr.dequeueFromOne(queueId, getMsid()); - if(item != null) { + } + + _queueMgr.purgeItem(executor.getSyncSource().getId()); + checkQueue(executor.getSyncSource().getQueueId()); + } + } + + private void checkQueue(long queueId) { + while(true) { + try { + SyncQueueItemVO item = _queueMgr.dequeueFromOne(queueId, getMsid()); + if(item != null) { if(s_logger.isDebugEnabled()) { s_logger.debug("Executing sync queue item: " + item.toString()); - } - - executeQueueItem(item, false); - } else { - break; - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when kicking sync queue-" + queueId, e); - break; - } - } - } - - private Runnable getHeartbeatTask() { - return new Runnable() { + } + + executeQueueItem(item, false); + } else { + break; + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when kicking sync queue-" + queueId, e); + break; + } + } + } + + private Runnable getHeartbeatTask() { + return new Runnable() { @Override - public void run() { + public void run() { try { - List l = _queueMgr.dequeueFromAny(getMsid(), MAX_ONETIME_SCHEDULE_SIZE); - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item: l) { + List l = _queueMgr.dequeueFromAny(getMsid(), MAX_ONETIME_SCHEDULE_SIZE); + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item: l) { if(s_logger.isDebugEnabled()) { s_logger.debug("Execute sync-queue item: " + item.toString()); } executeQueueItem(item, false); - } - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when trying to execute queue item, ", e); + } + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when trying to execute queue item, ", e); } finally { StackMaid.current().exitCleanup(); - } - } - }; + } + } + }; } @DB @@ -643,14 +643,14 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } }; } - - private long getMsid() { + + private long getMsid() { if(_clusterMgr != null) { return _clusterMgr.getManagementNodeId(); - } - - return MacAddress.getMacAddress().toLong(); - } + } + + return MacAddress.getMacAddress().toLong(); + } private void cleanupPendingJobs(List l) { if(l != null && l.size() > 0) { @@ -670,13 +670,13 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe _queueMgr.purgeItem(item.getId()); } } - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; + } - ComponentLocator locator = ComponentLocator.getCurrentLocator(); + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); if (configDao == null) { @@ -694,25 +694,25 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe _accountDao = locator.getDao(AccountDao.class); if (_accountDao == null) { throw new ConfigurationException("Unable to get " + AccountDao.class.getName()); - } - _jobDao = locator.getDao(AsyncJobDao.class); - if (_jobDao == null) { - throw new ConfigurationException("Unable to get " - + AsyncJobDao.class.getName()); - } - - _context = locator.getManager(AsyncJobExecutorContext.class); - if (_context == null) { - throw new ConfigurationException("Unable to get " - + AsyncJobExecutorContext.class.getName()); - } - - _queueMgr = locator.getManager(SyncQueueManager.class); - if(_queueMgr == null) { - throw new ConfigurationException("Unable to get " - + SyncQueueManager.class.getName()); - } - + } + _jobDao = locator.getDao(AsyncJobDao.class); + if (_jobDao == null) { + throw new ConfigurationException("Unable to get " + + AsyncJobDao.class.getName()); + } + + _context = locator.getManager(AsyncJobExecutorContext.class); + if (_context == null) { + throw new ConfigurationException("Unable to get " + + AsyncJobExecutorContext.class.getName()); + } + + _queueMgr = locator.getManager(SyncQueueManager.class); + if(_queueMgr == null) { + throw new ConfigurationException("Unable to get " + + SyncQueueManager.class.getName()); + } + _clusterMgr = locator.getManager(ClusterManager.class); _accountMgr = locator.getManager(AccountManager.class); @@ -735,7 +735,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl"); } - return true; + return true; } @Override @@ -765,10 +765,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe @Override public void onManagementNodeIsolated() { } - - @Override + + @Override public boolean start() { - try { + try { List l = _queueMgr.getActiveQueueItems(getMsid(), false); cleanupPendingJobs(l); _queueMgr.resetQueueProcess(getMsid()); @@ -776,13 +776,13 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } catch(Throwable e) { s_logger.error("Unexpected exception " + e.getMessage(), e); } - - _heartbeatScheduler.scheduleAtFixedRate(getHeartbeatTask(), HEARTBEAT_INTERVAL, + + _heartbeatScheduler.scheduleAtFixedRate(getHeartbeatTask(), HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS); _heartbeatScheduler.scheduleAtFixedRate(getGCTask(), GC_INTERVAL, GC_INTERVAL, TimeUnit.MILLISECONDS); - - return true; + + return true; } private static ExceptionResponse getResetResultResponse(String errorMessage) { @@ -794,17 +794,17 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe private static String getSerializedErrorMessage(String errorMessage) { return ApiSerializerHelper.toSerializedStringOld(getResetResultResponse(errorMessage)); - } - - @Override - public boolean stop() { - _heartbeatScheduler.shutdown(); - _executor.shutdown(); - return true; - } - - @Override - public String getName() { - return _name; - } -} + } + + @Override + public boolean stop() { + _heartbeatScheduler.shutdown(); + _executor.shutdown(); + return true; + } + + @Override + public String getName() { + return _name; + } +} diff --git a/server/src/com/cloud/async/AsyncJobResult.java b/server/src/com/cloud/async/AsyncJobResult.java index 2a0e6d9313d..3019c338037 100644 --- a/server/src/com/cloud/async/AsyncJobResult.java +++ b/server/src/com/cloud/async/AsyncJobResult.java @@ -10,45 +10,45 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import com.cloud.api.ApiSerializerHelper; - -public class AsyncJobResult { - public static final int STATUS_IN_PROGRESS = 0; - public static final int STATUS_SUCCEEDED = 1; - public static final int STATUS_FAILED = 2; - - private String cmdOriginator; - private long jobId; - private int jobStatus; - private int processStatus; - private int resultCode; + +public class AsyncJobResult { + public static final int STATUS_IN_PROGRESS = 0; + public static final int STATUS_SUCCEEDED = 1; + public static final int STATUS_FAILED = 2; + + private String cmdOriginator; + private long jobId; + private int jobStatus; + private int processStatus; + private int resultCode; private String result; - private String uuid; - - public AsyncJobResult(long jobId) { - this.jobId = jobId; - jobStatus = STATUS_IN_PROGRESS; - processStatus = 0; - resultCode = 0; - result = ""; - } - - public String getCmdOriginator() { - return cmdOriginator; - } - - public void setCmdOriginator(String cmdOriginator) { - this.cmdOriginator = cmdOriginator; - } - - public long getJobId() { - return jobId; - } - - public void setJobId(long jobId) { - this.jobId = jobId; + private String uuid; + + public AsyncJobResult(long jobId) { + this.jobId = jobId; + jobStatus = STATUS_IN_PROGRESS; + processStatus = 0; + resultCode = 0; + result = ""; + } + + public String getCmdOriginator() { + return cmdOriginator; + } + + public void setCmdOriginator(String cmdOriginator) { + this.cmdOriginator = cmdOriginator; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; } public String getUuid() { @@ -57,57 +57,57 @@ public class AsyncJobResult { public void setUuid(String uuid) { this.uuid = uuid; - } - - public int getJobStatus() { - return jobStatus; - } - - public void setJobStatus(int jobStatus) { - this.jobStatus = jobStatus; - } - - public int getProcessStatus() { - return processStatus; - } - - public void setProcessStatus(int processStatus) { - this.processStatus = processStatus; - } - - public int getResultCode() { - return resultCode; - } - - public void setResultCode(int resultCode) { - this.resultCode = resultCode; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - - public Object getResultObject() { - return ApiSerializerHelper.fromSerializedString(result); - } - - public void setResultObject(Object result) { - this.result = ApiSerializerHelper.toSerializedStringOld(result); - } - + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + public int getProcessStatus() { + return processStatus; + } + + public void setProcessStatus(int processStatus) { + this.processStatus = processStatus; + } + + public int getResultCode() { + return resultCode; + } + + public void setResultCode(int resultCode) { + this.resultCode = resultCode; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public Object getResultObject() { + return ApiSerializerHelper.fromSerializedString(result); + } + + public void setResultObject(Object result) { + this.result = ApiSerializerHelper.toSerializedStringOld(result); + } + @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("AsyncJobResult {jobId:").append(getJobId()); - sb.append(", jobStatus: ").append(getJobStatus()); - sb.append(", processStatus: ").append(getProcessStatus()); - sb.append(", resultCode: ").append(getResultCode()); - sb.append(", result: ").append(result); - sb.append("}"); - return sb.toString(); - } -} + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("AsyncJobResult {jobId:").append(getJobId()); + sb.append(", jobStatus: ").append(getJobStatus()); + sb.append(", processStatus: ").append(getProcessStatus()); + sb.append(", resultCode: ").append(getResultCode()); + sb.append(", result: ").append(result); + sb.append("}"); + return sb.toString(); + } +} diff --git a/server/src/com/cloud/async/BaseAsyncJobExecutor.java b/server/src/com/cloud/async/BaseAsyncJobExecutor.java index 9bd9a34d256..577c1e16532 100644 --- a/server/src/com/cloud/async/BaseAsyncJobExecutor.java +++ b/server/src/com/cloud/async/BaseAsyncJobExecutor.java @@ -10,56 +10,56 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; +package com.cloud.async; - -public abstract class BaseAsyncJobExecutor implements AsyncJobExecutor { - private SyncQueueItemVO _syncSource; - private AsyncJobVO _job; - private boolean _fromPreviousSession; - private AsyncJobManager _asyncJobMgr; - - private static ThreadLocal s_currentExector = new ThreadLocal(); - - public AsyncJobManager getAsyncJobMgr() { - return _asyncJobMgr; - } - - public void setAsyncJobMgr(AsyncJobManager asyncMgr) { - _asyncJobMgr = asyncMgr; - } - - public SyncQueueItemVO getSyncSource() { - return _syncSource; - } - - public void setSyncSource(SyncQueueItemVO syncSource) { - _syncSource = syncSource; - } - - public AsyncJobVO getJob() { - return _job; - } - - public void setJob(AsyncJobVO job) { - _job = job; - } - - public void setFromPreviousSession(boolean value) { - _fromPreviousSession = value; - } - - public boolean isFromPreviousSession() { - return _fromPreviousSession; - } - - public abstract boolean execute(); - - public static AsyncJobExecutor getCurrentExecutor() { - return s_currentExector.get(); - } - - public static void setCurrentExecutor(AsyncJobExecutor currentExecutor) { - s_currentExector.set(currentExecutor); - } -} + +public abstract class BaseAsyncJobExecutor implements AsyncJobExecutor { + private SyncQueueItemVO _syncSource; + private AsyncJobVO _job; + private boolean _fromPreviousSession; + private AsyncJobManager _asyncJobMgr; + + private static ThreadLocal s_currentExector = new ThreadLocal(); + + public AsyncJobManager getAsyncJobMgr() { + return _asyncJobMgr; + } + + public void setAsyncJobMgr(AsyncJobManager asyncMgr) { + _asyncJobMgr = asyncMgr; + } + + public SyncQueueItemVO getSyncSource() { + return _syncSource; + } + + public void setSyncSource(SyncQueueItemVO syncSource) { + _syncSource = syncSource; + } + + public AsyncJobVO getJob() { + return _job; + } + + public void setJob(AsyncJobVO job) { + _job = job; + } + + public void setFromPreviousSession(boolean value) { + _fromPreviousSession = value; + } + + public boolean isFromPreviousSession() { + return _fromPreviousSession; + } + + public abstract boolean execute(); + + public static AsyncJobExecutor getCurrentExecutor() { + return s_currentExector.get(); + } + + public static void setCurrentExecutor(AsyncJobExecutor currentExecutor) { + s_currentExector.set(currentExecutor); + } +} diff --git a/server/src/com/cloud/async/SyncQueueManager.java b/server/src/com/cloud/async/SyncQueueManager.java index 7d40e8a6a71..94fc4638718 100644 --- a/server/src/com/cloud/async/SyncQueueManager.java +++ b/server/src/com/cloud/async/SyncQueueManager.java @@ -10,20 +10,20 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.List; import com.cloud.utils.component.Manager; - -public interface SyncQueueManager extends Manager { - public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId); - public SyncQueueItemVO dequeueFromOne(long queueId, Long msid); - public List dequeueFromAny(Long msid, int maxItems); - public void purgeItem(long queueItemId); + +public interface SyncQueueManager extends Manager { + public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId); + public SyncQueueItemVO dequeueFromOne(long queueId, Long msid); + public List dequeueFromAny(Long msid, int maxItems); + public void purgeItem(long queueItemId); public void returnItem(long queueItemId); - + public List getActiveQueueItems(Long msid, boolean exclusive); public List getBlockedQueueItems(long thresholdMs, boolean exclusive); public void resetQueueProcess(long msid); -} +} diff --git a/server/src/com/cloud/async/SyncQueueManagerImpl.java b/server/src/com/cloud/async/SyncQueueManagerImpl.java index 45c2d11ab61..9e04199dfea 100644 --- a/server/src/com/cloud/async/SyncQueueManagerImpl.java +++ b/server/src/com/cloud/async/SyncQueueManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -29,166 +29,166 @@ import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={SyncQueueManager.class}) -public class SyncQueueManagerImpl implements SyncQueueManager { - public static final Logger s_logger = Logger.getLogger(SyncQueueManagerImpl.class.getName()); - - private String _name; - - private SyncQueueDao _syncQueueDao; - private SyncQueueItemDao _syncQueueItemDao; - - @Override - @DB - public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId) { - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - - _syncQueueDao.ensureQueue(syncObjType, syncObjId); - SyncQueueVO queueVO = _syncQueueDao.find(syncObjType, syncObjId); - if(queueVO == null) - throw new CloudRuntimeException("Unable to queue item into DB, DB is full?"); - - - Date dt = DateUtil.currentGMTTime(); - SyncQueueItemVO item = new SyncQueueItemVO(); - item.setQueueId(queueVO.getId()); - item.setContentType(itemType); - item.setContentId(itemId); - item.setCreated(dt); - - _syncQueueItemDao.persist(item); - txn.commit(); - - return queueVO; - } catch(Exception e) { - s_logger.error("Unexpected exception: ", e); - txn.rollback(); - } - return null; - } - - @Override - @DB - public SyncQueueItemVO dequeueFromOne(long queueId, Long msid) { - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - - SyncQueueVO queueVO = _syncQueueDao.lockRow(queueId, true); - if(queueVO == null) { - s_logger.error("Sync queue(id: " + queueId + ") does not exist"); - txt.commit(); - return null; - } - - if(queueVO.getLastProcessTime() == null) { - SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId()); - if(itemVO != null) { - Long processNumber = queueVO.getLastProcessNumber(); - if(processNumber == null) - processNumber = new Long(1); - else - processNumber = processNumber + 1; - Date dt = DateUtil.currentGMTTime(); - queueVO.setLastProcessMsid(msid); - queueVO.setLastProcessNumber(processNumber); - queueVO.setLastProcessTime(dt); - queueVO.setLastUpdated(dt); - _syncQueueDao.update(queueVO.getId(), queueVO); - - itemVO.setLastProcessMsid(msid); - itemVO.setLastProcessNumber(processNumber); - _syncQueueItemDao.update(itemVO.getId(), itemVO); - - txt.commit(); - return itemVO; - } else { - if(s_logger.isDebugEnabled()) - s_logger.debug("Sync queue (" + queueId + ") is currently empty"); - } - } else { - if(s_logger.isDebugEnabled()) - s_logger.debug("There is a pending process in sync queue(id: " + queueId + ")"); - } - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception: ", e); - txt.rollback(); - } - - return null; - } - - @Override - @DB - public List dequeueFromAny(Long msid, int maxItems) { - - List resultList = new ArrayList(); - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - - List l = _syncQueueItemDao.getNextQueueItems(maxItems); - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item : l) { - SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true); - SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true); - if(queueVO.getLastProcessTime() == null && itemVO.getLastProcessNumber() == null) { - Long processNumber = queueVO.getLastProcessNumber(); - if(processNumber == null) - processNumber = new Long(1); - else - processNumber = processNumber + 1; - - Date dt = DateUtil.currentGMTTime(); - queueVO.setLastProcessMsid(msid); - queueVO.setLastProcessNumber(processNumber); - queueVO.setLastProcessTime(dt); - queueVO.setLastUpdated(dt); - _syncQueueDao.update(queueVO.getId(), queueVO); - - itemVO.setLastProcessMsid(msid); - itemVO.setLastProcessNumber(processNumber); - _syncQueueItemDao.update(item.getId(), itemVO); - - resultList.add(item); - } - } - } - txt.commit(); - return resultList; - } catch(Exception e) { - s_logger.error("Unexpected exception: ", e); - txt.rollback(); - } - return null; - } - - @Override - @DB - public void purgeItem(long queueItemId) { - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - - SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId); - if(itemVO != null) { - SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true); - - _syncQueueItemDao.expunge(itemVO.getId()); - - queueVO.setLastProcessTime(null); - queueVO.setLastUpdated(DateUtil.currentGMTTime()); - _syncQueueDao.update(queueVO.getId(), queueVO); - } - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception: ", e); - txt.rollback(); - } + +@Local(value={SyncQueueManager.class}) +public class SyncQueueManagerImpl implements SyncQueueManager { + public static final Logger s_logger = Logger.getLogger(SyncQueueManagerImpl.class.getName()); + + private String _name; + + private SyncQueueDao _syncQueueDao; + private SyncQueueItemDao _syncQueueItemDao; + + @Override + @DB + public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId) { + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + + _syncQueueDao.ensureQueue(syncObjType, syncObjId); + SyncQueueVO queueVO = _syncQueueDao.find(syncObjType, syncObjId); + if(queueVO == null) + throw new CloudRuntimeException("Unable to queue item into DB, DB is full?"); + + + Date dt = DateUtil.currentGMTTime(); + SyncQueueItemVO item = new SyncQueueItemVO(); + item.setQueueId(queueVO.getId()); + item.setContentType(itemType); + item.setContentId(itemId); + item.setCreated(dt); + + _syncQueueItemDao.persist(item); + txn.commit(); + + return queueVO; + } catch(Exception e) { + s_logger.error("Unexpected exception: ", e); + txn.rollback(); + } + return null; + } + + @Override + @DB + public SyncQueueItemVO dequeueFromOne(long queueId, Long msid) { + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + + SyncQueueVO queueVO = _syncQueueDao.lockRow(queueId, true); + if(queueVO == null) { + s_logger.error("Sync queue(id: " + queueId + ") does not exist"); + txt.commit(); + return null; + } + + if(queueVO.getLastProcessTime() == null) { + SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId()); + if(itemVO != null) { + Long processNumber = queueVO.getLastProcessNumber(); + if(processNumber == null) + processNumber = new Long(1); + else + processNumber = processNumber + 1; + Date dt = DateUtil.currentGMTTime(); + queueVO.setLastProcessMsid(msid); + queueVO.setLastProcessNumber(processNumber); + queueVO.setLastProcessTime(dt); + queueVO.setLastUpdated(dt); + _syncQueueDao.update(queueVO.getId(), queueVO); + + itemVO.setLastProcessMsid(msid); + itemVO.setLastProcessNumber(processNumber); + _syncQueueItemDao.update(itemVO.getId(), itemVO); + + txt.commit(); + return itemVO; + } else { + if(s_logger.isDebugEnabled()) + s_logger.debug("Sync queue (" + queueId + ") is currently empty"); + } + } else { + if(s_logger.isDebugEnabled()) + s_logger.debug("There is a pending process in sync queue(id: " + queueId + ")"); + } + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception: ", e); + txt.rollback(); + } + + return null; + } + + @Override + @DB + public List dequeueFromAny(Long msid, int maxItems) { + + List resultList = new ArrayList(); + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + + List l = _syncQueueItemDao.getNextQueueItems(maxItems); + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item : l) { + SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true); + SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true); + if(queueVO.getLastProcessTime() == null && itemVO.getLastProcessNumber() == null) { + Long processNumber = queueVO.getLastProcessNumber(); + if(processNumber == null) + processNumber = new Long(1); + else + processNumber = processNumber + 1; + + Date dt = DateUtil.currentGMTTime(); + queueVO.setLastProcessMsid(msid); + queueVO.setLastProcessNumber(processNumber); + queueVO.setLastProcessTime(dt); + queueVO.setLastUpdated(dt); + _syncQueueDao.update(queueVO.getId(), queueVO); + + itemVO.setLastProcessMsid(msid); + itemVO.setLastProcessNumber(processNumber); + _syncQueueItemDao.update(item.getId(), itemVO); + + resultList.add(item); + } + } + } + txt.commit(); + return resultList; + } catch(Exception e) { + s_logger.error("Unexpected exception: ", e); + txt.rollback(); + } + return null; + } + + @Override + @DB + public void purgeItem(long queueItemId) { + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + + SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId); + if(itemVO != null) { + SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true); + + _syncQueueItemDao.expunge(itemVO.getId()); + + queueVO.setLastProcessTime(null); + queueVO.setLastUpdated(DateUtil.currentGMTTime()); + _syncQueueDao.update(queueVO.getId(), queueVO); + } + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception: ", e); + txt.rollback(); + } } @Override @@ -215,11 +215,11 @@ public class SyncQueueManagerImpl implements SyncQueueManager { s_logger.error("Unexpected exception: ", e); txt.rollback(); } - } - - @Override - public List getActiveQueueItems(Long msid, boolean exclusive) { - return _syncQueueItemDao.getActiveQueueItems(msid, exclusive); + } + + @Override + public List getActiveQueueItems(Long msid, boolean exclusive) { + return _syncQueueItemDao.getActiveQueueItems(msid, exclusive); } @Override @@ -232,39 +232,39 @@ public class SyncQueueManagerImpl implements SyncQueueManager { _syncQueueDao.resetQueueProcessing(msid); } - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - - _syncQueueDao = locator.getDao(SyncQueueDao.class); - if (_syncQueueDao == null) { - throw new ConfigurationException("Unable to get " - + SyncQueueDao.class.getName()); - } - - _syncQueueItemDao = locator.getDao(SyncQueueItemDao.class); - if (_syncQueueItemDao == null) { - throw new ConfigurationException("Unable to get " - + SyncQueueDao.class.getName()); - } - - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } -} - + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + + _syncQueueDao = locator.getDao(SyncQueueDao.class); + if (_syncQueueDao == null) { + throw new ConfigurationException("Unable to get " + + SyncQueueDao.class.getName()); + } + + _syncQueueItemDao = locator.getDao(SyncQueueItemDao.class); + if (_syncQueueItemDao == null) { + throw new ConfigurationException("Unable to get " + + SyncQueueDao.class.getName()); + } + + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } +} + diff --git a/server/src/com/cloud/async/dao/AsyncJobDao.java b/server/src/com/cloud/async/dao/AsyncJobDao.java index 25a94d8abaf..f7c7c2fb04f 100644 --- a/server/src/com/cloud/async/dao/AsyncJobDao.java +++ b/server/src/com/cloud/async/dao/AsyncJobDao.java @@ -10,18 +10,18 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.dao; - +package com.cloud.async.dao; + import java.util.Date; import java.util.List; import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobVO; import com.cloud.utils.db.GenericDao; - -public interface AsyncJobDao extends GenericDao { + +public interface AsyncJobDao extends GenericDao { AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId); List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId); List getExpiredJobs(Date cutTime, int limit); void resetJobProcess(long msid, int jobResultCode, String jobResultMessage); -} +} diff --git a/server/src/com/cloud/async/dao/AsyncJobDaoImpl.java b/server/src/com/cloud/async/dao/AsyncJobDaoImpl.java index c63a7d06646..2b429666b8f 100644 --- a/server/src/com/cloud/async/dao/AsyncJobDaoImpl.java +++ b/server/src/com/cloud/async/dao/AsyncJobDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.dao; - +package com.cloud.async.dao; + import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; @@ -30,23 +30,23 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value = { AsyncJobDao.class }) -public class AsyncJobDaoImpl extends GenericDaoBase implements AsyncJobDao { - private static final Logger s_logger = Logger.getLogger(AsyncJobDaoImpl.class.getName()); - + +@Local(value = { AsyncJobDao.class }) +public class AsyncJobDaoImpl extends GenericDaoBase implements AsyncJobDao { + private static final Logger s_logger = Logger.getLogger(AsyncJobDaoImpl.class.getName()); + private final SearchBuilder pendingAsyncJobSearch; - private final SearchBuilder pendingAsyncJobsSearch; + private final SearchBuilder pendingAsyncJobsSearch; private final SearchBuilder expiringAsyncJobSearch; - - public AsyncJobDaoImpl() { - pendingAsyncJobSearch = createSearchBuilder(); - pendingAsyncJobSearch.and("instanceType", pendingAsyncJobSearch.entity().getInstanceType(), - SearchCriteria.Op.EQ); - pendingAsyncJobSearch.and("instanceId", pendingAsyncJobSearch.entity().getInstanceId(), - SearchCriteria.Op.EQ); - pendingAsyncJobSearch.and("status", pendingAsyncJobSearch.entity().getStatus(), - SearchCriteria.Op.EQ); + + public AsyncJobDaoImpl() { + pendingAsyncJobSearch = createSearchBuilder(); + pendingAsyncJobSearch.and("instanceType", pendingAsyncJobSearch.entity().getInstanceType(), + SearchCriteria.Op.EQ); + pendingAsyncJobSearch.and("instanceId", pendingAsyncJobSearch.entity().getInstanceId(), + SearchCriteria.Op.EQ); + pendingAsyncJobSearch.and("status", pendingAsyncJobSearch.entity().getStatus(), + SearchCriteria.Op.EQ); pendingAsyncJobSearch.done(); pendingAsyncJobsSearch = createSearchBuilder(); @@ -62,23 +62,23 @@ public class AsyncJobDaoImpl extends GenericDaoBase implements expiringAsyncJobSearch.and("created", expiringAsyncJobSearch.entity().getCreated(), SearchCriteria.Op.LTEQ); expiringAsyncJobSearch.done(); - } - - public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { - SearchCriteria sc = pendingAsyncJobSearch.create(); - sc.setParameters("instanceType", instanceType); - sc.setParameters("instanceId", instanceId); - sc.setParameters("status", AsyncJobResult.STATUS_IN_PROGRESS); - - List l = listIncludingRemovedBy(sc); - if(l != null && l.size() > 0) { - if(l.size() > 1) { - s_logger.warn("Instance " + instanceType + "-" + instanceId + " has multiple pending async-job"); - } - - return l.get(0); - } - return null; + } + + public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { + SearchCriteria sc = pendingAsyncJobSearch.create(); + sc.setParameters("instanceType", instanceType); + sc.setParameters("instanceId", instanceId); + sc.setParameters("status", AsyncJobResult.STATUS_IN_PROGRESS); + + List l = listIncludingRemovedBy(sc); + if(l != null && l.size() > 0) { + if(l.size() > 1) { + s_logger.warn("Instance " + instanceType + "-" + instanceId + " has multiple pending async-job"); + } + + return l.get(0); + } + return null; } public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId) { @@ -118,4 +118,4 @@ public class AsyncJobDaoImpl extends GenericDaoBase implements s_logger.warn("Unable to reset job status for management server " + msid, e); } } -} +} diff --git a/server/src/com/cloud/async/dao/SyncQueueDao.java b/server/src/com/cloud/async/dao/SyncQueueDao.java index fe21cbc9703..df18bcabde8 100644 --- a/server/src/com/cloud/async/dao/SyncQueueDao.java +++ b/server/src/com/cloud/async/dao/SyncQueueDao.java @@ -10,13 +10,13 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.dao; - +package com.cloud.async.dao; + import com.cloud.async.SyncQueueVO; import com.cloud.utils.db.GenericDao; - -public interface SyncQueueDao extends GenericDao{ - public void ensureQueue(String syncObjType, long syncObjId); + +public interface SyncQueueDao extends GenericDao{ + public void ensureQueue(String syncObjType, long syncObjId); public SyncQueueVO find(String syncObjType, long syncObjId); public void resetQueueProcessing(long msid); -} +} diff --git a/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java b/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java index c358704ffde..ddc94ea1603 100644 --- a/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java +++ b/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.dao; - +package com.cloud.async.dao; + import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; @@ -28,40 +28,40 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value = { SyncQueueDao.class }) -public class SyncQueueDaoImpl extends GenericDaoBase implements SyncQueueDao { + +@Local(value = { SyncQueueDao.class }) +public class SyncQueueDaoImpl extends GenericDaoBase implements SyncQueueDao { private static final Logger s_logger = Logger.getLogger(SyncQueueDaoImpl.class.getName()); - + SearchBuilder TypeIdSearch = createSearchBuilder(); - - @Override - public void ensureQueue(String syncObjType, long syncObjId) { - Date dt = DateUtil.currentGMTTime(); - String sql = "INSERT IGNORE INTO sync_queue(sync_objtype, sync_objid, created, last_updated) values(?, ?, ?, ?)"; - - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setString(1, syncObjType); - pstmt.setLong(2, syncObjId); - pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), dt)); - pstmt.setString(4, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), dt)); - pstmt.execute(); - } catch (SQLException e) { - s_logger.warn("Unable to create sync queue " + syncObjType + "-" + syncObjId + ":" + e.getMessage(), e); - } catch (Throwable e) { - s_logger.warn("Unable to create sync queue " + syncObjType + "-" + syncObjId + ":" + e.getMessage(), e); - } - } - - @Override - public SyncQueueVO find(String syncObjType, long syncObjId) { - SearchCriteria sc = TypeIdSearch.create(); - sc.setParameters("syncObjType", syncObjType); - sc.setParameters("syncObjId", syncObjId); - return findOneBy(sc); + + @Override + public void ensureQueue(String syncObjType, long syncObjId) { + Date dt = DateUtil.currentGMTTime(); + String sql = "INSERT IGNORE INTO sync_queue(sync_objtype, sync_objid, created, last_updated) values(?, ?, ?, ?)"; + + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setString(1, syncObjType); + pstmt.setLong(2, syncObjId); + pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), dt)); + pstmt.setString(4, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), dt)); + pstmt.execute(); + } catch (SQLException e) { + s_logger.warn("Unable to create sync queue " + syncObjType + "-" + syncObjId + ":" + e.getMessage(), e); + } catch (Throwable e) { + s_logger.warn("Unable to create sync queue " + syncObjType + "-" + syncObjId + ":" + e.getMessage(), e); + } + } + + @Override + public SyncQueueVO find(String syncObjType, long syncObjId) { + SearchCriteria sc = TypeIdSearch.create(); + sc.setParameters("syncObjType", syncObjType); + sc.setParameters("syncObjId", syncObjId); + return findOneBy(sc); } @Override @DB @@ -87,5 +87,5 @@ public class SyncQueueDaoImpl extends GenericDaoBase implemen TypeIdSearch.and("syncObjType", TypeIdSearch.entity().getSyncObjType(), SearchCriteria.Op.EQ); TypeIdSearch.and("syncObjId", TypeIdSearch.entity().getSyncObjId(), SearchCriteria.Op.EQ); TypeIdSearch.done(); - } -} + } +} diff --git a/server/src/com/cloud/async/dao/SyncQueueItemDao.java b/server/src/com/cloud/async/dao/SyncQueueItemDao.java index 61d0733b334..4058d42680b 100644 --- a/server/src/com/cloud/async/dao/SyncQueueItemDao.java +++ b/server/src/com/cloud/async/dao/SyncQueueItemDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.dao; - +package com.cloud.async.dao; + import java.util.List; import com.cloud.async.SyncQueueItemVO; import com.cloud.utils.db.GenericDao; - -public interface SyncQueueItemDao extends GenericDao { - public SyncQueueItemVO getNextQueueItem(long queueId); - public List getNextQueueItems(int maxItems); + +public interface SyncQueueItemDao extends GenericDao { + public SyncQueueItemVO getNextQueueItem(long queueId); + public List getNextQueueItems(int maxItems); public List getActiveQueueItems(Long msid, boolean exclusive); - public List getBlockedQueueItems(long thresholdMs, boolean exclusive); -} + public List getBlockedQueueItems(long thresholdMs, boolean exclusive); +} diff --git a/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java b/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java index d1534da00d6..7972ffcf362 100644 --- a/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java +++ b/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.dao; - +package com.cloud.async.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -33,81 +33,81 @@ import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value = { SyncQueueItemDao.class }) + +@Local(value = { SyncQueueItemDao.class }) public class SyncQueueItemDaoImpl extends GenericDaoBase implements SyncQueueItemDao { private static final Logger s_logger = Logger.getLogger(SyncQueueItemDaoImpl.class); - private final SyncQueueDao _syncQueueDao = new SyncQueueDaoImpl(); - - @Override - public SyncQueueItemVO getNextQueueItem(long queueId) { - - SearchBuilder sb = createSearchBuilder(); - sb.and("queueId", sb.entity().getQueueId(), SearchCriteria.Op.EQ); - sb.and("lastProcessNumber", sb.entity().getLastProcessNumber(), SearchCriteria.Op.NULL); - sb.done(); - - SearchCriteria sc = sb.create(); - sc.setParameters("queueId", queueId); - - Filter filter = new Filter(SyncQueueItemVO.class, "created", true, 0L, 1L); - List l = listBy(sc, filter); - if(l != null && l.size() > 0) - return l.get(0); - - return null; - } - - @Override - public List getNextQueueItems(int maxItems) { - List l = new ArrayList(); - - String sql = "SELECT i.id, i.queue_id, i.content_type, i.content_id, i.created " + - " FROM sync_queue AS q JOIN sync_queue_item AS i ON q.id = i.queue_id " + - " WHERE q.queue_proc_time IS NULL AND i.queue_proc_number IS NULL " + - " GROUP BY q.id " + - " ORDER BY i.id " + - " LIMIT 0, ?"; - - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setInt(1, maxItems); - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - SyncQueueItemVO item = new SyncQueueItemVO(); - item.setId(rs.getLong(1)); - item.setQueueId(rs.getLong(2)); - item.setContentType(rs.getString(3)); - item.setContentId(rs.getLong(4)); - item.setCreated(DateUtil.parseDateString(TimeZone.getTimeZone("GMT"), rs.getString(5))); - l.add(item); - } - } catch (SQLException e) { - s_logger.error("Unexpected sql excetpion, ", e); - } catch (Throwable e) { - s_logger.error("Unexpected excetpion, ", e); - } - return l; - } - - @Override - public List getActiveQueueItems(Long msid, boolean exclusive) { - SearchBuilder sb = createSearchBuilder(); - sb.and("lastProcessMsid", sb.entity().getLastProcessMsid(), - SearchCriteria.Op.EQ); - sb.done(); - - SearchCriteria sc = sb.create(); - sc.setParameters("lastProcessMsid", msid); - + private final SyncQueueDao _syncQueueDao = new SyncQueueDaoImpl(); + + @Override + public SyncQueueItemVO getNextQueueItem(long queueId) { + + SearchBuilder sb = createSearchBuilder(); + sb.and("queueId", sb.entity().getQueueId(), SearchCriteria.Op.EQ); + sb.and("lastProcessNumber", sb.entity().getLastProcessNumber(), SearchCriteria.Op.NULL); + sb.done(); + + SearchCriteria sc = sb.create(); + sc.setParameters("queueId", queueId); + + Filter filter = new Filter(SyncQueueItemVO.class, "created", true, 0L, 1L); + List l = listBy(sc, filter); + if(l != null && l.size() > 0) + return l.get(0); + + return null; + } + + @Override + public List getNextQueueItems(int maxItems) { + List l = new ArrayList(); + + String sql = "SELECT i.id, i.queue_id, i.content_type, i.content_id, i.created " + + " FROM sync_queue AS q JOIN sync_queue_item AS i ON q.id = i.queue_id " + + " WHERE q.queue_proc_time IS NULL AND i.queue_proc_number IS NULL " + + " GROUP BY q.id " + + " ORDER BY i.id " + + " LIMIT 0, ?"; + + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setInt(1, maxItems); + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + SyncQueueItemVO item = new SyncQueueItemVO(); + item.setId(rs.getLong(1)); + item.setQueueId(rs.getLong(2)); + item.setContentType(rs.getString(3)); + item.setContentId(rs.getLong(4)); + item.setCreated(DateUtil.parseDateString(TimeZone.getTimeZone("GMT"), rs.getString(5))); + l.add(item); + } + } catch (SQLException e) { + s_logger.error("Unexpected sql excetpion, ", e); + } catch (Throwable e) { + s_logger.error("Unexpected excetpion, ", e); + } + return l; + } + + @Override + public List getActiveQueueItems(Long msid, boolean exclusive) { + SearchBuilder sb = createSearchBuilder(); + sb.and("lastProcessMsid", sb.entity().getLastProcessMsid(), + SearchCriteria.Op.EQ); + sb.done(); + + SearchCriteria sc = sb.create(); + sc.setParameters("lastProcessMsid", msid); + Filter filter = new Filter(SyncQueueItemVO.class, "created", true, null, null); if(exclusive) - return lockRows(sc, filter, true); - return listBy(sc, filter); + return lockRows(sc, filter, true); + return listBy(sc, filter); } @Override @@ -134,4 +134,4 @@ public class SyncQueueItemDaoImpl extends GenericDaoBase return lockRows(sc, null, true); return listBy(sc, null); } -} +} diff --git a/server/src/com/cloud/async/executor/ExtractJobResultObject.java b/server/src/com/cloud/async/executor/ExtractJobResultObject.java index c9829fe1b85..1e47eb079ab 100644 --- a/server/src/com/cloud/async/executor/ExtractJobResultObject.java +++ b/server/src/com/cloud/async/executor/ExtractJobResultObject.java @@ -10,170 +10,170 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async.executor; - -import java.util.Date; - -import com.cloud.async.AsyncInstanceCreateStatus; -import com.cloud.serializer.Param; -import com.cloud.storage.Volume.Type; -import com.cloud.storage.upload.UploadState; - -public class ExtractJobResultObject { - - public ExtractJobResultObject(Long accountId, String typeName, String currState, int uploadPercent, Long uploadId){ - this.accountId = accountId; - this.name = typeName; - this.state = currState; - this.id = uploadId; - this.uploadPercent = uploadPercent; - } - - public ExtractJobResultObject(Long accountId, String typeName, String currState, Long uploadId, String url){ - this.accountId = accountId; - this.name = typeName; - this.state = currState; - this.id = uploadId; - this.url = url; - } - - public ExtractJobResultObject(){ - } - - @Param(name="id") - private long id; - - @Param(name="name") - private String name; - - @Param(name="uploadPercentage") - private int uploadPercent; - - @Param(name="uploadStatus") - private String uploadStatus; - - @Param(name="accountid") - long accountId; - - @Param(name="result_string") - String result_string; - - @Param(name="created") - private Date createdDate; - - @Param(name="state") - private String state; - - @Param(name="storagetype") - String storageType; - - @Param(name="storage") - private String storage; - - @Param(name="zoneid") - private Long zoneId; - - @Param(name="zonename") - private String zoneName; - - @Param(name="url") - private String url; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public int getUploadPercent() { - return uploadPercent; - } - - public void setUploadPercent(int i) { - this.uploadPercent = i; - } - - public String getUploadStatus() { - return uploadStatus; - } - - public void setUploadStatus(String uploadStatus) { - this.uploadStatus = uploadStatus; - } - - public String getResult_string() { - return result_string; - } - - public void setResult_string(String resultString) { - result_string = resultString; - } - - - public Long getZoneId() { - return zoneId; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - public String getZoneName() { - return zoneName; - } - - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - } - - public String getStorage() { - return storage; - } - - public void setStorage(String storage) { - this.storage = storage; - } - - public void setId(long id) { - this.id = id; - } - - public long getId() { - return id; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setState(String status) { - this.state = status; - } - - public String getState() { - return state; - } - - public void setStorageType (String storageType) { - this.storageType = storageType; - } - - public String getStorageType() { - return storageType; - } - -} +package com.cloud.async.executor; + +import java.util.Date; + +import com.cloud.async.AsyncInstanceCreateStatus; +import com.cloud.serializer.Param; +import com.cloud.storage.Volume.Type; +import com.cloud.storage.upload.UploadState; + +public class ExtractJobResultObject { + + public ExtractJobResultObject(Long accountId, String typeName, String currState, int uploadPercent, Long uploadId){ + this.accountId = accountId; + this.name = typeName; + this.state = currState; + this.id = uploadId; + this.uploadPercent = uploadPercent; + } + + public ExtractJobResultObject(Long accountId, String typeName, String currState, Long uploadId, String url){ + this.accountId = accountId; + this.name = typeName; + this.state = currState; + this.id = uploadId; + this.url = url; + } + + public ExtractJobResultObject(){ + } + + @Param(name="id") + private long id; + + @Param(name="name") + private String name; + + @Param(name="uploadPercentage") + private int uploadPercent; + + @Param(name="uploadStatus") + private String uploadStatus; + + @Param(name="accountid") + long accountId; + + @Param(name="result_string") + String result_string; + + @Param(name="created") + private Date createdDate; + + @Param(name="state") + private String state; + + @Param(name="storagetype") + String storageType; + + @Param(name="storage") + private String storage; + + @Param(name="zoneid") + private Long zoneId; + + @Param(name="zonename") + private String zoneName; + + @Param(name="url") + private String url; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public int getUploadPercent() { + return uploadPercent; + } + + public void setUploadPercent(int i) { + this.uploadPercent = i; + } + + public String getUploadStatus() { + return uploadStatus; + } + + public void setUploadStatus(String uploadStatus) { + this.uploadStatus = uploadStatus; + } + + public String getResult_string() { + return result_string; + } + + public void setResult_string(String resultString) { + result_string = resultString; + } + + + public Long getZoneId() { + return zoneId; + } + + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public String getStorage() { + return storage; + } + + public void setStorage(String storage) { + this.storage = storage; + } + + public void setId(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setState(String status) { + this.state = status; + } + + public String getState() { + return state; + } + + public void setStorageType (String storageType) { + this.storageType = storageType; + } + + public String getStorageType() { + return storageType; + } + +} diff --git a/server/src/com/cloud/capacity/dao/CapacityDao.java b/server/src/com/cloud/capacity/dao/CapacityDao.java index 0906952b8e0..268ff2e9804 100755 --- a/server/src/com/cloud/capacity/dao/CapacityDao.java +++ b/server/src/com/cloud/capacity/dao/CapacityDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.capacity.dao; - +package com.cloud.capacity.dao; + import java.util.List; import java.util.Map; @@ -19,7 +19,7 @@ import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; - + public interface CapacityDao extends GenericDao { CapacityVO findByHostIdType(Long hostId, short capacityType); List listClustersInZoneOrPodByHostCapacities(long id, int requiredCpu, long requiredRam, short capacityTypeForOrdering, boolean isZone, float cpuOverprovisioningFactor); @@ -36,5 +36,5 @@ public interface CapacityDao extends GenericDao { Long podId, Long clusterId, String resourceState); List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit); void updateCapacityState(Long dcId, Long podId, Long clusterId, - Long hostId, String capacityState); -} + Long hostId, String capacityState); +} diff --git a/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java b/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java index b3e73c89bc0..f5760c8d4cd 100755 --- a/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java +++ b/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.capacity.dao; - +package com.cloud.capacity.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -47,12 +47,12 @@ import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value = { CapacityDao.class }) + +@Local(value = { CapacityDao.class }) public class CapacityDaoImpl extends GenericDaoBase implements CapacityDao { - private static final Logger s_logger = Logger.getLogger(CapacityDaoImpl.class); - - private static final String ADD_ALLOCATED_SQL = "UPDATE `cloud`.`op_host_capacity` SET used_capacity = used_capacity + ? WHERE host_id = ? AND capacity_type = ?"; + private static final Logger s_logger = Logger.getLogger(CapacityDaoImpl.class); + + private static final String ADD_ALLOCATED_SQL = "UPDATE `cloud`.`op_host_capacity` SET used_capacity = used_capacity + ? WHERE host_id = ? AND capacity_type = ?"; private static final String SUBTRACT_ALLOCATED_SQL = "UPDATE `cloud`.`op_host_capacity` SET used_capacity = used_capacity - ? WHERE host_id = ? AND capacity_type = ?"; private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART1 = "SELECT DISTINCT capacity.cluster_id FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster` cluster on (cluster.id = capacity.cluster_id AND cluster.removed is NULL) WHERE "; @@ -306,29 +306,29 @@ public class CapacityDaoImpl extends GenericDaoBase implements return results; } - - public void updateAllocated(Long hostId, long allocatedAmount, short capacityType, boolean add) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = null; - if (add) { - sql = ADD_ALLOCATED_SQL; - } else { - sql = SUBTRACT_ALLOCATED_SQL; - } - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, allocatedAmount); - pstmt.setLong(2, hostId); - pstmt.setShort(3, capacityType); - pstmt.executeUpdate(); // TODO: Make sure exactly 1 row was updated? - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Exception updating capacity for host: " + hostId, e); - } - } + + public void updateAllocated(Long hostId, long allocatedAmount, short capacityType, boolean add) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = null; + if (add) { + sql = ADD_ALLOCATED_SQL; + } else { + sql = SUBTRACT_ALLOCATED_SQL; + } + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, allocatedAmount); + pstmt.setLong(2, hostId); + pstmt.setShort(3, capacityType); + pstmt.executeUpdate(); // TODO: Make sure exactly 1 row was updated? + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Exception updating capacity for host: " + hostId, e); + } + } @Override @@ -717,5 +717,5 @@ public class CapacityDaoImpl extends GenericDaoBase implements } catch (Exception e) { s_logger.warn("Error updating CapacityVO", e); } - } -} + } +} diff --git a/server/src/com/cloud/cluster/CheckPointManager.java b/server/src/com/cloud/cluster/CheckPointManager.java index b55cf058bd9..58056229d60 100644 --- a/server/src/com/cloud/cluster/CheckPointManager.java +++ b/server/src/com/cloud/cluster/CheckPointManager.java @@ -10,39 +10,39 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - - -/** - * TaskManager helps business logic deal with clustering failover. - * Say you're writing code that introduces an inconsistent state over - * of your operation? Who will come back to cleanup this state? TaskManager - * with different content during your process. If the server dies, TaskManager - * running elsewhere. If there are no clustered servers, then TaskManager will - * cleanup when the dead server resumes. - * - */ -public interface CheckPointManager { - /** - * responsible for cleaning up. - * - * @param context context information to be stored. - * @return Check point id. - */ - long pushCheckPoint(CleanupMaid context); - - /** - * update the task with new context - * @param taskId - * @param updatedContext new updated context. - */ - void updateCheckPointState(long taskId, CleanupMaid updatedContext); - - - /** - * removes the task as it is completed. - * - * @param taskId - */ - void popCheckPoint(long taskId); -} +package com.cloud.cluster; + + +/** + * TaskManager helps business logic deal with clustering failover. + * Say you're writing code that introduces an inconsistent state over + * of your operation? Who will come back to cleanup this state? TaskManager + * with different content during your process. If the server dies, TaskManager + * running elsewhere. If there are no clustered servers, then TaskManager will + * cleanup when the dead server resumes. + * + */ +public interface CheckPointManager { + /** + * responsible for cleaning up. + * + * @param context context information to be stored. + * @return Check point id. + */ + long pushCheckPoint(CleanupMaid context); + + /** + * update the task with new context + * @param taskId + * @param updatedContext new updated context. + */ + void updateCheckPointState(long taskId, CleanupMaid updatedContext); + + + /** + * removes the task as it is completed. + * + * @param taskId + */ + void popCheckPoint(long taskId); +} diff --git a/server/src/com/cloud/cluster/CheckPointManagerImpl.java b/server/src/com/cloud/cluster/CheckPointManagerImpl.java index ebbb67e6296..7cbca31164c 100644 --- a/server/src/com/cloud/cluster/CheckPointManagerImpl.java +++ b/server/src/com/cloud/cluster/CheckPointManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -37,206 +37,206 @@ import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; - -@Local(value=CheckPointManager.class) -public class CheckPointManagerImpl implements CheckPointManager, Manager, ClusterManagerListener { - private static final Logger s_logger = Logger.getLogger(CheckPointManagerImpl.class); - - private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds - private int _cleanupRetryInterval; - - private String _name; - - @Inject - private StackMaidDao _maidDao; - - @Inject - private ClusterManager _clusterMgr; - - long _msId; - - private final ScheduledExecutorService _cleanupScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Task-Cleanup")); - - protected CheckPointManagerImpl() { - } - - @Override - public boolean configure(String name, Map xmlParams) throws ConfigurationException { - _name = name; - - if (s_logger.isInfoEnabled()) { - s_logger.info("Start configuring StackMaidManager : " + name); - } - - StackMaid.init(ManagementServerNode.getManagementServerId()); - _msId = ManagementServerNode.getManagementServerId(); - - _clusterMgr.registerListener(this); - - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - - Map params = configDao.getConfiguration(xmlParams); - - _cleanupRetryInterval = NumbersUtil.parseInt(params.get(Config.TaskCleanupRetryInterval.key()), 600); - _maidDao.takeover(_msId, _msId); - return true; - } - - private void cleanupLeftovers(List l) { - for (CheckPointVO maid : l) { - if (StackMaid.doCleanup(maid)) { - _maidDao.expunge(maid.getId()); - } - } - } - - @Override - public void onManagementNodeIsolated() { - } - - @DB - private Runnable getGCTask() { - return new Runnable() { - @Override - public void run() { - GlobalLock scanLock = GlobalLock.getInternLock("StackMaidManagerGC"); - try { - if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { - try { - reallyRun(); - } finally { - scanLock.unlock(); - } - } - } finally { - scanLock.releaseRef(); - } - } - - public void reallyRun() { - try { - Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - 7200000); - List l = _maidDao.listLeftoversByCutTime(cutTime); - cleanupLeftovers(l); - } catch (Throwable e) { - s_logger.error("Unexpected exception when trying to execute queue item, ", e); - } - } - }; - } - - @Override - public boolean start() { - _cleanupScheduler.schedule(new CleanupTask(), _cleanupRetryInterval > 0 ? _cleanupRetryInterval : 600, TimeUnit.SECONDS); - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public void onManagementNodeJoined(List nodeList, long selfNodeId) { - // Nothing to do - } - - @Override - public void onManagementNodeLeft(List nodeList, long selfNodeId) { - for (ManagementServerHostVO node : nodeList) { - if (_maidDao.takeover(node.getMsid(), selfNodeId)) { - s_logger.info("Taking over from " + node.getMsid()); - _cleanupScheduler.execute(new CleanupTask()); - } - } - } - + +@Local(value=CheckPointManager.class) +public class CheckPointManagerImpl implements CheckPointManager, Manager, ClusterManagerListener { + private static final Logger s_logger = Logger.getLogger(CheckPointManagerImpl.class); + + private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds + private int _cleanupRetryInterval; + + private String _name; + + @Inject + private StackMaidDao _maidDao; + + @Inject + private ClusterManager _clusterMgr; + + long _msId; + + private final ScheduledExecutorService _cleanupScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Task-Cleanup")); + + protected CheckPointManagerImpl() { + } + @Override - @DB - public long pushCheckPoint(CleanupMaid context) { - long seq = _maidDao.pushCleanupDelegate(_msId, 0, context.getClass().getName(), context); - return seq; - } - - @Override + public boolean configure(String name, Map xmlParams) throws ConfigurationException { + _name = name; + + if (s_logger.isInfoEnabled()) { + s_logger.info("Start configuring StackMaidManager : " + name); + } + + StackMaid.init(ManagementServerNode.getManagementServerId()); + _msId = ManagementServerNode.getManagementServerId(); + + _clusterMgr.registerListener(this); + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + + Map params = configDao.getConfiguration(xmlParams); + + _cleanupRetryInterval = NumbersUtil.parseInt(params.get(Config.TaskCleanupRetryInterval.key()), 600); + _maidDao.takeover(_msId, _msId); + return true; + } + + private void cleanupLeftovers(List l) { + for (CheckPointVO maid : l) { + if (StackMaid.doCleanup(maid)) { + _maidDao.expunge(maid.getId()); + } + } + } + + @Override + public void onManagementNodeIsolated() { + } + @DB - public void updateCheckPointState(long taskId, CleanupMaid updatedContext) { - CheckPointVO task = _maidDao.createForUpdate(); - task.setDelegate(updatedContext.getClass().getName()); - task.setContext(SerializerHelper.toSerializedStringOld(updatedContext)); - _maidDao.update(taskId, task); - } - - @Override + private Runnable getGCTask() { + return new Runnable() { + @Override + public void run() { + GlobalLock scanLock = GlobalLock.getInternLock("StackMaidManagerGC"); + try { + if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { + try { + reallyRun(); + } finally { + scanLock.unlock(); + } + } + } finally { + scanLock.releaseRef(); + } + } + + public void reallyRun() { + try { + Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - 7200000); + List l = _maidDao.listLeftoversByCutTime(cutTime); + cleanupLeftovers(l); + } catch (Throwable e) { + s_logger.error("Unexpected exception when trying to execute queue item, ", e); + } + } + }; + } + + @Override + public boolean start() { + _cleanupScheduler.schedule(new CleanupTask(), _cleanupRetryInterval > 0 ? _cleanupRetryInterval : 600, TimeUnit.SECONDS); + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public void onManagementNodeJoined(List nodeList, long selfNodeId) { + // Nothing to do + } + + @Override + public void onManagementNodeLeft(List nodeList, long selfNodeId) { + for (ManagementServerHostVO node : nodeList) { + if (_maidDao.takeover(node.getMsid(), selfNodeId)) { + s_logger.info("Taking over from " + node.getMsid()); + _cleanupScheduler.execute(new CleanupTask()); + } + } + } + + @Override @DB - public void popCheckPoint(long taskId) { - _maidDao.remove(taskId); - } - - protected boolean cleanup(CheckPointVO task) { - s_logger.info("Cleaning up " + task); - CleanupMaid delegate = (CleanupMaid)SerializerHelper.fromSerializedString(task.getContext()); - assert delegate.getClass().getName().equals(task.getDelegate()) : "Deserializer says " + delegate.getClass().getName() + " but it's suppose to be " + task.getDelegate(); - - int result = delegate.cleanup(this); - if (result <= 0) { - if (result == 0) { - s_logger.info("Successfully cleaned up " + task.getId()); - } else { - s_logger.warn("Unsuccessful in cleaning up " + task + ". Procedure to cleanup manaully: " + delegate.getCleanupProcedure()); - } - popCheckPoint(task.getId()); - return true; - } else { - s_logger.error("Unable to cleanup " + task.getId()); - return false; - } - } - - class CleanupTask implements Runnable { - private Date _curDate; + public long pushCheckPoint(CleanupMaid context) { + long seq = _maidDao.pushCleanupDelegate(_msId, 0, context.getClass().getName(), context); + return seq; + } + + @Override + @DB + public void updateCheckPointState(long taskId, CleanupMaid updatedContext) { + CheckPointVO task = _maidDao.createForUpdate(); + task.setDelegate(updatedContext.getClass().getName()); + task.setContext(SerializerHelper.toSerializedStringOld(updatedContext)); + _maidDao.update(taskId, task); + } + + @Override + @DB + public void popCheckPoint(long taskId) { + _maidDao.remove(taskId); + } + + protected boolean cleanup(CheckPointVO task) { + s_logger.info("Cleaning up " + task); + CleanupMaid delegate = (CleanupMaid)SerializerHelper.fromSerializedString(task.getContext()); + assert delegate.getClass().getName().equals(task.getDelegate()) : "Deserializer says " + delegate.getClass().getName() + " but it's suppose to be " + task.getDelegate(); + + int result = delegate.cleanup(this); + if (result <= 0) { + if (result == 0) { + s_logger.info("Successfully cleaned up " + task.getId()); + } else { + s_logger.warn("Unsuccessful in cleaning up " + task + ". Procedure to cleanup manaully: " + delegate.getCleanupProcedure()); + } + popCheckPoint(task.getId()); + return true; + } else { + s_logger.error("Unable to cleanup " + task.getId()); + return false; + } + } + + class CleanupTask implements Runnable { + private Date _curDate; public CleanupTask() { - _curDate = new Date(); - } - - @Override - public void run() { + _curDate = new Date(); + } + + @Override + public void run() { try { - List tasks = _maidDao.listLeftoversByCutTime(_curDate, _msId); - tasks.addAll(_maidDao.listCleanupTasks(_msId)); - - List retries = new ArrayList(); - - for (CheckPointVO task : tasks) { - try { - if (!cleanup(task)) { - retries.add(task); - } - } catch (Exception e) { - s_logger.warn("Unable to clean up " + task, e); - - } - } - - if (retries.size() > 0) { - if (_cleanupRetryInterval > 0) { - _cleanupScheduler.schedule(this, _cleanupRetryInterval, TimeUnit.SECONDS); - } else { - for (CheckPointVO task : retries) { - s_logger.warn("Cleanup procedure for " + task + ": " + ((CleanupMaid)SerializerHelper.fromSerializedString(task.getContext())).getCleanupProcedure()); - } - } - } - - } catch (Exception e) { - s_logger.error("Unable to cleanup all of the tasks for " + _msId, e); - } - } - } -} + List tasks = _maidDao.listLeftoversByCutTime(_curDate, _msId); + tasks.addAll(_maidDao.listCleanupTasks(_msId)); + + List retries = new ArrayList(); + + for (CheckPointVO task : tasks) { + try { + if (!cleanup(task)) { + retries.add(task); + } + } catch (Exception e) { + s_logger.warn("Unable to clean up " + task, e); + + } + } + + if (retries.size() > 0) { + if (_cleanupRetryInterval > 0) { + _cleanupScheduler.schedule(this, _cleanupRetryInterval, TimeUnit.SECONDS); + } else { + for (CheckPointVO task : retries) { + s_logger.warn("Cleanup procedure for " + task + ": " + ((CleanupMaid)SerializerHelper.fromSerializedString(task.getContext())).getCleanupProcedure()); + } + } + } + + } catch (Exception e) { + s_logger.error("Unable to cleanup all of the tasks for " + _msId, e); + } + } + } +} diff --git a/server/src/com/cloud/cluster/CheckPointVO.java b/server/src/com/cloud/cluster/CheckPointVO.java index ca618bca9f5..85e2b60c037 100644 --- a/server/src/com/cloud/cluster/CheckPointVO.java +++ b/server/src/com/cloud/cluster/CheckPointVO.java @@ -10,107 +10,107 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="stack_maid") -public class CheckPointVO { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="msid") - private long msid; - - @Column(name="thread_id") - private long threadId; - - @Column(name="seq") - private long seq; - - @Column(name="cleanup_delegate", length=128) - private String delegate; - - @Column(name="cleanup_context", length=65535) - private String context; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date created; - - public CheckPointVO() { - } - - public CheckPointVO(long seq) { - this.seq = seq; - } - - public long getId() { - return id; - } - - public long getMsid() { - return msid; - } - - public void setMsid(long msid) { - this.msid = msid; - } - - public long getThreadId() { - return threadId; - } - - public void setThreadId(long threadId) { - this.threadId = threadId; - } - - public long getSeq() { - return seq; - } - - public void setSeq(long seq) { - this.seq = seq; - } - - public String getDelegate() { - return delegate; - } - - public void setDelegate(String delegate) { - this.delegate = delegate; - } - - public String getContext() { - return context; - } - - public void setContext(String context) { - this.context = context; - } - - public Date getCreated() { - return this.created; - } - - public void setCreated(Date created) { - this.created = created; - } - - @Override - public String toString() { - return new StringBuilder("Task[").append(id).append("-").append(context).append("-").append(delegate).append("]").toString(); - } -} +package com.cloud.cluster; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name="stack_maid") +public class CheckPointVO { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="msid") + private long msid; + + @Column(name="thread_id") + private long threadId; + + @Column(name="seq") + private long seq; + + @Column(name="cleanup_delegate", length=128) + private String delegate; + + @Column(name="cleanup_context", length=65535) + private String context; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + public CheckPointVO() { + } + + public CheckPointVO(long seq) { + this.seq = seq; + } + + public long getId() { + return id; + } + + public long getMsid() { + return msid; + } + + public void setMsid(long msid) { + this.msid = msid; + } + + public long getThreadId() { + return threadId; + } + + public void setThreadId(long threadId) { + this.threadId = threadId; + } + + public long getSeq() { + return seq; + } + + public void setSeq(long seq) { + this.seq = seq; + } + + public String getDelegate() { + return delegate; + } + + public void setDelegate(String delegate) { + this.delegate = delegate; + } + + public String getContext() { + return context; + } + + public void setContext(String context) { + this.context = context; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + @Override + public String toString() { + return new StringBuilder("Task[").append(id).append("-").append(context).append("-").append(delegate).append("]").toString(); + } +} diff --git a/server/src/com/cloud/cluster/ClusterManager.java b/server/src/com/cloud/cluster/ClusterManager.java index 2bb774af8fb..7268edc0fb0 100755 --- a/server/src/com/cloud/cluster/ClusterManager.java +++ b/server/src/com/cloud/cluster/ClusterManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.exception.AgentUnavailableException; @@ -19,45 +19,45 @@ import com.cloud.exception.OperationTimedoutException; import com.cloud.host.Status.Event; import com.cloud.resource.ResourceState; import com.cloud.utils.component.Manager; - -public interface ClusterManager extends Manager { - public static final int DEFAULT_HEARTBEAT_INTERVAL = 1500; - public static final int DEFAULT_HEARTBEAT_THRESHOLD = 150000; - public static final String ALERT_SUBJECT = "cluster-alert"; + +public interface ClusterManager extends Manager { + public static final int DEFAULT_HEARTBEAT_INTERVAL = 1500; + public static final int DEFAULT_HEARTBEAT_THRESHOLD = 150000; + public static final String ALERT_SUBJECT = "cluster-alert"; public void OnReceiveClusterServicePdu(ClusterServicePdu pdu); public void executeAsync(String strPeer, long agentId, Command [] cmds, boolean stopOnError); - public Answer[] execute(String strPeer, long agentId, Command [] cmds, boolean stopOnError); + public Answer[] execute(String strPeer, long agentId, Command [] cmds, boolean stopOnError); public Answer[] sendToAgent(Long hostId, Command [] cmds, boolean stopOnError) throws AgentUnavailableException, OperationTimedoutException; - public boolean executeAgentUserRequest(long agentId, Event event) throws AgentUnavailableException; + public boolean executeAgentUserRequest(long agentId, Event event) throws AgentUnavailableException; public Boolean propagateAgentEvent(long agentId, Event event) throws AgentUnavailableException; public Boolean propagateResourceEvent(long agentId, ResourceState.Event event) throws AgentUnavailableException; - public boolean executeResourceUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException; - + public boolean executeResourceUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException; + public int getHeartbeatThreshold(); - + public long getManagementNodeId(); // msid of current management server node public boolean isManagementNodeAlive(long msid); public boolean pingManagementNode(long msid); public long getCurrentRunId(); - public String getSelfPeerName(); - public String getSelfNodeIP(); - public String getPeerName(long agentHostId); - - public void registerListener(ClusterManagerListener listener); - public void unregisterListener(ClusterManagerListener listener); - public ManagementServerHostVO getPeer(String peerName); - - /** - * Broadcast the command to all of the management server nodes. - * @param agentId agent id this broadcast is regarding - * @param cmds commands to broadcast - */ + public String getSelfPeerName(); + public String getSelfNodeIP(); + public String getPeerName(long agentHostId); + + public void registerListener(ClusterManagerListener listener); + public void unregisterListener(ClusterManagerListener listener); + public ManagementServerHostVO getPeer(String peerName); + + /** + * Broadcast the command to all of the management server nodes. + * @param agentId agent id this broadcast is regarding + * @param cmds commands to broadcast + */ public void broadcast(long agentId, Command[] cmds); boolean rebalanceAgent(long agentId, Event event, long currentOwnerId, long futureOwnerId) throws AgentUnavailableException, OperationTimedoutException; - boolean isAgentRebalanceEnabled(); -} + boolean isAgentRebalanceEnabled(); +} diff --git a/server/src/com/cloud/cluster/ClusterManagerListener.java b/server/src/com/cloud/cluster/ClusterManagerListener.java index fbad4e1fde9..485ae5d0f98 100644 --- a/server/src/com/cloud/cluster/ClusterManagerListener.java +++ b/server/src/com/cloud/cluster/ClusterManagerListener.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import java.util.List; - -public interface ClusterManagerListener { - void onManagementNodeJoined(List nodeList, long selfNodeId); + +public interface ClusterManagerListener { + void onManagementNodeJoined(List nodeList, long selfNodeId); void onManagementNodeLeft(List nodeList, long selfNodeId); - void onManagementNodeIsolated(); -} + void onManagementNodeIsolated(); +} diff --git a/server/src/com/cloud/cluster/ClusterNodeJoinEventArgs.java b/server/src/com/cloud/cluster/ClusterNodeJoinEventArgs.java index 333de85c0ae..1a793d63da0 100644 --- a/server/src/com/cloud/cluster/ClusterNodeJoinEventArgs.java +++ b/server/src/com/cloud/cluster/ClusterNodeJoinEventArgs.java @@ -10,30 +10,30 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.util.List; - +package com.cloud.cluster; + +import java.util.List; + import com.cloud.utils.events.EventArgs; - -public class ClusterNodeJoinEventArgs extends EventArgs { - private static final long serialVersionUID = 6284545402661799476L; - - private List joinedNodes; - private Long self; - - public ClusterNodeJoinEventArgs(Long self, List joinedNodes) { - super(ClusterManager.ALERT_SUBJECT); - - this.self = self; - this.joinedNodes = joinedNodes; - } - - public List getJoinedNodes() { - return joinedNodes; - } - - public Long getSelf() { - return self; - } -} + +public class ClusterNodeJoinEventArgs extends EventArgs { + private static final long serialVersionUID = 6284545402661799476L; + + private List joinedNodes; + private Long self; + + public ClusterNodeJoinEventArgs(Long self, List joinedNodes) { + super(ClusterManager.ALERT_SUBJECT); + + this.self = self; + this.joinedNodes = joinedNodes; + } + + public List getJoinedNodes() { + return joinedNodes; + } + + public Long getSelf() { + return self; + } +} diff --git a/server/src/com/cloud/cluster/ClusterNodeLeftEventArgs.java b/server/src/com/cloud/cluster/ClusterNodeLeftEventArgs.java index 6cf622d3b57..0f70611addc 100644 --- a/server/src/com/cloud/cluster/ClusterNodeLeftEventArgs.java +++ b/server/src/com/cloud/cluster/ClusterNodeLeftEventArgs.java @@ -10,31 +10,31 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.util.List; +package com.cloud.cluster; + +import java.util.List; import com.cloud.utils.events.EventArgs; - -public class ClusterNodeLeftEventArgs extends EventArgs { - private static final long serialVersionUID = 7236743316223611935L; - - private List leftNodes; - private Long self; - - public ClusterNodeLeftEventArgs(Long self, List leftNodes) { - super(ClusterManager.ALERT_SUBJECT); - - this.self = self; - this.leftNodes = leftNodes; - } - - public List getLeftNodes() { - return leftNodes; - } - - public Long getSelf() { - return self; - } -} - + +public class ClusterNodeLeftEventArgs extends EventArgs { + private static final long serialVersionUID = 7236743316223611935L; + + private List leftNodes; + private Long self; + + public ClusterNodeLeftEventArgs(Long self, List leftNodes) { + super(ClusterManager.ALERT_SUBJECT); + + this.self = self; + this.leftNodes = leftNodes; + } + + public List getLeftNodes() { + return leftNodes; + } + + public Long getSelf() { + return self; + } +} + diff --git a/server/src/com/cloud/cluster/ClusterService.java b/server/src/com/cloud/cluster/ClusterService.java index 7f7b818a3a6..16de2174bf4 100644 --- a/server/src/com/cloud/cluster/ClusterService.java +++ b/server/src/com/cloud/cluster/ClusterService.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import java.rmi.Remote; import java.rmi.RemoteException; - + public interface ClusterService extends Remote { String execute(ClusterServicePdu pdu) throws RemoteException; boolean ping(String callingPeer) throws RemoteException; -} +} diff --git a/server/src/com/cloud/cluster/ClusterServiceAdapter.java b/server/src/com/cloud/cluster/ClusterServiceAdapter.java index 5645bd1cedd..5f8fbef0c37 100644 --- a/server/src/com/cloud/cluster/ClusterServiceAdapter.java +++ b/server/src/com/cloud/cluster/ClusterServiceAdapter.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.rmi.RemoteException; - -import com.cloud.cluster.ClusterService; -import com.cloud.utils.component.Adapter; - -public interface ClusterServiceAdapter extends Adapter { - public ClusterService getPeerService(String strPeer) throws RemoteException; - public String getServiceEndpointName(String strPeer); - public int getServicePort(); -} +package com.cloud.cluster; + +import java.rmi.RemoteException; + +import com.cloud.cluster.ClusterService; +import com.cloud.utils.component.Adapter; + +public interface ClusterServiceAdapter extends Adapter { + public ClusterService getPeerService(String strPeer) throws RemoteException; + public String getServiceEndpointName(String strPeer); + public int getServicePort(); +} diff --git a/server/src/com/cloud/cluster/ClusterServiceServletAdapter.java b/server/src/com/cloud/cluster/ClusterServiceServletAdapter.java index f57733b0e5e..e26449c323e 100644 --- a/server/src/com/cloud/cluster/ClusterServiceServletAdapter.java +++ b/server/src/com/cloud/cluster/ClusterServiceServletAdapter.java @@ -10,49 +10,49 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.rmi.RemoteException; -import java.util.Map; -import java.util.Properties; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.cluster.dao.ManagementServerHostDao; +package com.cloud.cluster; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.rmi.RemoteException; +import java.util.Map; +import java.util.Properties; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.ComponentLocator; - -@Local(value={ClusterServiceAdapter.class}) -public class ClusterServiceServletAdapter implements ClusterServiceAdapter { - - private static final Logger s_logger = Logger.getLogger(ClusterServiceServletAdapter.class); +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.component.ComponentLocator; + +@Local(value={ClusterServiceAdapter.class}) +public class ClusterServiceServletAdapter implements ClusterServiceAdapter { + + private static final Logger s_logger = Logger.getLogger(ClusterServiceServletAdapter.class); private static final int DEFAULT_SERVICE_PORT = 9090; - private static final int DEFAULT_REQUEST_TIMEOUT = 300; // 300 seconds - - private ClusterManager _manager; - + private static final int DEFAULT_REQUEST_TIMEOUT = 300; // 300 seconds + + private ClusterManager _manager; + private ManagementServerHostDao _mshostDao; private ConfigurationDao _configDao; - - private ClusterServiceServletContainer _servletContainer; - - private String _name; + + private ClusterServiceServletContainer _servletContainer; + + private String _name; private int _clusterServicePort = DEFAULT_SERVICE_PORT; private int _clusterRequestTimeoutSeconds = DEFAULT_REQUEST_TIMEOUT; - - @Override + + @Override public ClusterService getPeerService(String strPeer) throws RemoteException { try { init(); @@ -60,68 +60,68 @@ public class ClusterServiceServletAdapter implements ClusterServiceAdapter { s_logger.error("Unable to init ClusterServiceServletAdapter"); throw new RemoteException("Unable to init ClusterServiceServletAdapter"); } - - String serviceUrl = getServiceEndpointName(strPeer); - if(serviceUrl == null) - return null; - - return new ClusterServiceServletImpl(serviceUrl, _clusterRequestTimeoutSeconds); - } - - @Override - public String getServiceEndpointName(String strPeer) { + + String serviceUrl = getServiceEndpointName(strPeer); + if(serviceUrl == null) + return null; + + return new ClusterServiceServletImpl(serviceUrl, _clusterRequestTimeoutSeconds); + } + + @Override + public String getServiceEndpointName(String strPeer) { try { init(); } catch (ConfigurationException e) { s_logger.error("Unable to init ClusterServiceServletAdapter"); return null; } - - long msid = Long.parseLong(strPeer); - - ManagementServerHostVO mshost = _mshostDao.findByMsid(msid); - if(mshost == null) - return null; - - return composeEndpointName(mshost.getServiceIP(), mshost.getServicePort()); - } - - @Override - public int getServicePort() { - return _clusterServicePort; - } - - private String composeEndpointName(String nodeIP, int port) { - StringBuffer sb = new StringBuffer(); - sb.append("http://").append(nodeIP).append(":").append(port).append("/clusterservice"); - return sb.toString(); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - init(); - return true; + + long msid = Long.parseLong(strPeer); + + ManagementServerHostVO mshost = _mshostDao.findByMsid(msid); + if(mshost == null) + return null; + + return composeEndpointName(mshost.getServiceIP(), mshost.getServicePort()); } - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - _servletContainer = new ClusterServiceServletContainer(); - _servletContainer.start(new ClusterServiceServletHttpHandler(_manager), _clusterServicePort); - return true; - } - - @Override - public boolean stop() { - if(_servletContainer != null) - _servletContainer.stop(); - return true; + @Override + public int getServicePort() { + return _clusterServicePort; + } + + private String composeEndpointName(String nodeIP, int port) { + StringBuffer sb = new StringBuffer(); + sb.append("http://").append(nodeIP).append(":").append(port).append("/clusterservice"); + return sb.toString(); + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + init(); + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + _servletContainer = new ClusterServiceServletContainer(); + _servletContainer.start(new ClusterServiceServletHttpHandler(_manager), _clusterServicePort); + return true; + } + + @Override + public boolean stop() { + if(_servletContainer != null) + _servletContainer.stop(); + return true; } private void init() throws ConfigurationException { @@ -163,4 +163,4 @@ public class ClusterServiceServletAdapter implements ClusterServiceAdapter { if(s_logger.isInfoEnabled()) s_logger.info("Cluster servlet port : " + _clusterServicePort); } -} +} diff --git a/server/src/com/cloud/cluster/ClusterServiceServletContainer.java b/server/src/com/cloud/cluster/ClusterServiceServletContainer.java index b1b281484ce..00b8e3d6243 100644 --- a/server/src/com/cloud/cluster/ClusterServiceServletContainer.java +++ b/server/src/com/cloud/cluster/ClusterServiceServletContainer.java @@ -10,98 +10,98 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.apache.http.ConnectionClosedException; -import org.apache.http.HttpException; -import org.apache.http.impl.DefaultConnectionReuseStrategy; -import org.apache.http.impl.DefaultHttpResponseFactory; -import org.apache.http.impl.DefaultHttpServerConnection; -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.utils.concurrency.NamedThreadFactory; - -public class ClusterServiceServletContainer { - private static final Logger s_logger = Logger.getLogger(ClusterServiceServletContainer.class); - +package com.cloud.cluster; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.apache.http.ConnectionClosedException; +import org.apache.http.HttpException; +import org.apache.http.impl.DefaultConnectionReuseStrategy; +import org.apache.http.impl.DefaultHttpResponseFactory; +import org.apache.http.impl.DefaultHttpServerConnection; +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.utils.concurrency.NamedThreadFactory; + +public class ClusterServiceServletContainer { + private static final Logger s_logger = Logger.getLogger(ClusterServiceServletContainer.class); + private ListenerThread listenerThread; - - public ClusterServiceServletContainer() { - } - - public boolean start(HttpRequestHandler requestHandler, int port) { - - listenerThread = new ListenerThread(requestHandler, port); - listenerThread.start(); - - return true; - } - + + public ClusterServiceServletContainer() { + } + + public boolean start(HttpRequestHandler requestHandler, int port) { + + listenerThread = new ListenerThread(requestHandler, port); + listenerThread.start(); + + return true; + } + public void stop() { if(listenerThread != null) { - listenerThread.stopRunning(); - } - } - - static class ListenerThread extends Thread { - private HttpService _httpService = null; - private volatile ServerSocket _serverSocket = null; - private HttpParams _params = null; - private ExecutorService _executor; - - public ListenerThread(HttpRequestHandler requestHandler, int port) { - _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener")); - - try { - _serverSocket = new ServerSocket(port); - } catch (IOException ioex) { - s_logger.error("error initializing cluster service servlet container", ioex); - return; - } - - _params = new BasicHttpParams(); - _params - .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) - .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("/clusterservice", requestHandler); - - // Set up the HTTP service - _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); - _httpService.setParams(_params); - _httpService.setHandlerResolver(reqistry); + listenerThread.stopRunning(); + } + } + + static class ListenerThread extends Thread { + private HttpService _httpService = null; + private volatile ServerSocket _serverSocket = null; + private HttpParams _params = null; + private ExecutorService _executor; + + public ListenerThread(HttpRequestHandler requestHandler, int port) { + _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener")); + + try { + _serverSocket = new ServerSocket(port); + } catch (IOException ioex) { + s_logger.error("error initializing cluster service servlet container", ioex); + return; + } + + _params = new BasicHttpParams(); + _params + .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) + .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("/clusterservice", requestHandler); + + // Set up the HTTP service + _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); + _httpService.setParams(_params); + _httpService.setHandlerResolver(reqistry); } public void stopRunning() { @@ -112,50 +112,50 @@ public class ClusterServiceServletContainer { } _serverSocket = null; } - } - - public void run() { - if(s_logger.isInfoEnabled()) - s_logger.info("Cluster service servlet container listening on port " + _serverSocket.getLocalPort()); - - while (_serverSocket != null) { - try { - // Set up HTTP connection - Socket socket = _serverSocket.accept(); - final DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); - conn.bind(socket, _params); - - _executor.execute(new Runnable() { - public void run() { - HttpContext context = new BasicHttpContext(null); + } + + public void run() { + if(s_logger.isInfoEnabled()) + s_logger.info("Cluster service servlet container listening on port " + _serverSocket.getLocalPort()); + + while (_serverSocket != null) { + try { + // Set up HTTP connection + Socket socket = _serverSocket.accept(); + final DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); + conn.bind(socket, _params); + + _executor.execute(new Runnable() { + public void run() { + HttpContext context = new BasicHttpContext(null); try { - while(!Thread.interrupted() && conn.isOpen()) { - if(s_logger.isTraceEnabled()) - s_logger.trace("dispatching cluster request from " + conn.getRemoteAddress().toString()); - - _httpService.handleRequest(conn, context); - - if(s_logger.isTraceEnabled()) + while(!Thread.interrupted() && conn.isOpen()) { + if(s_logger.isTraceEnabled()) + s_logger.trace("dispatching cluster request from " + conn.getRemoteAddress().toString()); + + _httpService.handleRequest(conn, context); + + if(s_logger.isTraceEnabled()) s_logger.trace("Cluster request from " + conn.getRemoteAddress().toString() + " is processed"); - } + } } catch (ConnectionClosedException ex) { // client close and read time out exceptions are expected - // when KEEP-AVLIE is enabled - s_logger.trace("Client closed connection", ex); - } catch (IOException ex) { - s_logger.trace("I/O error", ex); - } catch (HttpException ex) { - s_logger.error("Unrecoverable HTTP protocol violation", ex); - } finally { - try { + // when KEEP-AVLIE is enabled + s_logger.trace("Client closed connection", ex); + } catch (IOException ex) { + s_logger.trace("I/O error", ex); + } catch (HttpException ex) { + s_logger.error("Unrecoverable HTTP protocol violation", ex); + } finally { + try { conn.shutdown(); } catch (IOException ignore) { s_logger.error("unexpected exception", ignore); - } - } + } + } } - }); - + }); + } catch (Throwable e) { s_logger.error("Unexpected exception ", e); @@ -163,13 +163,13 @@ public class ClusterServiceServletContainer { try { Thread.sleep(1000); } catch (InterruptedException e1) { - } - } - } - - _executor.shutdown(); - if(s_logger.isInfoEnabled()) - s_logger.info("Cluster service servlet container shutdown"); - } - } -} + } + } + } + + _executor.shutdown(); + if(s_logger.isInfoEnabled()) + s_logger.info("Cluster service servlet container shutdown"); + } + } +} diff --git a/server/src/com/cloud/cluster/ClusterServiceServletHttpHandler.java b/server/src/com/cloud/cluster/ClusterServiceServletHttpHandler.java index 14d299a22c2..7d932a143f6 100755 --- a/server/src/com/cloud/cluster/ClusterServiceServletHttpHandler.java +++ b/server/src/com/cloud/cluster/ClusterServiceServletHttpHandler.java @@ -10,7 +10,7 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; +package com.cloud.cluster; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -27,129 +27,129 @@ import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -public class ClusterServiceServletHttpHandler implements HttpRequestHandler { - private static final Logger s_logger = Logger.getLogger(ClusterServiceServletHttpHandler.class); - - private final ClusterManager manager; - - public ClusterServiceServletHttpHandler(ClusterManager manager) { - this.manager = manager; - } - - @Override - public void handle(HttpRequest request, HttpResponse response, HttpContext context) - throws HttpException, IOException { - - try { +public class ClusterServiceServletHttpHandler implements HttpRequestHandler { + private static final Logger s_logger = Logger.getLogger(ClusterServiceServletHttpHandler.class); + + private final ClusterManager manager; + + public ClusterServiceServletHttpHandler(ClusterManager manager) { + this.manager = manager; + } + + @Override + public void handle(HttpRequest request, HttpResponse response, HttpContext context) + throws HttpException, IOException { + + try { if(s_logger.isTraceEnabled()) { s_logger.trace("Start Handling cluster HTTP request"); - } - - parseRequest(request); - handleRequest(request, response); - + } + + parseRequest(request); + handleRequest(request, response); + if(s_logger.isTraceEnabled()) { s_logger.trace("Handle cluster HTTP request done"); - } - - } catch(Throwable e) { + } + + } catch(Throwable e) { if(s_logger.isDebugEnabled()) { s_logger.debug("Exception " + e.toString()); - } + } - try { + try { writeResponse(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, null); } catch(Throwable e2) { if(s_logger.isDebugEnabled()) { s_logger.debug("Exception " + e2.toString()); } - } - } - } - - @SuppressWarnings("deprecation") - private void parseRequest(HttpRequest request) throws IOException { - if(request instanceof HttpEntityEnclosingRequest) { - HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest)request; - - String body = EntityUtils.toString(entityRequest.getEntity()); - if(body != null) { - String[] paramArray = body.split("&"); - if(paramArray != null) { - for (String paramEntry : paramArray) { - String[] paramValue = paramEntry.split("="); + } + } + } + + @SuppressWarnings("deprecation") + private void parseRequest(HttpRequest request) throws IOException { + if(request instanceof HttpEntityEnclosingRequest) { + HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest)request; + + String body = EntityUtils.toString(entityRequest.getEntity()); + if(body != null) { + String[] paramArray = body.split("&"); + if(paramArray != null) { + for (String paramEntry : paramArray) { + String[] paramValue = paramEntry.split("="); if (paramValue.length != 2) { continue; - } - - String name = URLDecoder.decode(paramValue[0]); - String value = URLDecoder.decode(paramValue[1]); - + } + + String name = URLDecoder.decode(paramValue[0]); + String value = URLDecoder.decode(paramValue[1]); + if(s_logger.isTraceEnabled()) { s_logger.trace("Parsed request parameter " + name + "=" + value); - } - request.getParams().setParameter(name, value); - } - } - } - } - } - - private void writeResponse(HttpResponse response, int statusCode, String content) { + } + request.getParams().setParameter(name, value); + } + } + } + } + } + + private void writeResponse(HttpResponse response, int statusCode, String content) { if(content == null) { content = ""; - } - response.setStatusCode(statusCode); - BasicHttpEntity body = new BasicHttpEntity(); - body.setContentType("text/html; charset=UTF-8"); - - byte[] bodyData = content.getBytes(); - body.setContent(new ByteArrayInputStream(bodyData)); - body.setContentLength(bodyData.length); - response.setEntity(body); - } - - protected void handleRequest(HttpRequest req, HttpResponse response) { - String method = (String)req.getParams().getParameter("method"); - - int nMethod = RemoteMethodConstants.METHOD_UNKNOWN; - String responseContent = null; - try { + } + response.setStatusCode(statusCode); + BasicHttpEntity body = new BasicHttpEntity(); + body.setContentType("text/html; charset=UTF-8"); + + byte[] bodyData = content.getBytes(); + body.setContent(new ByteArrayInputStream(bodyData)); + body.setContentLength(bodyData.length); + response.setEntity(body); + } + + protected void handleRequest(HttpRequest req, HttpResponse response) { + String method = (String)req.getParams().getParameter("method"); + + int nMethod = RemoteMethodConstants.METHOD_UNKNOWN; + String responseContent = null; + try { if(method != null) { nMethod = Integer.parseInt(method); - } - - switch(nMethod) { + } + + switch(nMethod) { case RemoteMethodConstants.METHOD_DELIVER_PDU : responseContent = handleDeliverPduMethodCall(req); break; - - case RemoteMethodConstants.METHOD_PING : - responseContent = handlePingMethodCall(req); - break; - - case RemoteMethodConstants.METHOD_UNKNOWN : - default : - assert(false); - s_logger.error("unrecognized method " + nMethod); - break; - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when processing cluster service request : ", e); - } - + + case RemoteMethodConstants.METHOD_PING : + responseContent = handlePingMethodCall(req); + break; + + case RemoteMethodConstants.METHOD_UNKNOWN : + default : + assert(false); + s_logger.error("unrecognized method " + nMethod); + break; + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when processing cluster service request : ", e); + } + if(responseContent != null) { if(s_logger.isTraceEnabled()) s_logger.trace("Write reponse with HTTP OK " + responseContent); - - writeResponse(response, HttpStatus.SC_OK, responseContent); + + writeResponse(response, HttpStatus.SC_OK, responseContent); } else { if(s_logger.isTraceEnabled()) s_logger.trace("Write reponse with HTTP Bad request"); - - writeResponse(response, HttpStatus.SC_BAD_REQUEST, null); - } - } + + writeResponse(response, HttpStatus.SC_BAD_REQUEST, null); + } + } private String handleDeliverPduMethodCall(HttpRequest req) { @@ -175,14 +175,14 @@ public class ClusterServiceServletHttpHandler implements HttpRequestHandler { manager.OnReceiveClusterServicePdu(pdu); return "true"; } - - private String handlePingMethodCall(HttpRequest req) { - String callingPeer = (String)req.getParams().getParameter("callingPeer"); - + + private String handlePingMethodCall(HttpRequest req) { + String callingPeer = (String)req.getParams().getParameter("callingPeer"); + if(s_logger.isDebugEnabled()) { s_logger.debug("Handle ping request from " + callingPeer); - } - - return "true"; - } -} + } + + return "true"; + } +} diff --git a/server/src/com/cloud/cluster/ClusterServiceServletImpl.java b/server/src/com/cloud/cluster/ClusterServiceServletImpl.java index da0e577cee4..7ed8c36eab5 100644 --- a/server/src/com/cloud/cluster/ClusterServiceServletImpl.java +++ b/server/src/com/cloud/cluster/ClusterServiceServletImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import java.io.IOException; import java.rmi.RemoteException; @@ -23,26 +23,26 @@ import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.log4j.Logger; -public class ClusterServiceServletImpl implements ClusterService { +public class ClusterServiceServletImpl implements ClusterService { private static final long serialVersionUID = 4574025200012566153L; - private static final Logger s_logger = Logger.getLogger(ClusterServiceServletImpl.class); - + private static final Logger s_logger = Logger.getLogger(ClusterServiceServletImpl.class); + private String _serviceUrl; - + private int _requestTimeoutSeconds; protected static HttpClient s_client = null; - - public ClusterServiceServletImpl() { - } - + + public ClusterServiceServletImpl() { + } + public ClusterServiceServletImpl(String serviceUrl, int requestTimeoutSeconds) { s_logger.info("Setup cluster service servlet. service url: " + serviceUrl + ", request timeout: " + requestTimeoutSeconds + " seconds"); - + this._serviceUrl = serviceUrl; - this._requestTimeoutSeconds = requestTimeoutSeconds; + this._requestTimeoutSeconds = requestTimeoutSeconds; } - @Override + @Override public String execute(ClusterServicePdu pdu) throws RemoteException { HttpClient client = getHttpClient(); @@ -66,54 +66,54 @@ public class ClusterServiceServletImpl implements ClusterService { } @Override - public boolean ping(String callingPeer) throws RemoteException { + public boolean ping(String callingPeer) throws RemoteException { if(s_logger.isDebugEnabled()) { s_logger.debug("Ping at " + _serviceUrl); - } + } - HttpClient client = getHttpClient(); - PostMethod method = new PostMethod(_serviceUrl); - - method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_PING)); + HttpClient client = getHttpClient(); + PostMethod method = new PostMethod(_serviceUrl); + + method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_PING)); method.addParameter("callingPeer", callingPeer); - try { + try { String returnVal = executePostMethod(client, method); if("true".equalsIgnoreCase(returnVal)) { return true; - } + } return false; } finally { method.releaseConnection(); - } - } - - private String executePostMethod(HttpClient client, PostMethod method) { - int response = 0; - String result = null; - try { - long startTick = System.currentTimeMillis(); - response = client.executeMethod(method); - if(response == HttpStatus.SC_OK) { - result = method.getResponseBodyAsString(); - if(s_logger.isDebugEnabled()) { - s_logger.debug("POST " + _serviceUrl + " response :" + result + ", responding time: " - + (System.currentTimeMillis() - startTick) + " ms"); - } - } else { - s_logger.error("Invalid response code : " + response + ", from : " - + _serviceUrl + ", method : " + method.getParameter("method") - + " responding time: " + (System.currentTimeMillis() - startTick)); - } - } catch (HttpException e) { - s_logger.error("HttpException from : " + _serviceUrl + ", method : " + method.getParameter("method")); - } catch (IOException e) { - s_logger.error("IOException from : " + _serviceUrl + ", method : " + method.getParameter("method")); - } catch(Throwable e) { - s_logger.error("Exception from : " + _serviceUrl + ", method : " + method.getParameter("method") + ", exception :", e); - } + } + } - return result; + private String executePostMethod(HttpClient client, PostMethod method) { + int response = 0; + String result = null; + try { + long startTick = System.currentTimeMillis(); + response = client.executeMethod(method); + if(response == HttpStatus.SC_OK) { + result = method.getResponseBodyAsString(); + if(s_logger.isDebugEnabled()) { + s_logger.debug("POST " + _serviceUrl + " response :" + result + ", responding time: " + + (System.currentTimeMillis() - startTick) + " ms"); + } + } else { + s_logger.error("Invalid response code : " + response + ", from : " + + _serviceUrl + ", method : " + method.getParameter("method") + + " responding time: " + (System.currentTimeMillis() - startTick)); + } + } catch (HttpException e) { + s_logger.error("HttpException from : " + _serviceUrl + ", method : " + method.getParameter("method")); + } catch (IOException e) { + s_logger.error("IOException from : " + _serviceUrl + ", method : " + method.getParameter("method")); + } catch(Throwable e) { + s_logger.error("Exception from : " + _serviceUrl + ", method : " + method.getParameter("method") + ", exception :", e); + } + + return result; } private HttpClient getHttpClient() { @@ -133,16 +133,16 @@ public class ClusterServiceServletImpl implements ClusterService { } return s_client; } - - // for test purpose only - public static void main(String[] args) { + + // for test purpose only + public static void main(String[] args) { /* - ClusterServiceServletImpl service = new ClusterServiceServletImpl("http://localhost:9090/clusterservice", 300); - try { - String result = service.execute("test", 1, "{ p1:v1, p2:v2 }", true); - System.out.println(result); - } catch (RemoteException e) { + ClusterServiceServletImpl service = new ClusterServiceServletImpl("http://localhost:9090/clusterservice", 300); + try { + String result = service.execute("test", 1, "{ p1:v1, p2:v2 }", true); + System.out.println(result); + } catch (RemoteException e) { } */ - } -} + } +} diff --git a/server/src/com/cloud/cluster/DummyClusterManagerImpl.java b/server/src/com/cloud/cluster/DummyClusterManagerImpl.java index 2e631ed706b..38ca1bf0537 100755 --- a/server/src/com/cloud/cluster/DummyClusterManagerImpl.java +++ b/server/src/com/cloud/cluster/DummyClusterManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import java.util.Map; import javax.ejb.Local; @@ -28,15 +28,15 @@ import com.cloud.host.Status.Event; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.MacAddress; -@Local(value={ClusterManager.class}) -public class DummyClusterManagerImpl implements ClusterManager { - private static final Logger s_logger = Logger.getLogger(DummyClusterManagerImpl.class); - +@Local(value={ClusterManager.class}) +public class DummyClusterManagerImpl implements ClusterManager { + private static final Logger s_logger = Logger.getLogger(DummyClusterManagerImpl.class); + protected long _id = MacAddress.getMacAddress().toLong(); protected long _runId = System.currentTimeMillis(); - - private String _name; - private final String _clusterNodeIP = "127.0.0.1"; + + private String _name; + private final String _clusterNodeIP = "127.0.0.1"; @Override public void OnReceiveClusterServicePdu(ClusterServicePdu pdu) { @@ -47,63 +47,63 @@ public class DummyClusterManagerImpl implements ClusterManager { public void executeAsync(String strPeer, long agentId, Command [] cmds, boolean stopOnError) { throw new CloudRuntimeException("Unsupported feature"); } - + @Override - public Answer[] execute(String strPeer, long agentId, Command [] cmds, boolean stopOnError) { - throw new CloudRuntimeException("Unsupported feature"); + public Answer[] execute(String strPeer, long agentId, Command [] cmds, boolean stopOnError) { + throw new CloudRuntimeException("Unsupported feature"); } @Override - public Answer[] sendToAgent(Long hostId, Command [] cmds, boolean stopOnError) - throws AgentUnavailableException, OperationTimedoutException { - throw new CloudRuntimeException("Unsupported feature"); - } + public Answer[] sendToAgent(Long hostId, Command [] cmds, boolean stopOnError) + throws AgentUnavailableException, OperationTimedoutException { + throw new CloudRuntimeException("Unsupported feature"); + } -/* +/* @Override - public long sendToAgent(Long hostId, Command[] cmds, boolean stopOnError, Listener listener) throws AgentUnavailableException { - throw new CloudRuntimeException("Unsupported feature"); - } -*/ + public long sendToAgent(Long hostId, Command[] cmds, boolean stopOnError, Listener listener) throws AgentUnavailableException { + throw new CloudRuntimeException("Unsupported feature"); + } +*/ @Override - public boolean executeAgentUserRequest(long agentId, Event event) throws AgentUnavailableException { - throw new CloudRuntimeException("Unsupported feature"); - } - + public boolean executeAgentUserRequest(long agentId, Event event) throws AgentUnavailableException { + throw new CloudRuntimeException("Unsupported feature"); + } + @Override - public Boolean propagateAgentEvent(long agentId, Event event) throws AgentUnavailableException { - throw new CloudRuntimeException("Unsupported feature"); - } - + public Boolean propagateAgentEvent(long agentId, Event event) throws AgentUnavailableException { + throw new CloudRuntimeException("Unsupported feature"); + } + @Override - public int getHeartbeatThreshold() { - return ClusterManager.DEFAULT_HEARTBEAT_INTERVAL; - } - + public int getHeartbeatThreshold() { + return ClusterManager.DEFAULT_HEARTBEAT_INTERVAL; + } + @Override - public long getManagementNodeId() { - return _id; + public long getManagementNodeId() { + return _id; } @Override public long getCurrentRunId() { return _runId; } - - @Override - public ManagementServerHostVO getPeer(String str) { - return null; - } - + @Override - public String getSelfPeerName() { - return Long.toString(_id); - } - + public ManagementServerHostVO getPeer(String str) { + return null; + } + @Override - public String getSelfNodeIP() { - return _clusterNodeIP; - } + public String getSelfPeerName() { + return Long.toString(_id); + } + + @Override + public String getSelfNodeIP() { + return _clusterNodeIP; + } @Override public boolean isManagementNodeAlive(long msid) { @@ -114,46 +114,46 @@ public class DummyClusterManagerImpl implements ClusterManager { public boolean pingManagementNode(long msid) { return false; } - + @Override - public String getPeerName(long agentHostId) { - throw new CloudRuntimeException("Unsupported feature"); - } - + public String getPeerName(long agentHostId) { + throw new CloudRuntimeException("Unsupported feature"); + } + @Override - public void registerListener(ClusterManagerListener listener) { - } - + public void registerListener(ClusterManagerListener listener) { + } + @Override - public void unregisterListener(ClusterManagerListener listener) { - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - return true; - } - - @Override - public void broadcast(long hostId, Command[] cmds) { - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - if(s_logger.isInfoEnabled()) - s_logger.info("Starting cluster manager, msid : " + _id); - - return true; - } - - @Override - public boolean stop() { - return true; + public void unregisterListener(ClusterManagerListener listener) { + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + return true; + } + + @Override + public void broadcast(long hostId, Command[] cmds) { + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + if(s_logger.isInfoEnabled()) + s_logger.info("Starting cluster manager, msid : " + _id); + + return true; + } + + @Override + public boolean stop() { + return true; } @Override @@ -176,5 +176,5 @@ public class DummyClusterManagerImpl implements ClusterManager { public boolean executeResourceUserRequest(long hostId, com.cloud.resource.ResourceState.Event event) throws AgentUnavailableException { // TODO Auto-generated method stub return false; - } -} + } +} diff --git a/server/src/com/cloud/cluster/ManagementServerHostVO.java b/server/src/com/cloud/cluster/ManagementServerHostVO.java index 5799569ffc2..8bbd384c5de 100644 --- a/server/src/com/cloud/cluster/ManagementServerHostVO.java +++ b/server/src/com/cloud/cluster/ManagementServerHostVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - +package com.cloud.cluster; + import java.util.Date; import javax.persistence.Column; @@ -26,65 +26,65 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="mshost") -public class ManagementServerHostVO implements ManagementServerHost{ - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="msid", updatable=true, nullable=false) + +@Entity +@Table(name="mshost") +public class ManagementServerHostVO implements ManagementServerHost{ + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="msid", updatable=true, nullable=false) private long msid; @Column(name="runid", updatable=true, nullable=false) - private long runid; - - @Column(name="name", updatable=true, nullable=true) + private long runid; + + @Column(name="name", updatable=true, nullable=true) private String name; @Column(name="state", updatable = true, nullable=false) @Enumerated(value=EnumType.STRING) - private ManagementServerHost.State state; - - @Column(name="version", updatable=true, nullable=true) - private String version; - - @Column(name="service_ip", updatable=true, nullable=false) - private String serviceIP; - - @Column(name="service_port", updatable=true, nullable=false) - private int servicePort; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="last_update", updatable=true, nullable=true) - private Date lastUpdateTime; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - @Column(name="alert_count", updatable=true, nullable=false) - private int alertCount; - - public ManagementServerHostVO() { - } - - public ManagementServerHostVO(long msid, long runid, String serviceIP, int servicePort, Date updateTime) { + private ManagementServerHost.State state; + + @Column(name="version", updatable=true, nullable=true) + private String version; + + @Column(name="service_ip", updatable=true, nullable=false) + private String serviceIP; + + @Column(name="service_port", updatable=true, nullable=false) + private int servicePort; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="last_update", updatable=true, nullable=true) + private Date lastUpdateTime; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="alert_count", updatable=true, nullable=false) + private int alertCount; + + public ManagementServerHostVO() { + } + + public ManagementServerHostVO(long msid, long runid, String serviceIP, int servicePort, Date updateTime) { this.msid = msid; - this.runid = runid; - this.serviceIP = serviceIP; - this.servicePort = servicePort; - this.lastUpdateTime = updateTime; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; + this.runid = runid; + this.serviceIP = serviceIP; + this.servicePort = servicePort; + this.lastUpdateTime = updateTime; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; } public long getRunid() { @@ -93,23 +93,23 @@ public class ManagementServerHostVO implements ManagementServerHost{ public void setRunid(long runid) { this.runid = runid; - } + } - @Override - public long getMsid() { - return msid; - } - - public void setMsid(long msid) { - this.msid = msid; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; + @Override + public long getMsid() { + return msid; + } + + public void setMsid(long msid) { + this.msid = msid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; } @Override @@ -119,59 +119,59 @@ public class ManagementServerHostVO implements ManagementServerHost{ public void setState(ManagementServerHost.State state) { this.state = state; - } + } - @Override - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getServiceIP() { - return serviceIP; - } - - public void setServiceIP(String serviceIP) { - this.serviceIP = serviceIP; - } - - public int getServicePort() { - return servicePort; - } - - public void setServicePort(int servicePort) { - this.servicePort = servicePort; - } - - public Date getLastUpdateTime() { - return lastUpdateTime; - } - - public void setLastUpdateTime(Date lastUpdateTime) { - this.lastUpdateTime = lastUpdateTime; - } - - public Date getRemoved() { - return removed; - } - - public void setRemoved(Date removedTime) { - removed = removedTime; - } - - public int getAlertCount() { - return alertCount; - } - - public void setAlertCount(int count) { - alertCount = count; + @Override + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceIP() { + return serviceIP; + } + + public void setServiceIP(String serviceIP) { + this.serviceIP = serviceIP; + } + + public int getServicePort() { + return servicePort; + } + + public void setServicePort(int servicePort) { + this.servicePort = servicePort; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removedTime) { + removed = removedTime; + } + + public int getAlertCount() { + return alertCount; + } + + public void setAlertCount(int count) { + alertCount = count; } @Override public String toString() { return new StringBuilder("ManagementServer[").append("-").append(id).append("-").append(msid).append("-").append(state).append("]").toString(); - } -} + } +} diff --git a/server/src/com/cloud/cluster/RemoteMethodConstants.java b/server/src/com/cloud/cluster/RemoteMethodConstants.java index 2c4eb687f0c..49f5b1208ac 100644 --- a/server/src/com/cloud/cluster/RemoteMethodConstants.java +++ b/server/src/com/cloud/cluster/RemoteMethodConstants.java @@ -10,10 +10,10 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -public interface RemoteMethodConstants { +package com.cloud.cluster; + +public interface RemoteMethodConstants { public static final int METHOD_UNKNOWN = 0; - public static final int METHOD_PING = 4; + public static final int METHOD_PING = 4; public static final int METHOD_DELIVER_PDU = 5; -} +} diff --git a/server/src/com/cloud/cluster/StackMaid.java b/server/src/com/cloud/cluster/StackMaid.java index 0a6bd1f86cd..f1915da1d25 100644 --- a/server/src/com/cloud/cluster/StackMaid.java +++ b/server/src/com/cloud/cluster/StackMaid.java @@ -10,140 +10,140 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.cloud.cluster.dao.StackMaidDao; -import com.cloud.cluster.dao.StackMaidDaoImpl; -import com.cloud.serializer.SerializerHelper; -import com.cloud.utils.CleanupDelegate; -import com.cloud.utils.db.Transaction; - -public class StackMaid { - protected final static Logger s_logger = Logger.getLogger(StackMaid.class); - - private static ThreadLocal threadMaid = new ThreadLocal(); - - private static long msid_setby_manager = 0; - - private StackMaidDao maidDao = new StackMaidDaoImpl(); - private int currentSeq = 0; - private Map context = new HashMap(); - - public static void init(long msid) { - msid_setby_manager = msid; - } - - public static StackMaid current() { - StackMaid maid = threadMaid.get(); - if(maid == null) { - maid = new StackMaid(); - threadMaid.set(maid); - } - return maid; - } - - public void registerContext(String key, Object contextObject) { - assert(!context.containsKey(key)) : "Context key has already been registered"; - context.put(key, contextObject); - } - - public Object getContext(String key) { - return context.get(key); - } - - public void expungeMaidItem(long maidId) { - // this is a bit ugly, but when it is not loaded by component locator, this is just a workable way for now - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - maidDao.expunge(maidId); - } finally { - txn.close(); - } - } - - public int push(String delegateClzName, Object context) { - assert(msid_setby_manager != 0) : "Fatal, make sure StackMaidManager is loaded"; - if(msid_setby_manager == 0) - s_logger.error("Fatal, make sure StackMaidManager is loaded"); - - return push(msid_setby_manager, delegateClzName, context); - } - - public int push(long currentMsid, String delegateClzName, Object context) { - int savePoint = currentSeq; - maidDao.pushCleanupDelegate(currentMsid, currentSeq++, delegateClzName, context); - return savePoint; - } - - public void pop(int savePoint) { - assert(msid_setby_manager != 0) : "Fatal, make sure StackMaidManager is loaded"; - if(msid_setby_manager == 0) - s_logger.error("Fatal, make sure StackMaidManager is loaded"); - - pop(msid_setby_manager, savePoint); - } - - public void pop() { - if(currentSeq > 0) - pop(currentSeq -1); - } - - /** - * must be called within thread context - * @param currentMsid - */ - public void pop(long currentMsid, int savePoint) { - while(currentSeq > savePoint) { - maidDao.popCleanupDelegate(currentMsid); - currentSeq--; - } - } - - public void exitCleanup() { - exitCleanup(msid_setby_manager); - } - - public void exitCleanup(long currentMsid) { - if(currentSeq > 0) { - CheckPointVO maid = null; - while((maid = maidDao.popCleanupDelegate(currentMsid)) != null) { - doCleanup(maid); - } - currentSeq = 0; - } - - context.clear(); - } - - public static boolean doCleanup(CheckPointVO maid) { - if(maid.getDelegate() != null) { - try { - Class clz = Class.forName(maid.getDelegate()); - Object delegate = clz.newInstance(); - if(delegate instanceof CleanupDelegate) { - return ((CleanupDelegate)delegate).cleanup(SerializerHelper.fromSerializedString(maid.getContext()), maid); - } else { - assert(false); - } - } catch (final ClassNotFoundException e) { - s_logger.error("Unable to load StackMaid delegate class: " + maid.getDelegate(), e); - } catch (final SecurityException e) { - s_logger.error("Security excetion when loading resource: " + maid.getDelegate()); - } catch (final IllegalArgumentException e) { - s_logger.error("Illegal argument excetion when loading resource: " + maid.getDelegate()); - } catch (final InstantiationException e) { - s_logger.error("Instantiation excetion when loading resource: " + maid.getDelegate()); - } catch (final IllegalAccessException e) { - s_logger.error("Illegal access exception when loading resource: " + maid.getDelegate()); - } - - return false; - } - return true; - } -} +package com.cloud.cluster; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.cloud.cluster.dao.StackMaidDao; +import com.cloud.cluster.dao.StackMaidDaoImpl; +import com.cloud.serializer.SerializerHelper; +import com.cloud.utils.CleanupDelegate; +import com.cloud.utils.db.Transaction; + +public class StackMaid { + protected final static Logger s_logger = Logger.getLogger(StackMaid.class); + + private static ThreadLocal threadMaid = new ThreadLocal(); + + private static long msid_setby_manager = 0; + + private StackMaidDao maidDao = new StackMaidDaoImpl(); + private int currentSeq = 0; + private Map context = new HashMap(); + + public static void init(long msid) { + msid_setby_manager = msid; + } + + public static StackMaid current() { + StackMaid maid = threadMaid.get(); + if(maid == null) { + maid = new StackMaid(); + threadMaid.set(maid); + } + return maid; + } + + public void registerContext(String key, Object contextObject) { + assert(!context.containsKey(key)) : "Context key has already been registered"; + context.put(key, contextObject); + } + + public Object getContext(String key) { + return context.get(key); + } + + public void expungeMaidItem(long maidId) { + // this is a bit ugly, but when it is not loaded by component locator, this is just a workable way for now + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + maidDao.expunge(maidId); + } finally { + txn.close(); + } + } + + public int push(String delegateClzName, Object context) { + assert(msid_setby_manager != 0) : "Fatal, make sure StackMaidManager is loaded"; + if(msid_setby_manager == 0) + s_logger.error("Fatal, make sure StackMaidManager is loaded"); + + return push(msid_setby_manager, delegateClzName, context); + } + + public int push(long currentMsid, String delegateClzName, Object context) { + int savePoint = currentSeq; + maidDao.pushCleanupDelegate(currentMsid, currentSeq++, delegateClzName, context); + return savePoint; + } + + public void pop(int savePoint) { + assert(msid_setby_manager != 0) : "Fatal, make sure StackMaidManager is loaded"; + if(msid_setby_manager == 0) + s_logger.error("Fatal, make sure StackMaidManager is loaded"); + + pop(msid_setby_manager, savePoint); + } + + public void pop() { + if(currentSeq > 0) + pop(currentSeq -1); + } + + /** + * must be called within thread context + * @param currentMsid + */ + public void pop(long currentMsid, int savePoint) { + while(currentSeq > savePoint) { + maidDao.popCleanupDelegate(currentMsid); + currentSeq--; + } + } + + public void exitCleanup() { + exitCleanup(msid_setby_manager); + } + + public void exitCleanup(long currentMsid) { + if(currentSeq > 0) { + CheckPointVO maid = null; + while((maid = maidDao.popCleanupDelegate(currentMsid)) != null) { + doCleanup(maid); + } + currentSeq = 0; + } + + context.clear(); + } + + public static boolean doCleanup(CheckPointVO maid) { + if(maid.getDelegate() != null) { + try { + Class clz = Class.forName(maid.getDelegate()); + Object delegate = clz.newInstance(); + if(delegate instanceof CleanupDelegate) { + return ((CleanupDelegate)delegate).cleanup(SerializerHelper.fromSerializedString(maid.getContext()), maid); + } else { + assert(false); + } + } catch (final ClassNotFoundException e) { + s_logger.error("Unable to load StackMaid delegate class: " + maid.getDelegate(), e); + } catch (final SecurityException e) { + s_logger.error("Security excetion when loading resource: " + maid.getDelegate()); + } catch (final IllegalArgumentException e) { + s_logger.error("Illegal argument excetion when loading resource: " + maid.getDelegate()); + } catch (final InstantiationException e) { + s_logger.error("Instantiation excetion when loading resource: " + maid.getDelegate()); + } catch (final IllegalAccessException e) { + s_logger.error("Illegal access exception when loading resource: " + maid.getDelegate()); + } + + return false; + } + return true; + } +} diff --git a/server/src/com/cloud/cluster/dao/ManagementServerHostDao.java b/server/src/com/cloud/cluster/dao/ManagementServerHostDao.java index d83dd5d6de6..472628c561b 100644 --- a/server/src/com/cloud/cluster/dao/ManagementServerHostDao.java +++ b/server/src/com/cloud/cluster/dao/ManagementServerHostDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster.dao; - +package com.cloud.cluster.dao; + import java.util.Date; import java.util.List; @@ -20,17 +20,17 @@ import com.cloud.cluster.ManagementServerHost.State; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; - -public interface ManagementServerHostDao extends GenericDao { + +public interface ManagementServerHostDao extends GenericDao { @Override boolean remove(Long id); - ManagementServerHostVO findByMsid(long msid); + ManagementServerHostVO findByMsid(long msid); int increaseAlertCount(long id); - void update(long id, long runid, String name, String version, String serviceIP, int servicePort, Date lastUpdate); - void update(long id, long runid, Date lastUpdate); - List getActiveList(Date cutTime); + void update(long id, long runid, String name, String version, String serviceIP, int servicePort, Date lastUpdate); + void update(long id, long runid, Date lastUpdate); + List getActiveList(Date cutTime); List getInactiveList(Date cutTime); void invalidateRunSession(long id, long runid); @@ -41,4 +41,4 @@ public interface ManagementServerHostDao extends GenericDao listOrphanMsids(); ManagementServerHostVO findOneInUpState(Filter filter); -} +} diff --git a/server/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java b/server/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java index f2cf64e7066..f2cae06dca2 100644 --- a/server/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java +++ b/server/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster.dao; - +package com.cloud.cluster.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -36,12 +36,12 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={ManagementServerHostDao.class}) -public class ManagementServerHostDaoImpl extends GenericDaoBase implements ManagementServerHostDao { - private static final Logger s_logger = Logger.getLogger(ManagementServerHostDaoImpl.class); - - private final SearchBuilder MsIdSearch; + +@Local(value={ManagementServerHostDao.class}) +public class ManagementServerHostDaoImpl extends GenericDaoBase implements ManagementServerHostDao { + private static final Logger s_logger = Logger.getLogger(ManagementServerHostDaoImpl.class); + + private final SearchBuilder MsIdSearch; private final SearchBuilder ActiveSearch; private final SearchBuilder InactiveSearch; private final SearchBuilder StateSearch; @@ -76,27 +76,27 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase getActiveList(Date cutTime) { - SearchCriteria sc = ActiveSearch.create(); - sc.setParameters("lastUpdateTime", cutTime); - - return listIncludingRemovedBy(sc); + SearchCriteria sc = ActiveSearch.create(); + sc.setParameters("lastUpdateTime", cutTime); + + return listIncludingRemovedBy(sc); } @Override @@ -161,30 +161,30 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase { - public long pushCleanupDelegate(long msid, int seq, String delegateClzName, Object context); - public CheckPointVO popCleanupDelegate(long msid); - public void clearStack(long msid); - - public List listLeftoversByMsid(long msid); - public List listLeftoversByCutTime(Date cutTime); - - /** - * Take over the task items of another management server and clean them up. - * - * @param takeOverMsid management server id to take over. - * @param selfId the management server id of this node. - * @return list of tasks to take over. - */ - boolean takeover(long takeOverMsid, long selfId); - +package com.cloud.cluster.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.cluster.CheckPointVO; +import com.cloud.utils.db.GenericDao; + +public interface StackMaidDao extends GenericDao { + public long pushCleanupDelegate(long msid, int seq, String delegateClzName, Object context); + public CheckPointVO popCleanupDelegate(long msid); + public void clearStack(long msid); + + public List listLeftoversByMsid(long msid); + public List listLeftoversByCutTime(Date cutTime); + + /** + * Take over the task items of another management server and clean them up. + * + * @param takeOverMsid management server id to take over. + * @param selfId the management server id of this node. + * @return list of tasks to take over. + */ + boolean takeover(long takeOverMsid, long selfId); + List listCleanupTasks(long selfId); - List listLeftoversByCutTime(Date cutTime, long msid); -} + List listLeftoversByCutTime(Date cutTime, long msid); +} diff --git a/server/src/com/cloud/cluster/dao/StackMaidDaoImpl.java b/server/src/com/cloud/cluster/dao/StackMaidDaoImpl.java index 762b9ba36c6..8055f9eb93b 100644 --- a/server/src/com/cloud/cluster/dao/StackMaidDaoImpl.java +++ b/server/src/com/cloud/cluster/dao/StackMaidDaoImpl.java @@ -10,164 +10,164 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.cluster.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.cluster.CheckPointVO; -import com.cloud.serializer.SerializerHelper; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericDaoBase; -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; - -@Local(value = { StackMaidDao.class }) @DB(txn=false) -public class StackMaidDaoImpl extends GenericDaoBase implements StackMaidDao { - private static final Logger s_logger = Logger.getLogger(StackMaidDaoImpl.class); - - private SearchBuilder popSearch; - private SearchBuilder clearSearch; - private final SearchBuilder AllFieldsSearch; - - public StackMaidDaoImpl() { - popSearch = createSearchBuilder(); - popSearch.and("msid", popSearch.entity().getMsid(), SearchCriteria.Op.EQ); - popSearch.and("threadId", popSearch.entity().getThreadId(), SearchCriteria.Op.EQ); - - clearSearch = createSearchBuilder(); - clearSearch.and("msid", clearSearch.entity().getMsid(), SearchCriteria.Op.EQ); - - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("msid", AllFieldsSearch.entity().getMsid(), Op.EQ); - AllFieldsSearch.and("thread", AllFieldsSearch.entity().getThreadId(), Op.EQ); - AllFieldsSearch.done(); - } - - @Override - public boolean takeover(long takeOverMsid, long selfId) { - CheckPointVO task = createForUpdate(); - task.setMsid(selfId); - task.setThreadId(0); - - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("msid", takeOverMsid); - return update(task, sc) > 0; - - } - - @Override - public List listCleanupTasks(long msId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("msid", msId); - sc.setParameters("thread", 0); - - return this.search(sc, null); - } - - @Override - public long pushCleanupDelegate(long msid, int seq, String delegateClzName, Object context) { - CheckPointVO delegateItem = new CheckPointVO(); - delegateItem.setMsid(msid); - delegateItem.setThreadId(Thread.currentThread().getId()); - delegateItem.setSeq(seq); - delegateItem.setDelegate(delegateClzName); - delegateItem.setContext(SerializerHelper.toSerializedStringOld(context)); - delegateItem.setCreated(DateUtil.currentGMTTime()); - - super.persist(delegateItem); - return delegateItem.getId(); - } - - @Override - public CheckPointVO popCleanupDelegate(long msid) { - SearchCriteria sc = popSearch.create(); - sc.setParameters("msid", msid); - sc.setParameters("threadId", Thread.currentThread().getId()); - - Filter filter = new Filter(CheckPointVO.class, "seq", false, 0L, (long)1); - List l = listIncludingRemovedBy(sc, filter); - if(l != null && l.size() > 0) { - expunge(l.get(0).getId()); - return l.get(0); - } - - return null; - } - - @Override - public void clearStack(long msid) { - SearchCriteria sc = clearSearch.create(); - sc.setParameters("msid", msid); - - expunge(sc); - } - - @Override - @DB - public List listLeftoversByMsid(long msid) { - List l = new ArrayList(); - String sql = "select * from stack_maid where msid=? order by msid asc, thread_id asc, seq desc"; - - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, msid); - - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - l.add(toEntityBean(rs, false)); - } - } catch (SQLException e) { - s_logger.error("unexcpected exception " + e.getMessage(), e); - } catch (Throwable e) { - s_logger.error("unexcpected exception " + e.getMessage(), e); - } finally { - txn.close(); - } - return l; - } - - @Override - @DB - public List listLeftoversByCutTime(Date cutTime) { - - List l = new ArrayList(); - String sql = "select * from stack_maid where created < ? order by msid asc, thread_id asc, seq desc"; - - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - String gmtCutTime = DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime); - pstmt.setString(1, gmtCutTime); - - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - l.add(toEntityBean(rs, false)); - } - } catch (SQLException e) { - s_logger.error("unexcpected exception " + e.getMessage(), e); - } catch (Throwable e) { - s_logger.error("unexcpected exception " + e.getMessage(), e); - } finally { - txn.close(); - } - return l; +package com.cloud.cluster.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.cluster.CheckPointVO; +import com.cloud.serializer.SerializerHelper; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +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; + +@Local(value = { StackMaidDao.class }) @DB(txn=false) +public class StackMaidDaoImpl extends GenericDaoBase implements StackMaidDao { + private static final Logger s_logger = Logger.getLogger(StackMaidDaoImpl.class); + + private SearchBuilder popSearch; + private SearchBuilder clearSearch; + private final SearchBuilder AllFieldsSearch; + + public StackMaidDaoImpl() { + popSearch = createSearchBuilder(); + popSearch.and("msid", popSearch.entity().getMsid(), SearchCriteria.Op.EQ); + popSearch.and("threadId", popSearch.entity().getThreadId(), SearchCriteria.Op.EQ); + + clearSearch = createSearchBuilder(); + clearSearch.and("msid", clearSearch.entity().getMsid(), SearchCriteria.Op.EQ); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("msid", AllFieldsSearch.entity().getMsid(), Op.EQ); + AllFieldsSearch.and("thread", AllFieldsSearch.entity().getThreadId(), Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public boolean takeover(long takeOverMsid, long selfId) { + CheckPointVO task = createForUpdate(); + task.setMsid(selfId); + task.setThreadId(0); + + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("msid", takeOverMsid); + return update(task, sc) > 0; + + } + + @Override + public List listCleanupTasks(long msId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("msid", msId); + sc.setParameters("thread", 0); + + return this.search(sc, null); + } + + @Override + public long pushCleanupDelegate(long msid, int seq, String delegateClzName, Object context) { + CheckPointVO delegateItem = new CheckPointVO(); + delegateItem.setMsid(msid); + delegateItem.setThreadId(Thread.currentThread().getId()); + delegateItem.setSeq(seq); + delegateItem.setDelegate(delegateClzName); + delegateItem.setContext(SerializerHelper.toSerializedStringOld(context)); + delegateItem.setCreated(DateUtil.currentGMTTime()); + + super.persist(delegateItem); + return delegateItem.getId(); + } + + @Override + public CheckPointVO popCleanupDelegate(long msid) { + SearchCriteria sc = popSearch.create(); + sc.setParameters("msid", msid); + sc.setParameters("threadId", Thread.currentThread().getId()); + + Filter filter = new Filter(CheckPointVO.class, "seq", false, 0L, (long)1); + List l = listIncludingRemovedBy(sc, filter); + if(l != null && l.size() > 0) { + expunge(l.get(0).getId()); + return l.get(0); + } + + return null; + } + + @Override + public void clearStack(long msid) { + SearchCriteria sc = clearSearch.create(); + sc.setParameters("msid", msid); + + expunge(sc); + } + + @Override + @DB + public List listLeftoversByMsid(long msid) { + List l = new ArrayList(); + String sql = "select * from stack_maid where msid=? order by msid asc, thread_id asc, seq desc"; + + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, msid); + + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + l.add(toEntityBean(rs, false)); + } + } catch (SQLException e) { + s_logger.error("unexcpected exception " + e.getMessage(), e); + } catch (Throwable e) { + s_logger.error("unexcpected exception " + e.getMessage(), e); + } finally { + txn.close(); + } + return l; + } + + @Override + @DB + public List listLeftoversByCutTime(Date cutTime) { + + List l = new ArrayList(); + String sql = "select * from stack_maid where created < ? order by msid asc, thread_id asc, seq desc"; + + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + String gmtCutTime = DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime); + pstmt.setString(1, gmtCutTime); + + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + l.add(toEntityBean(rs, false)); + } + } catch (SQLException e) { + s_logger.error("unexcpected exception " + e.getMessage(), e); + } catch (Throwable e) { + s_logger.error("unexcpected exception " + e.getMessage(), e); + } finally { + txn.close(); + } + return l; } @Override @@ -197,6 +197,6 @@ public class StackMaidDaoImpl extends GenericDaoBase impleme txn.close(); } return l; - } -} - + } +} + diff --git a/server/src/com/cloud/configuration/dao/ConfigurationDao.java b/server/src/com/cloud/configuration/dao/ConfigurationDao.java index 8cf63408ad9..6c376cbf999 100644 --- a/server/src/com/cloud/configuration/dao/ConfigurationDao.java +++ b/server/src/com/cloud/configuration/dao/ConfigurationDao.java @@ -10,53 +10,53 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.configuration.dao; - +package com.cloud.configuration.dao; + import java.util.Map; import com.cloud.configuration.ConfigurationVO; import com.cloud.utils.db.GenericDao; - -public interface ConfigurationDao extends GenericDao { - - /** - * - * 1. params passed in. - * 2. configuration for the instance. - * 3. configuration for the DEFAULT instance. - * - * @param params parameters from the components.xml which will override the database values. - * @return a consolidated look at the configuration parameters. - */ + +public interface ConfigurationDao extends GenericDao { + + /** + * + * 1. params passed in. + * 2. configuration for the instance. + * 3. configuration for the DEFAULT instance. + * + * @param params parameters from the components.xml which will override the database values. + * @return a consolidated look at the configuration parameters. + */ public Map getConfiguration(String instance, Map params); public Map getConfiguration(Map params); - public Map getConfiguration(); - - /** - * Updates a configuration value - * @param value the new value - * @return true if success, false if failure - */ - public boolean update(String name, String value); - - /** - * Gets the value for the specified configuration name - * @return value - */ + public Map getConfiguration(); + + /** + * Updates a configuration value + * @param value the new value + * @return true if success, false if failure + */ + public boolean update(String name, String value); + + /** + * Gets the value for the specified configuration name + * @return value + */ public String getValue(String name); public String getValueAndInitIfNotExist(String name, String category, String initValue); - + /** * returns whether or not this is a premium configuration * @return true if premium configuration, false otherwise - */ + */ boolean isPremium(); ConfigurationVO findByName(String name); boolean update(String name, String category, String value); -} +} diff --git a/server/src/com/cloud/configuration/dao/ConfigurationDaoImpl.java b/server/src/com/cloud/configuration/dao/ConfigurationDaoImpl.java index a34bfd39229..0aa0f27ec39 100644 --- a/server/src/com/cloud/configuration/dao/ConfigurationDaoImpl.java +++ b/server/src/com/cloud/configuration/dao/ConfigurationDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.configuration.dao; - +package com.cloud.configuration.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; @@ -31,65 +31,65 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={ConfigurationDao.class}) -public class ConfigurationDaoImpl extends GenericDaoBase implements ConfigurationDao { + +@Local(value={ConfigurationDao.class}) +public class ConfigurationDaoImpl extends GenericDaoBase implements ConfigurationDao { private static final Logger s_logger = Logger.getLogger(ConfigurationDaoImpl.class); private Map _configs = null; - private boolean _premium; - - final SearchBuilder InstanceSearch; - final SearchBuilder NameSearch; - - public static final String UPDATE_CONFIGURATION_SQL = "UPDATE configuration SET value = ? WHERE name = ?"; - + private boolean _premium; + + final SearchBuilder InstanceSearch; + final SearchBuilder NameSearch; + + public static final String UPDATE_CONFIGURATION_SQL = "UPDATE configuration SET value = ? WHERE name = ?"; + public ConfigurationDaoImpl () { InstanceSearch = createSearchBuilder(); InstanceSearch.and("instance", InstanceSearch.entity().getInstance(), SearchCriteria.Op.EQ); NameSearch = createSearchBuilder(); NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); - } + } @Override public boolean isPremium() { return _premium; } - - @Override - public Map getConfiguration(String instance, Map params) { - if (_configs == null) { - _configs = new HashMap(); - - SearchCriteria sc = InstanceSearch.create(); - sc.setParameters("instance", "DEFAULT"); - - List configurations = listIncludingRemovedBy(sc); - - for (ConfigurationVO config : configurations) { - if (config.getValue() != null) - _configs.put(config.getName(), config.getValue()); - } + + @Override + public Map getConfiguration(String instance, Map params) { + if (_configs == null) { + _configs = new HashMap(); + + SearchCriteria sc = InstanceSearch.create(); + sc.setParameters("instance", "DEFAULT"); + + List configurations = listIncludingRemovedBy(sc); + + for (ConfigurationVO config : configurations) { + if (config.getValue() != null) + _configs.put(config.getName(), config.getValue()); + } if(!"DEFAULT".equals(instance)){ - //Default instance params are already added, need not add again - sc = InstanceSearch.create(); - sc.setParameters("instance", instance); - - configurations = listIncludingRemovedBy(sc); - - for (ConfigurationVO config : configurations) { - if (config.getValue() != null) - _configs.put(config.getName(), config.getValue()); + //Default instance params are already added, need not add again + sc = InstanceSearch.create(); + sc.setParameters("instance", instance); + + configurations = listIncludingRemovedBy(sc); + + for (ConfigurationVO config : configurations) { + if (config.getValue() != null) + _configs.put(config.getName(), config.getValue()); } - } - - } - - mergeConfigs(_configs, params); - return _configs; - } - + } + + } + + mergeConfigs(_configs, params); + return _configs; + } + @Override public Map getConfiguration(Map params) { return getConfiguration("DEFAULT", params); @@ -100,37 +100,37 @@ public class ConfigurationDaoImpl extends GenericDaoBase()); } - protected void mergeConfigs(Map dbParams, Map xmlParams) { - for (Map.Entry param : xmlParams.entrySet()) { - dbParams.put(param.getKey(), (String)param.getValue()); - } - } + protected void mergeConfigs(Map dbParams, Map xmlParams) { + for (Map.Entry param : xmlParams.entrySet()) { + dbParams.put(param.getKey(), (String)param.getValue()); + } + } - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); Object premium = params.get("premium"); _premium = (premium != null) && ((String) premium).equals("true"); - return true; - } + return true; + } //Use update method with category instead - @Override @Deprecated - public boolean update(String name, String value) { - Transaction txn = Transaction.currentTxn(); - try { - PreparedStatement stmt = txn.prepareStatement(UPDATE_CONFIGURATION_SQL); - stmt.setString(1, value); - stmt.setString(2, name); - stmt.executeUpdate(); - return true; - } catch (Exception e) { - s_logger.warn("Unable to update Configuration Value", e); - } - return false; - } + @Override @Deprecated + public boolean update(String name, String value) { + Transaction txn = Transaction.currentTxn(); + try { + PreparedStatement stmt = txn.prepareStatement(UPDATE_CONFIGURATION_SQL); + stmt.setString(1, value); + stmt.setString(2, name); + stmt.executeUpdate(); + return true; + } catch (Exception e) { + s_logger.warn("Unable to update Configuration Value", e); + } + return false; + } @Override public boolean update(String name, String category, String value) { @@ -147,11 +147,11 @@ public class ConfigurationDaoImpl extends GenericDaoBase candidates, final Map loadInfo, long dataCenterId) { - if(candidates != null) { - - List allocationList = new ArrayList(); - for(ConsoleProxyVO proxy : candidates) { - allocationList.add(proxy); + +@Local(value={ConsoleProxyAllocator.class}) +public class ConsoleProxyBalanceAllocator implements ConsoleProxyAllocator { + + private String _name; + private final Random _rand = new Random(System.currentTimeMillis()); + + @Override + public ConsoleProxyVO allocProxy(List candidates, final Map loadInfo, long dataCenterId) { + if(candidates != null) { + + List allocationList = new ArrayList(); + for(ConsoleProxyVO proxy : candidates) { + allocationList.add(proxy); } Collections.sort(candidates, new Comparator () { @@ -63,40 +63,40 @@ public class ConsoleProxyBalanceAllocator implements ConsoleProxyAllocator { return 1; } } - }); - - if(allocationList.size() > 0) - return allocationList.get(0); - } - return null; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - if (configDao == null) { - throw new ConfigurationException("Unable to get the configuration dao."); - } - - Map configs = configDao.getConfiguration(); - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } -} + }); + + if(allocationList.size() > 0) + return allocationList.get(0); + } + return null; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + if (configDao == null) { + throw new ConfigurationException("Unable to get the configuration dao."); + } + + Map configs = configDao.getConfiguration(); + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } +} diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index 4a4142d8f66..28cc484b491 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc; - +package com.cloud.dc; + import java.util.Date; import java.util.Map; import java.util.UUID; @@ -32,37 +32,37 @@ import com.cloud.network.Network.Provider; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="data_center") -public class DataCenterVO implements DataCenter, Identity { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="name") - private String name = null; - - @Column(name="description") - private String description = null; - - @Column(name="dns1") - private String dns1 = null; - - @Column(name="dns2") - private String dns2 = null; - - @Column(name="internal_dns1") - private String internalDns1 = null; - - @Column(name="internal_dns2") - private String internalDns2 = null; - - @Column(name="router_mac_address", updatable = false, nullable=false) - private String routerMacAddress = "02:00:00:00:00:01"; - + +@Entity +@Table(name="data_center") +public class DataCenterVO implements DataCenter, Identity { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="name") + private String name = null; + + @Column(name="description") + private String description = null; + + @Column(name="dns1") + private String dns1 = null; + + @Column(name="dns2") + private String dns2 = null; + + @Column(name="internal_dns1") + private String internalDns1 = null; + + @Column(name="internal_dns2") + private String internalDns2 = null; + + @Column(name="router_mac_address", updatable = false, nullable=false) + private String routerMacAddress = "02:00:00:00:00:01"; + @Column(name="guest_network_cidr") private String guestNetworkCidr = null; @@ -169,13 +169,13 @@ public class DataCenterVO implements DataCenter, Identity { } public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4,String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { - this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false); + this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false); this.id = id; this.allocationState = Grouping.AllocationState.Enabled; - this.uuid = UUID.randomUUID().toString(); - } - - public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled) { + this.uuid = UUID.randomUUID().toString(); + } + + public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled) { this.name = name; this.description = description; this.dns1 = dns1; @@ -246,72 +246,72 @@ public class DataCenterVO implements DataCenter, Identity { public void setDomainId(Long domainId) { this.domainId = domainId; - } - + } + @Override - public String getDescription() { - return description; - } - - public String getRouterMacAddress() { - return routerMacAddress; - } - + public String getDescription() { + return description; + } + + public String getRouterMacAddress() { + return routerMacAddress; + } + @Override - public String getDns1() { - return dns1; - } - + public String getDns1() { + return dns1; + } + @Override - public String getDns2() { - return dns2; - } - + public String getDns2() { + return dns2; + } + @Override - public String getInternalDns1() { - return internalDns1; - } - + public String getInternalDns1() { + return internalDns1; + } + @Override - public String getInternalDns2() { - return internalDns2; - } - - protected DataCenterVO() { - } - + public String getInternalDns2() { + return internalDns2; + } + + protected DataCenterVO() { + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public void setDns1(String dns1) { - this.dns1 = dns1; - } - - public void setDns2(String dns2) { - this.dns2 = dns2; - } - - public void setInternalDns1(String dns3) { - this.internalDns1 = dns3; - } - - public void setInternalDns2(String dns4) { - this.internalDns2 = dns4; - } - - public void setRouterMacAddress(String routerMacAddress) { - this.routerMacAddress = routerMacAddress; + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + public void setInternalDns1(String dns3) { + this.internalDns1 = dns3; + } + + public void setInternalDns2(String dns4) { + this.internalDns2 = dns4; + } + + public void setRouterMacAddress(String routerMacAddress) { + this.routerMacAddress = routerMacAddress; } @Override @@ -406,4 +406,4 @@ public class DataCenterVO implements DataCenter, Identity { public void setUuid(String uuid) { this.uuid = uuid; } -} +} diff --git a/server/src/com/cloud/dc/HostPodVO.java b/server/src/com/cloud/dc/HostPodVO.java index 529ef9d6f76..ceafdea71c1 100644 --- a/server/src/com/cloud/dc/HostPodVO.java +++ b/server/src/com/cloud/dc/HostPodVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc; - +package com.cloud.dc; + import java.util.Date; import java.util.UUID; @@ -28,101 +28,101 @@ import com.cloud.api.Identity; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name = "host_pod_ref") -public class HostPodVO implements Pod, Identity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - long id; - - @Column(name = "name") - private String name = null; - - @Column(name = "data_center_id") + +@Entity +@Table(name = "host_pod_ref") +public class HostPodVO implements Pod, Identity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + long id; + + @Column(name = "name") + private String name = null; + + @Column(name = "data_center_id") private long dataCenterId; @Column(name = "gateway") - private String gateway; - - @Column(name = "cidr_address") - private String cidrAddress; - - @Column(name = "cidr_size") - private int cidrSize; - - @Column(name = "description") + private String gateway; + + @Column(name = "cidr_address") + private String cidrAddress; + + @Column(name = "cidr_size") + private int cidrSize; + + @Column(name = "description") private String description; @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) - AllocationState allocationState; + AllocationState allocationState; @Column(name = "external_dhcp") private Boolean externalDhcp; @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + @Column(name = "uuid") private String uuid; - - public HostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { - this.name = name; + + public HostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { + this.name = name; this.dataCenterId = dcId; - this.gateway = gateway; - this.cidrAddress = cidrAddress; - this.cidrSize = cidrSize; + this.gateway = gateway; + this.cidrAddress = cidrAddress; + this.cidrSize = cidrSize; this.description = description; this.allocationState = Grouping.AllocationState.Enabled; this.externalDhcp = false; - this.uuid = UUID.randomUUID().toString(); - } - - /* - * public HostPodVO(String name, long dcId) { this(null, name, dcId); } - */ - protected HostPodVO() { this.uuid = UUID.randomUUID().toString(); - } - + } + + /* + * public HostPodVO(String name, long dcId) { this(null, name, dcId); } + */ + protected HostPodVO() { + this.uuid = UUID.randomUUID().toString(); + } + @Override - public long getId() { - return id; - } - - public long getDataCenterId() { - return dataCenterId; - } - - public void setDataCenterId(long dataCenterId) { - this.dataCenterId = dataCenterId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - + public long getId() { + return id; + } + + public long getDataCenterId() { + return dataCenterId; + } + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + @Override - public String getCidrAddress() { - return cidrAddress; - } - - public void setCidrAddress(String cidrAddress) { - this.cidrAddress = cidrAddress; - } - + public String getCidrAddress() { + return cidrAddress; + } + + public void setCidrAddress(String cidrAddress) { + this.cidrAddress = cidrAddress; + } + @Override - public int getCidrSize() { - return cidrSize; - } - - public void setCidrSize(int cidrSize) { - this.cidrSize = cidrSize; + public int getCidrSize() { + return cidrSize; + } + + public void setCidrSize(int cidrSize) { + this.cidrSize = cidrSize; } @Override @@ -132,14 +132,14 @@ public class HostPodVO implements Pod, Identity { public void setGateway(String gateway) { this.gateway = gateway; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; } public AllocationState getAllocationState() { @@ -188,5 +188,5 @@ public class HostPodVO implements Pod, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } -} + } +} diff --git a/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java b/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java index 2372607ff90..ae2021ecf8e 100755 --- a/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java +++ b/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java @@ -10,105 +10,105 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.SecondaryTable; -import javax.persistence.SecondaryTables; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="op_dc_storage_network_ip_address") -@SecondaryTables({@SecondaryTable(name = "dc_storage_network_ip_range", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "range_id", referencedColumnName = "id")})}) -public class StorageNetworkIpAddressVO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - long id; - - @Column(name = "range_id") - long rangeId; - - @Column(name = "ip_address", updatable = false, nullable = false) - String ipAddress; - - @Column(name = "taken") - @Temporal(value = TemporalType.TIMESTAMP) - private Date takenAt; - - @Column(name = "netmask", table = "dc_storage_network_ip_range", insertable = false, updatable = false) - private String netmask; - - @Column(name = "mac_address") - long mac; - - @Column(name = "vlan", table = "dc_storage_network_ip_range", insertable = false, updatable = false) - Integer vlan; - - @Column(name = "gateway", table = "dc_storage_network_ip_range", insertable = false, updatable = false) - String gateway; - - protected StorageNetworkIpAddressVO() { - } - - public Long getId() { - return id; - } - - public void setTakenAt(Date takenDate) { - this.takenAt = takenDate; - } - - public String getIpAddress() { - return ipAddress; - } - - public void setIpAddress(String ip) { - this.ipAddress = ip; - } - - public Date getTakenAt() { - return takenAt; - } - - public long getRangeId() { - return rangeId; - } - - public void setRangeId(long id) { - this.rangeId = id; - } - - public long getMac() { - return mac; - } - - public void setMac(long mac) { - this.mac = mac; - } - - public String getNetmask() { - return netmask; - } - - public void setNetmask(String netmask) { - this.netmask = netmask; - } - - public Integer getVlan() { - return vlan; - } - - public String getGateway() { - return gateway; - } -} +package com.cloud.dc; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.SecondaryTables; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="op_dc_storage_network_ip_address") +@SecondaryTables({@SecondaryTable(name = "dc_storage_network_ip_range", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "range_id", referencedColumnName = "id")})}) +public class StorageNetworkIpAddressVO { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "range_id") + long rangeId; + + @Column(name = "ip_address", updatable = false, nullable = false) + String ipAddress; + + @Column(name = "taken") + @Temporal(value = TemporalType.TIMESTAMP) + private Date takenAt; + + @Column(name = "netmask", table = "dc_storage_network_ip_range", insertable = false, updatable = false) + private String netmask; + + @Column(name = "mac_address") + long mac; + + @Column(name = "vlan", table = "dc_storage_network_ip_range", insertable = false, updatable = false) + Integer vlan; + + @Column(name = "gateway", table = "dc_storage_network_ip_range", insertable = false, updatable = false) + String gateway; + + protected StorageNetworkIpAddressVO() { + } + + public Long getId() { + return id; + } + + public void setTakenAt(Date takenDate) { + this.takenAt = takenDate; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ip) { + this.ipAddress = ip; + } + + public Date getTakenAt() { + return takenAt; + } + + public long getRangeId() { + return rangeId; + } + + public void setRangeId(long id) { + this.rangeId = id; + } + + public long getMac() { + return mac; + } + + public void setMac(long mac) { + this.mac = mac; + } + + public String getNetmask() { + return netmask; + } + + public void setNetmask(String netmask) { + this.netmask = netmask; + } + + public Integer getVlan() { + return vlan; + } + + public String getGateway() { + return gateway; + } +} diff --git a/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java b/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java index 8de0b1e58df..a30ee1d8d21 100755 --- a/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java +++ b/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java @@ -10,169 +10,169 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.SecondaryTable; -import javax.persistence.SecondaryTables; -import javax.persistence.Table; - -@Entity -@Table(name="dc_storage_network_ip_range") -@SecondaryTables({@SecondaryTable(name="networks", pkJoinColumns={@PrimaryKeyJoinColumn(name="network_id", referencedColumnName="id")}), - @SecondaryTable(name="host_pod_ref", pkJoinColumns={@PrimaryKeyJoinColumn(name="pod_id", referencedColumnName="id")}), - @SecondaryTable(name="data_center", pkJoinColumns={@PrimaryKeyJoinColumn(name="data_center_id", referencedColumnName="id")}) -}) -public class StorageNetworkIpRangeVO implements StorageNetworkIpRange { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - String uuid; - - @Column(name = "vlan") - private Integer vlan; - - @Column(name = "data_center_id") - private long dataCenterId; - - @Column(name = "pod_id") - private long podId; - - @Column(name = "start_ip") - private String startIp; - - @Column(name = "end_ip") - private String endIp; - - @Column(name = "gateway") +package com.cloud.dc; + +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.SecondaryTables; +import javax.persistence.Table; + +@Entity +@Table(name="dc_storage_network_ip_range") +@SecondaryTables({@SecondaryTable(name="networks", pkJoinColumns={@PrimaryKeyJoinColumn(name="network_id", referencedColumnName="id")}), + @SecondaryTable(name="host_pod_ref", pkJoinColumns={@PrimaryKeyJoinColumn(name="pod_id", referencedColumnName="id")}), + @SecondaryTable(name="data_center", pkJoinColumns={@PrimaryKeyJoinColumn(name="data_center_id", referencedColumnName="id")}) +}) +public class StorageNetworkIpRangeVO implements StorageNetworkIpRange { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + String uuid; + + @Column(name = "vlan") + private Integer vlan; + + @Column(name = "data_center_id") + private long dataCenterId; + + @Column(name = "pod_id") + private long podId; + + @Column(name = "start_ip") + private String startIp; + + @Column(name = "end_ip") + private String endIp; + + @Column(name = "gateway") private String gateway; - - @Column(name = "network_id") - private long networkId; - - @Column(name="netmask") + + @Column(name = "network_id") + private long networkId; + + @Column(name="netmask") private String netmask; - - @Column(name = "uuid", table = "networks", insertable = false, updatable = false) - String networkUuid; - - @Column(name = "uuid", table = "host_pod_ref", insertable = false, updatable = false) - String podUuid; - - @Column(name = "uuid", table = "data_center", insertable = false, updatable = false) - String zoneUuid; - - public StorageNetworkIpRangeVO(long dcId, long podId, long networkId, String startIp, String endIp, Integer vlan, String netmask, String gateway) { - this(); - this.dataCenterId = dcId; - this.podId = podId; - this.networkId = networkId; - this.startIp = startIp; - this.endIp = endIp; - this.vlan = vlan; + + @Column(name = "uuid", table = "networks", insertable = false, updatable = false) + String networkUuid; + + @Column(name = "uuid", table = "host_pod_ref", insertable = false, updatable = false) + String podUuid; + + @Column(name = "uuid", table = "data_center", insertable = false, updatable = false) + String zoneUuid; + + public StorageNetworkIpRangeVO(long dcId, long podId, long networkId, String startIp, String endIp, Integer vlan, String netmask, String gateway) { + this(); + this.dataCenterId = dcId; + this.podId = podId; + this.networkId = networkId; + this.startIp = startIp; + this.endIp = endIp; + this.vlan = vlan; this.netmask = netmask; - this.gateway = gateway; - } - - protected StorageNetworkIpRangeVO() { - this.uuid = UUID.randomUUID().toString(); - } - - public long getId() { - return id; - } - - public long getDataCenterId() { - return dataCenterId; - } - - public void setDataCenterId(long dcId) { - this.dataCenterId = dcId; - } - - public long getPodId() { - return podId; - } - - public void setPodId(long podId) { - this.podId = podId; - } - - public long getNetworkId() { - return networkId; - } - - public void setNetworkId(long nwId) { - this.networkId = nwId; - } - - public Integer getVlan() { - return vlan; - } - - public void setVlan(int vlan) { - this.vlan = vlan; - } - - public void setStartIp(String start) { - this.startIp = start; - } - - public String getStartIp() { - return startIp; - } - - public void setEndIp(String end) { - this.endIp = end; - } - - public String getEndIp() { - return endIp; - } - - public String getNetmask() { - return netmask; + this.gateway = gateway; } - - public String getGateway() { - return this.gateway; + + protected StorageNetworkIpRangeVO() { + this.uuid = UUID.randomUUID().toString(); } - - public void setGateway(String gateway) { - this.gateway = gateway; - } - - public void setNetmask(String netmask) { - this.netmask = netmask; - } - - @Override - public String getUuid() { - return uuid; - } - - @Override - public String getPodUuid() { - return podUuid; - } - - @Override - public String getNetworkUuid() { - return networkUuid; - } - - @Override - public String getZoneUuid() { - return zoneUuid; - } -} + + public long getId() { + return id; + } + + public long getDataCenterId() { + return dataCenterId; + } + + public void setDataCenterId(long dcId) { + this.dataCenterId = dcId; + } + + public long getPodId() { + return podId; + } + + public void setPodId(long podId) { + this.podId = podId; + } + + public long getNetworkId() { + return networkId; + } + + public void setNetworkId(long nwId) { + this.networkId = nwId; + } + + public Integer getVlan() { + return vlan; + } + + public void setVlan(int vlan) { + this.vlan = vlan; + } + + public void setStartIp(String start) { + this.startIp = start; + } + + public String getStartIp() { + return startIp; + } + + public void setEndIp(String end) { + this.endIp = end; + } + + public String getEndIp() { + return endIp; + } + + public String getNetmask() { + return netmask; + } + + public String getGateway() { + return this.gateway; + } + + public void setGateway(String gateway) { + this.gateway = gateway; + } + + public void setNetmask(String netmask) { + this.netmask = netmask; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public String getPodUuid() { + return podUuid; + } + + @Override + public String getNetworkUuid() { + return networkUuid; + } + + @Override + public String getZoneUuid() { + return zoneUuid; + } +} diff --git a/server/src/com/cloud/dc/dao/HostPodDao.java b/server/src/com/cloud/dc/dao/HostPodDao.java index ff939556010..1217cd22fba 100644 --- a/server/src/com/cloud/dc/dao/HostPodDao.java +++ b/server/src/com/cloud/dc/dao/HostPodDao.java @@ -10,21 +10,21 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc.dao; - +package com.cloud.dc.dao; + import java.util.HashMap; import java.util.List; import com.cloud.dc.HostPodVO; import com.cloud.utils.db.GenericDao; - -public interface HostPodDao extends GenericDao { - public List listByDataCenterId(long id); - - public HostPodVO findByName(String name, long dcId); - + +public interface HostPodDao extends GenericDao { + public List listByDataCenterId(long id); + + public HostPodVO findByName(String name, long dcId); + public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip); public List listDisabledPods(long zoneId); - -} + +} diff --git a/server/src/com/cloud/dc/dao/HostPodDaoImpl.java b/server/src/com/cloud/dc/dao/HostPodDaoImpl.java index eab5c630a0f..e2697dfc779 100644 --- a/server/src/com/cloud/dc/dao/HostPodDaoImpl.java +++ b/server/src/com/cloud/dc/dao/HostPodDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc.dao; - +package com.cloud.dc.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,71 +31,71 @@ 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; - -@Local(value={HostPodDao.class}) -public class HostPodDaoImpl extends GenericDaoBase implements HostPodDao { - private static final Logger s_logger = Logger.getLogger(HostPodDaoImpl.class); - - protected SearchBuilder DataCenterAndNameSearch; + +@Local(value={HostPodDao.class}) +public class HostPodDaoImpl extends GenericDaoBase implements HostPodDao { + private static final Logger s_logger = Logger.getLogger(HostPodDaoImpl.class); + + protected SearchBuilder DataCenterAndNameSearch; protected SearchBuilder DataCenterIdSearch; - - protected HostPodDaoImpl() { - DataCenterAndNameSearch = createSearchBuilder(); - DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ); - DataCenterAndNameSearch.done(); - - DataCenterIdSearch = createSearchBuilder(); - DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + + protected HostPodDaoImpl() { + DataCenterAndNameSearch = createSearchBuilder(); + DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ); + DataCenterAndNameSearch.done(); + + DataCenterIdSearch = createSearchBuilder(); + DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); DataCenterIdSearch.done(); - } - + } + @Override - public List listByDataCenterId(long id) { - SearchCriteria sc = DataCenterIdSearch.create(); - sc.setParameters("dcId", id); - - return listBy(sc); - } - + public List listByDataCenterId(long id) { + SearchCriteria sc = DataCenterIdSearch.create(); + sc.setParameters("dcId", id); + + return listBy(sc); + } + @Override - public HostPodVO findByName(String name, long dcId) { - SearchCriteria sc = DataCenterAndNameSearch.create(); - sc.setParameters("dc", dcId); - sc.setParameters("name", name); - - return findOneBy(sc); - } - - @Override - public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) { - HashMap> currentPodCidrSubnets = new HashMap>(); - - String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL"; - Transaction txn = Transaction.currentTxn(); - try { - PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); - ResultSet rs = stmt.executeQuery(); - while (rs.next()) { - Long podId = rs.getLong("id"); + public HostPodVO findByName(String name, long dcId) { + SearchCriteria sc = DataCenterAndNameSearch.create(); + sc.setParameters("dc", dcId); + sc.setParameters("name", name); + + return findOneBy(sc); + } + + @Override + public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) { + HashMap> currentPodCidrSubnets = new HashMap>(); + + String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL"; + Transaction txn = Transaction.currentTxn(); + try { + PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + Long podId = rs.getLong("id"); if (podId.longValue() == podIdToSkip) { continue; - } - String cidrAddress = rs.getString("cidr_address"); - long cidrSize = rs.getLong("cidr_size"); - List cidrPair = new ArrayList(); - cidrPair.add(0, cidrAddress); - cidrPair.add(1, new Long(cidrSize)); - currentPodCidrSubnets.put(podId, cidrPair); - } - } catch (SQLException ex) { - s_logger.warn("DB exception " + ex.getMessage(), ex); - return null; - } - - return currentPodCidrSubnets; - } - + } + String cidrAddress = rs.getString("cidr_address"); + long cidrSize = rs.getLong("cidr_size"); + List cidrPair = new ArrayList(); + cidrPair.add(0, cidrAddress); + cidrPair.add(1, new Long(cidrSize)); + currentPodCidrSubnets.put(podId, cidrPair); + } + } catch (SQLException ex) { + s_logger.warn("DB exception " + ex.getMessage(), ex); + return null; + } + + return currentPodCidrSubnets; + } + @Override public boolean remove(Long id) { Transaction txn = Transaction.currentTxn(); @@ -125,4 +125,4 @@ public class HostPodDaoImpl extends GenericDaoBase implements H return customSearch(sc, null); } -} +} diff --git a/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDao.java b/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDao.java index f3e29c18325..723d0809831 100755 --- a/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDao.java +++ b/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDao.java @@ -10,19 +10,19 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc.dao; - -import java.util.List; - -import com.cloud.dc.StorageNetworkIpAddressVO; -import com.cloud.utils.db.GenericDao; - -public interface StorageNetworkIpAddressDao extends GenericDao { - long countInUseIpByRangeId(long rangeId); - - List listInUseIpByRangeId(long rangeId); - - StorageNetworkIpAddressVO takeIpAddress(long rangeId); - - void releaseIpAddress(String ip); -} +package com.cloud.dc.dao; + +import java.util.List; + +import com.cloud.dc.StorageNetworkIpAddressVO; +import com.cloud.utils.db.GenericDao; + +public interface StorageNetworkIpAddressDao extends GenericDao { + long countInUseIpByRangeId(long rangeId); + + List listInUseIpByRangeId(long rangeId); + + StorageNetworkIpAddressVO takeIpAddress(long rangeId); + + void releaseIpAddress(String ip); +} diff --git a/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java b/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java index ea0306e30cd..63a216ad81b 100755 --- a/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java +++ b/server/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java @@ -10,98 +10,98 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc.dao; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.dc.DataCenterIpAddressVO; -import com.cloud.dc.StorageNetworkIpAddressVO; -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.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.SearchCriteria.Func; -import com.cloud.utils.db.SearchCriteria.Op; - -@Local(value={StorageNetworkIpAddressDao.class}) -@DB(txn=false) -public class StorageNetworkIpAddressDaoImpl extends GenericDaoBase implements StorageNetworkIpAddressDao { - protected final GenericSearchBuilder countInUserIp; - protected final GenericSearchBuilder listInUseIp; - protected final SearchBuilder untakenIp; - protected final SearchBuilder ipSearch; - - - protected StorageNetworkIpAddressDaoImpl() { - countInUserIp = createSearchBuilder(Long.class); - countInUserIp.select(null, Func.COUNT, null); - countInUserIp.and("rangeId", countInUserIp.entity().getRangeId(), Op.EQ); - countInUserIp.and("taken", countInUserIp.entity().getTakenAt(), Op.NNULL); - countInUserIp.done(); - - listInUseIp = createSearchBuilder(String.class); - listInUseIp.selectField(listInUseIp.entity().getIpAddress()); - listInUseIp.and("rangeId", listInUseIp.entity().getRangeId(), Op.EQ); - listInUseIp.and("taken", listInUseIp.entity().getTakenAt(), Op.NNULL); - listInUseIp.done(); - - untakenIp = createSearchBuilder(); - untakenIp.and("rangeId", untakenIp.entity().getRangeId(), Op.EQ); - untakenIp.and("taken", untakenIp.entity().getTakenAt(), Op.NULL); - untakenIp.done(); - - ipSearch = createSearchBuilder(); - ipSearch.and("ipAddress", ipSearch.entity().getIpAddress(), Op.EQ); - ipSearch.done(); - } - - @Override - public long countInUseIpByRangeId(long rangeId) { - SearchCriteria sc = countInUserIp.create(); - sc.setParameters("rangeId", rangeId); - return customSearch(sc, null).get(0); - } - - @Override - public List listInUseIpByRangeId(long rangeId) { - SearchCriteria sc = listInUseIp.create(); - sc.setParameters("rangeId", rangeId); - return customSearch(sc, null); - } - - @Override - @DB - public StorageNetworkIpAddressVO takeIpAddress(long rangeId) { - SearchCriteria sc = untakenIp.create(); - sc.setParameters("rangeId", rangeId); - Transaction txn = Transaction.currentTxn(); - txn.start(); - StorageNetworkIpAddressVO ip = lockOneRandomRow(sc, true); - if (ip == null) { - txn.rollback(); - return null; - } - ip.setTakenAt(new Date()); - update(ip.getId(), ip); - txn.commit(); - return ip; - } - - @Override - public void releaseIpAddress(String ip) { - SearchCriteria sc = ipSearch.create(); - sc.setParameters("ipAddress", ip); - StorageNetworkIpAddressVO vo = createForUpdate(); - vo.setTakenAt(null); - update(vo, sc); - } -} +package com.cloud.dc.dao; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.dc.DataCenterIpAddressVO; +import com.cloud.dc.StorageNetworkIpAddressVO; +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.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value={StorageNetworkIpAddressDao.class}) +@DB(txn=false) +public class StorageNetworkIpAddressDaoImpl extends GenericDaoBase implements StorageNetworkIpAddressDao { + protected final GenericSearchBuilder countInUserIp; + protected final GenericSearchBuilder listInUseIp; + protected final SearchBuilder untakenIp; + protected final SearchBuilder ipSearch; + + + protected StorageNetworkIpAddressDaoImpl() { + countInUserIp = createSearchBuilder(Long.class); + countInUserIp.select(null, Func.COUNT, null); + countInUserIp.and("rangeId", countInUserIp.entity().getRangeId(), Op.EQ); + countInUserIp.and("taken", countInUserIp.entity().getTakenAt(), Op.NNULL); + countInUserIp.done(); + + listInUseIp = createSearchBuilder(String.class); + listInUseIp.selectField(listInUseIp.entity().getIpAddress()); + listInUseIp.and("rangeId", listInUseIp.entity().getRangeId(), Op.EQ); + listInUseIp.and("taken", listInUseIp.entity().getTakenAt(), Op.NNULL); + listInUseIp.done(); + + untakenIp = createSearchBuilder(); + untakenIp.and("rangeId", untakenIp.entity().getRangeId(), Op.EQ); + untakenIp.and("taken", untakenIp.entity().getTakenAt(), Op.NULL); + untakenIp.done(); + + ipSearch = createSearchBuilder(); + ipSearch.and("ipAddress", ipSearch.entity().getIpAddress(), Op.EQ); + ipSearch.done(); + } + + @Override + public long countInUseIpByRangeId(long rangeId) { + SearchCriteria sc = countInUserIp.create(); + sc.setParameters("rangeId", rangeId); + return customSearch(sc, null).get(0); + } + + @Override + public List listInUseIpByRangeId(long rangeId) { + SearchCriteria sc = listInUseIp.create(); + sc.setParameters("rangeId", rangeId); + return customSearch(sc, null); + } + + @Override + @DB + public StorageNetworkIpAddressVO takeIpAddress(long rangeId) { + SearchCriteria sc = untakenIp.create(); + sc.setParameters("rangeId", rangeId); + Transaction txn = Transaction.currentTxn(); + txn.start(); + StorageNetworkIpAddressVO ip = lockOneRandomRow(sc, true); + if (ip == null) { + txn.rollback(); + return null; + } + ip.setTakenAt(new Date()); + update(ip.getId(), ip); + txn.commit(); + return ip; + } + + @Override + public void releaseIpAddress(String ip) { + SearchCriteria sc = ipSearch.create(); + sc.setParameters("ipAddress", ip); + StorageNetworkIpAddressVO vo = createForUpdate(); + vo.setTakenAt(null); + update(vo, sc); + } +} diff --git a/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDao.java b/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDao.java index f7fc3b16d29..cb94b0875cb 100755 --- a/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDao.java +++ b/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDao.java @@ -10,19 +10,19 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc.dao; - -import java.util.List; - -import com.cloud.dc.StorageNetworkIpRangeVO; -import com.cloud.utils.db.GenericDao; - -public interface StorageNetworkIpRangeDao extends GenericDao { - List listByRangeId(long rangeId); - - List listByPodId(long podId); - - List listByDataCenterId(long dcId); - - long countRanges(); -} +package com.cloud.dc.dao; + +import java.util.List; + +import com.cloud.dc.StorageNetworkIpRangeVO; +import com.cloud.utils.db.GenericDao; + +public interface StorageNetworkIpRangeDao extends GenericDao { + List listByRangeId(long rangeId); + + List listByPodId(long podId); + + List listByDataCenterId(long dcId); + + long countRanges(); +} diff --git a/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java b/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java index abcb36a040a..feb3c8df930 100755 --- a/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java +++ b/server/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java @@ -10,62 +10,62 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.dc.dao; - -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.dc.StorageNetworkIpRangeVO; -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.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.db.SearchCriteria.Func; -import com.cloud.utils.db.SearchCriteria.Op; - -@Local(value={StorageNetworkIpRangeDao.class}) -@DB(txn=false) -public class StorageNetworkIpRangeDaoImpl extends GenericDaoBase implements StorageNetworkIpRangeDao { - protected final GenericSearchBuilder countRanges; - - protected StorageNetworkIpRangeDaoImpl() { - countRanges = createSearchBuilder(Long.class); - countRanges.select(null, Func.COUNT, null); - countRanges.done(); - } - - @Override - public List listByPodId(long podId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); - return sc.list(); - } - - @Override - public List listByRangeId(long rangeId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getId(), Op.EQ, rangeId); - return sc.list(); - } - - @Override - public List listByDataCenterId(long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - return sc.list(); - } - - @Override - public long countRanges() { - SearchCriteria sc = countRanges.create(); - return customSearch(sc, null).get(0); - } - -} +package com.cloud.dc.dao; + +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.dc.StorageNetworkIpRangeVO; +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.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value={StorageNetworkIpRangeDao.class}) +@DB(txn=false) +public class StorageNetworkIpRangeDaoImpl extends GenericDaoBase implements StorageNetworkIpRangeDao { + protected final GenericSearchBuilder countRanges; + + protected StorageNetworkIpRangeDaoImpl() { + countRanges = createSearchBuilder(Long.class); + countRanges.select(null, Func.COUNT, null); + countRanges.done(); + } + + @Override + public List listByPodId(long podId) { + SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); + return sc.list(); + } + + @Override + public List listByRangeId(long rangeId) { + SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + sc.addAnd(sc.getEntity().getId(), Op.EQ, rangeId); + return sc.list(); + } + + @Override + public List listByDataCenterId(long dcId) { + SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + return sc.list(); + } + + @Override + public long countRanges() { + SearchCriteria sc = countRanges.create(); + return customSearch(sc, null).get(0); + } + +} diff --git a/server/src/com/cloud/deploy/UserConcentratedPodPlanner.java b/server/src/com/cloud/deploy/UserConcentratedPodPlanner.java index bebd6fc3a9e..2b28d19cbf2 100644 --- a/server/src/com/cloud/deploy/UserConcentratedPodPlanner.java +++ b/server/src/com/cloud/deploy/UserConcentratedPodPlanner.java @@ -10,142 +10,142 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.deploy; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.utils.Pair; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; - -@Local(value=DeploymentPlanner.class) -public class UserConcentratedPodPlanner extends FirstFitPlanner implements DeploymentPlanner { - - private static final Logger s_logger = Logger.getLogger(UserConcentratedPodPlanner.class); - - /** - * This method should reorder the given list of Cluster Ids by applying any necessary heuristic - * for this planner - * For UserConcentratedPodPlanner we need to order the clusters in a zone across pods, by considering those pods first which have more number of VMs for this account - * This reordering is not done incase the clusters within single pod are passed when the allocation is applied at pod-level. - * @return List ordered list of Cluster Ids - */ - @Override - protected List reorderClusters(long id, boolean isZone, Pair, Map> clusterCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ - List clusterIdsByCapacity = clusterCapacityInfo.first(); - if(vmProfile.getOwner() == null || !isZone){ - return clusterIdsByCapacity; - } - return applyUserConcentrationPodHeuristicToClusters(id, clusterIdsByCapacity, vmProfile.getOwner().getAccountId()); - } - - private List applyUserConcentrationPodHeuristicToClusters(long zoneId, List prioritizedClusterIds, long accountId){ - //user has VMs in certain pods. - prioritize those pods first - //UserConcentratedPod strategy - List clusterList = new ArrayList(); - List podIds = listPodsByUserConcentration(zoneId, accountId); - if(!podIds.isEmpty()){ - clusterList = reorderClustersByPods(prioritizedClusterIds, podIds); - }else{ - clusterList = prioritizedClusterIds; - } - return clusterList; - } - - private List reorderClustersByPods(List clusterIds, List podIds) { - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Reordering cluster list as per pods ordered by user concentration"); - } - - Map> podClusterMap = _clusterDao.getPodClusterIdMap(clusterIds); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("Pod To cluster Map is: "+podClusterMap ); - } - - List reorderedClusters = new ArrayList(); - for (Long pod : podIds){ - if(podClusterMap.containsKey(pod)){ - List clustersOfThisPod = podClusterMap.get(pod); - if(clustersOfThisPod != null){ - for(Long clusterId : clusterIds){ - if(clustersOfThisPod.contains(clusterId)){ - reorderedClusters.add(clusterId); - } - } - clusterIds.removeAll(clustersOfThisPod); - } - } - } - reorderedClusters.addAll(clusterIds); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("Reordered cluster list: " + reorderedClusters); - } - return reorderedClusters; - } - - protected List listPodsByUserConcentration(long zoneId, long accountId){ - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Applying UserConcentratedPod heuristic for account: "+ accountId); - } - - List prioritizedPods = _vmDao.listPodIdsHavingVmsforAccount(zoneId, accountId); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("List of pods to be considered, after applying UserConcentratedPod heuristic: "+ prioritizedPods); - } - - return prioritizedPods; - } - - /** - * This method should reorder the given list of Pod Ids by applying any necessary heuristic - * for this planner - * For UserConcentratedPodPlanner we need to order the pods by considering those pods first which have more number of VMs for this account - * @return List ordered list of Pod Ids - */ - @Override - protected List reorderPods(Pair, Map> podCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ - List podIdsByCapacity = podCapacityInfo.first(); - if(vmProfile.getOwner() == null){ - return podIdsByCapacity; - } - long accountId = vmProfile.getOwner().getAccountId(); - - //user has VMs in certain pods. - prioritize those pods first - //UserConcentratedPod strategy - List podIds = listPodsByUserConcentration(plan.getDataCenterId(), accountId); - if(!podIds.isEmpty()){ - //remove pods that dont have capacity for this vm - podIds.retainAll(podIdsByCapacity); - podIdsByCapacity.removeAll(podIds); - podIds.addAll(podIdsByCapacity); - return podIds; - }else{ - return podIdsByCapacity; - } - - } - - @Override - public boolean canHandle(VirtualMachineProfile vm, DeploymentPlan plan, ExcludeList avoid) { - if(vm.getHypervisorType() != HypervisorType.BareMetal){ - //check the allocation strategy - if (_allocationAlgorithm != null && (_allocationAlgorithm.equals(AllocationAlgorithm.userconcentratedpod_random.toString()) || _allocationAlgorithm.equals(AllocationAlgorithm.userconcentratedpod_firstfit.toString()))){ - return true; - } - } - return false; - } - -} +package com.cloud.deploy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.utils.Pair; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@Local(value=DeploymentPlanner.class) +public class UserConcentratedPodPlanner extends FirstFitPlanner implements DeploymentPlanner { + + private static final Logger s_logger = Logger.getLogger(UserConcentratedPodPlanner.class); + + /** + * This method should reorder the given list of Cluster Ids by applying any necessary heuristic + * for this planner + * For UserConcentratedPodPlanner we need to order the clusters in a zone across pods, by considering those pods first which have more number of VMs for this account + * This reordering is not done incase the clusters within single pod are passed when the allocation is applied at pod-level. + * @return List ordered list of Cluster Ids + */ + @Override + protected List reorderClusters(long id, boolean isZone, Pair, Map> clusterCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ + List clusterIdsByCapacity = clusterCapacityInfo.first(); + if(vmProfile.getOwner() == null || !isZone){ + return clusterIdsByCapacity; + } + return applyUserConcentrationPodHeuristicToClusters(id, clusterIdsByCapacity, vmProfile.getOwner().getAccountId()); + } + + private List applyUserConcentrationPodHeuristicToClusters(long zoneId, List prioritizedClusterIds, long accountId){ + //user has VMs in certain pods. - prioritize those pods first + //UserConcentratedPod strategy + List clusterList = new ArrayList(); + List podIds = listPodsByUserConcentration(zoneId, accountId); + if(!podIds.isEmpty()){ + clusterList = reorderClustersByPods(prioritizedClusterIds, podIds); + }else{ + clusterList = prioritizedClusterIds; + } + return clusterList; + } + + private List reorderClustersByPods(List clusterIds, List podIds) { + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Reordering cluster list as per pods ordered by user concentration"); + } + + Map> podClusterMap = _clusterDao.getPodClusterIdMap(clusterIds); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("Pod To cluster Map is: "+podClusterMap ); + } + + List reorderedClusters = new ArrayList(); + for (Long pod : podIds){ + if(podClusterMap.containsKey(pod)){ + List clustersOfThisPod = podClusterMap.get(pod); + if(clustersOfThisPod != null){ + for(Long clusterId : clusterIds){ + if(clustersOfThisPod.contains(clusterId)){ + reorderedClusters.add(clusterId); + } + } + clusterIds.removeAll(clustersOfThisPod); + } + } + } + reorderedClusters.addAll(clusterIds); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("Reordered cluster list: " + reorderedClusters); + } + return reorderedClusters; + } + + protected List listPodsByUserConcentration(long zoneId, long accountId){ + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Applying UserConcentratedPod heuristic for account: "+ accountId); + } + + List prioritizedPods = _vmDao.listPodIdsHavingVmsforAccount(zoneId, accountId); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("List of pods to be considered, after applying UserConcentratedPod heuristic: "+ prioritizedPods); + } + + return prioritizedPods; + } + + /** + * This method should reorder the given list of Pod Ids by applying any necessary heuristic + * for this planner + * For UserConcentratedPodPlanner we need to order the pods by considering those pods first which have more number of VMs for this account + * @return List ordered list of Pod Ids + */ + @Override + protected List reorderPods(Pair, Map> podCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ + List podIdsByCapacity = podCapacityInfo.first(); + if(vmProfile.getOwner() == null){ + return podIdsByCapacity; + } + long accountId = vmProfile.getOwner().getAccountId(); + + //user has VMs in certain pods. - prioritize those pods first + //UserConcentratedPod strategy + List podIds = listPodsByUserConcentration(plan.getDataCenterId(), accountId); + if(!podIds.isEmpty()){ + //remove pods that dont have capacity for this vm + podIds.retainAll(podIdsByCapacity); + podIdsByCapacity.removeAll(podIds); + podIds.addAll(podIdsByCapacity); + return podIds; + }else{ + return podIdsByCapacity; + } + + } + + @Override + public boolean canHandle(VirtualMachineProfile vm, DeploymentPlan plan, ExcludeList avoid) { + if(vm.getHypervisorType() != HypervisorType.BareMetal){ + //check the allocation strategy + if (_allocationAlgorithm != null && (_allocationAlgorithm.equals(AllocationAlgorithm.userconcentratedpod_random.toString()) || _allocationAlgorithm.equals(AllocationAlgorithm.userconcentratedpod_firstfit.toString()))){ + return true; + } + } + return false; + } + +} diff --git a/server/src/com/cloud/deploy/UserDispersingPlanner.java b/server/src/com/cloud/deploy/UserDispersingPlanner.java index f4f001016f9..dcad1e70aff 100644 --- a/server/src/com/cloud/deploy/UserDispersingPlanner.java +++ b/server/src/com/cloud/deploy/UserDispersingPlanner.java @@ -10,206 +10,206 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.deploy; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.configuration.Config; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; - -@Local(value=DeploymentPlanner.class) -public class UserDispersingPlanner extends FirstFitPlanner implements DeploymentPlanner { - - private static final Logger s_logger = Logger.getLogger(UserDispersingPlanner.class); - - /** - * This method should reorder the given list of Cluster Ids by applying any necessary heuristic - * for this planner - * For UserDispersingPlanner we need to order the clusters by considering the number of VMs for this account - * @return List ordered list of Cluster Ids - */ - @Override - protected List reorderClusters(long id, boolean isZone, Pair, Map> clusterCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ - List clusterIdsByCapacity = clusterCapacityInfo.first(); - if(vmProfile.getOwner() == null){ - return clusterIdsByCapacity; - } - long accountId = vmProfile.getOwner().getAccountId(); - Pair, Map> clusterIdsVmCountInfo = listClustersByUserDispersion(id, isZone, accountId); - - //now we have 2 cluster lists - one ordered by capacity and the other by number of VMs for this account - //need to apply weights to these to find the correct ordering to follow - - if(_userDispersionWeight == 1.0f){ - List clusterIds = clusterIdsVmCountInfo.first(); - clusterIds.retainAll(clusterIdsByCapacity); - return clusterIds; - }else{ - //apply weights to the two lists - return orderByApplyingWeights(clusterCapacityInfo, clusterIdsVmCountInfo, accountId); - } - - - } - - /** - * This method should reorder the given list of Pod Ids by applying any necessary heuristic - * for this planner - * For UserDispersingPlanner we need to order the pods by considering the number of VMs for this account - * @return List ordered list of Pod Ids - */ - @Override - protected List reorderPods(Pair, Map> podCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ - List podIdsByCapacity = podCapacityInfo.first(); - if(vmProfile.getOwner() == null){ - return podIdsByCapacity; - } - long accountId = vmProfile.getOwner().getAccountId(); - - Pair, Map> podIdsVmCountInfo = listPodsByUserDispersion(plan.getDataCenterId(), accountId); - - //now we have 2 pod lists - one ordered by capacity and the other by number of VMs for this account - //need to apply weights to these to find the correct ordering to follow - - if(_userDispersionWeight == 1.0f){ - List podIds = podIdsVmCountInfo.first(); - podIds.retainAll(podIdsByCapacity); - return podIds; - }else{ - //apply weights to the two lists - return orderByApplyingWeights(podCapacityInfo, podIdsVmCountInfo, accountId); - } - - } - - protected Pair, Map> listClustersByUserDispersion(long id, boolean isZone, long accountId){ - if (s_logger.isDebugEnabled()) { - s_logger.debug("Applying Userdispersion heuristic to clusters for account: "+ accountId); - } - Pair, Map> clusterIdsVmCountInfo; - if(isZone){ - clusterIdsVmCountInfo = _vmInstanceDao.listClusterIdsInZoneByVmCount(id, accountId); - }else{ - clusterIdsVmCountInfo = _vmInstanceDao.listClusterIdsInPodByVmCount(id, accountId); - } - if (s_logger.isTraceEnabled()) { - s_logger.trace("List of clusters in ascending order of number of VMs: "+ clusterIdsVmCountInfo.first()); - } - return clusterIdsVmCountInfo; - } - - protected Pair, Map> listPodsByUserDispersion(long dataCenterId, long accountId) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Applying Userdispersion heuristic to pods for account: "+ accountId); - } - Pair, Map> podIdsVmCountInfo = _vmInstanceDao.listPodIdsInZoneByVmCount(dataCenterId, accountId); - if (s_logger.isTraceEnabled()) { - s_logger.trace("List of pods in ascending order of number of VMs: "+ podIdsVmCountInfo.first()); - } - - return podIdsVmCountInfo; - } - - - private List orderByApplyingWeights(Pair, Map> capacityInfo, Pair, Map> vmCountInfo, long accountId){ - List capacityOrderedIds = capacityInfo.first(); - List vmCountOrderedIds = vmCountInfo.first(); - Map capacityMap = capacityInfo.second(); - Map vmCountMap = vmCountInfo.second(); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("Capacity Id list: "+ capacityOrderedIds + " , capacityMap:"+capacityMap); - } - if (s_logger.isTraceEnabled()) { - s_logger.trace("Vm Count Id list: "+ vmCountOrderedIds + " , vmCountMap:"+vmCountMap); - } - - - List idsReorderedByWeights = new ArrayList(); - float capacityWeight = (1.0f -_userDispersionWeight); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Applying userDispersionWeight: "+ _userDispersionWeight); - } - //normalize the vmCountMap - LinkedHashMap normalisedVmCountIdMap= new LinkedHashMap(); - - Long totalVmsOfAccount = _vmInstanceDao.countRunningByAccount(accountId); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Total VMs for account: "+ totalVmsOfAccount); - } - for(Long id : vmCountOrderedIds){ - Double normalisedCount = vmCountMap.get(id) / totalVmsOfAccount; - normalisedVmCountIdMap.put(id, normalisedCount); - } - - //consider only those ids that are in capacity map. - - SortedMap> sortedMap= new TreeMap>(); - for(Long id : capacityOrderedIds){ - Double weightedCapacityValue = capacityMap.get(id) * capacityWeight; - Double weightedVmCountValue = normalisedVmCountIdMap.get(id) * _userDispersionWeight; - Double totalWeight = weightedCapacityValue + weightedVmCountValue; - if(sortedMap.containsKey(totalWeight)){ - List idList = sortedMap.get(totalWeight); - idList.add(id); - sortedMap.put(totalWeight, idList); - }else{ - List idList = new ArrayList(); - idList.add(id); - sortedMap.put(totalWeight, idList); - } - } - - for(List idList : sortedMap.values()){ - idsReorderedByWeights.addAll(idList); - } - - if (s_logger.isTraceEnabled()) { - s_logger.trace("Reordered Id list: "+ idsReorderedByWeights); - } - - return idsReorderedByWeights; - } - - - @Override - public boolean canHandle(VirtualMachineProfile vm, DeploymentPlan plan, ExcludeList avoid) { - if(vm.getHypervisorType() != HypervisorType.BareMetal){ - //check the allocation strategy - if (_allocationAlgorithm != null && _allocationAlgorithm.equals(AllocationAlgorithm.userdispersing.toString())) { - return true; - } - } - return false; - } - - float _userDispersionWeight; - - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - - String weight = _configDao.getValue(Config.VmUserDispersionWeight.key()); - _userDispersionWeight = NumbersUtil.parseFloat(weight, 1.0f); - - - return true; - } - -} +package com.cloud.deploy; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.configuration.Config; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.Pair; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@Local(value=DeploymentPlanner.class) +public class UserDispersingPlanner extends FirstFitPlanner implements DeploymentPlanner { + + private static final Logger s_logger = Logger.getLogger(UserDispersingPlanner.class); + + /** + * This method should reorder the given list of Cluster Ids by applying any necessary heuristic + * for this planner + * For UserDispersingPlanner we need to order the clusters by considering the number of VMs for this account + * @return List ordered list of Cluster Ids + */ + @Override + protected List reorderClusters(long id, boolean isZone, Pair, Map> clusterCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ + List clusterIdsByCapacity = clusterCapacityInfo.first(); + if(vmProfile.getOwner() == null){ + return clusterIdsByCapacity; + } + long accountId = vmProfile.getOwner().getAccountId(); + Pair, Map> clusterIdsVmCountInfo = listClustersByUserDispersion(id, isZone, accountId); + + //now we have 2 cluster lists - one ordered by capacity and the other by number of VMs for this account + //need to apply weights to these to find the correct ordering to follow + + if(_userDispersionWeight == 1.0f){ + List clusterIds = clusterIdsVmCountInfo.first(); + clusterIds.retainAll(clusterIdsByCapacity); + return clusterIds; + }else{ + //apply weights to the two lists + return orderByApplyingWeights(clusterCapacityInfo, clusterIdsVmCountInfo, accountId); + } + + + } + + /** + * This method should reorder the given list of Pod Ids by applying any necessary heuristic + * for this planner + * For UserDispersingPlanner we need to order the pods by considering the number of VMs for this account + * @return List ordered list of Pod Ids + */ + @Override + protected List reorderPods(Pair, Map> podCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan){ + List podIdsByCapacity = podCapacityInfo.first(); + if(vmProfile.getOwner() == null){ + return podIdsByCapacity; + } + long accountId = vmProfile.getOwner().getAccountId(); + + Pair, Map> podIdsVmCountInfo = listPodsByUserDispersion(plan.getDataCenterId(), accountId); + + //now we have 2 pod lists - one ordered by capacity and the other by number of VMs for this account + //need to apply weights to these to find the correct ordering to follow + + if(_userDispersionWeight == 1.0f){ + List podIds = podIdsVmCountInfo.first(); + podIds.retainAll(podIdsByCapacity); + return podIds; + }else{ + //apply weights to the two lists + return orderByApplyingWeights(podCapacityInfo, podIdsVmCountInfo, accountId); + } + + } + + protected Pair, Map> listClustersByUserDispersion(long id, boolean isZone, long accountId){ + if (s_logger.isDebugEnabled()) { + s_logger.debug("Applying Userdispersion heuristic to clusters for account: "+ accountId); + } + Pair, Map> clusterIdsVmCountInfo; + if(isZone){ + clusterIdsVmCountInfo = _vmInstanceDao.listClusterIdsInZoneByVmCount(id, accountId); + }else{ + clusterIdsVmCountInfo = _vmInstanceDao.listClusterIdsInPodByVmCount(id, accountId); + } + if (s_logger.isTraceEnabled()) { + s_logger.trace("List of clusters in ascending order of number of VMs: "+ clusterIdsVmCountInfo.first()); + } + return clusterIdsVmCountInfo; + } + + protected Pair, Map> listPodsByUserDispersion(long dataCenterId, long accountId) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Applying Userdispersion heuristic to pods for account: "+ accountId); + } + Pair, Map> podIdsVmCountInfo = _vmInstanceDao.listPodIdsInZoneByVmCount(dataCenterId, accountId); + if (s_logger.isTraceEnabled()) { + s_logger.trace("List of pods in ascending order of number of VMs: "+ podIdsVmCountInfo.first()); + } + + return podIdsVmCountInfo; + } + + + private List orderByApplyingWeights(Pair, Map> capacityInfo, Pair, Map> vmCountInfo, long accountId){ + List capacityOrderedIds = capacityInfo.first(); + List vmCountOrderedIds = vmCountInfo.first(); + Map capacityMap = capacityInfo.second(); + Map vmCountMap = vmCountInfo.second(); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("Capacity Id list: "+ capacityOrderedIds + " , capacityMap:"+capacityMap); + } + if (s_logger.isTraceEnabled()) { + s_logger.trace("Vm Count Id list: "+ vmCountOrderedIds + " , vmCountMap:"+vmCountMap); + } + + + List idsReorderedByWeights = new ArrayList(); + float capacityWeight = (1.0f -_userDispersionWeight); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Applying userDispersionWeight: "+ _userDispersionWeight); + } + //normalize the vmCountMap + LinkedHashMap normalisedVmCountIdMap= new LinkedHashMap(); + + Long totalVmsOfAccount = _vmInstanceDao.countRunningByAccount(accountId); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Total VMs for account: "+ totalVmsOfAccount); + } + for(Long id : vmCountOrderedIds){ + Double normalisedCount = vmCountMap.get(id) / totalVmsOfAccount; + normalisedVmCountIdMap.put(id, normalisedCount); + } + + //consider only those ids that are in capacity map. + + SortedMap> sortedMap= new TreeMap>(); + for(Long id : capacityOrderedIds){ + Double weightedCapacityValue = capacityMap.get(id) * capacityWeight; + Double weightedVmCountValue = normalisedVmCountIdMap.get(id) * _userDispersionWeight; + Double totalWeight = weightedCapacityValue + weightedVmCountValue; + if(sortedMap.containsKey(totalWeight)){ + List idList = sortedMap.get(totalWeight); + idList.add(id); + sortedMap.put(totalWeight, idList); + }else{ + List idList = new ArrayList(); + idList.add(id); + sortedMap.put(totalWeight, idList); + } + } + + for(List idList : sortedMap.values()){ + idsReorderedByWeights.addAll(idList); + } + + if (s_logger.isTraceEnabled()) { + s_logger.trace("Reordered Id list: "+ idsReorderedByWeights); + } + + return idsReorderedByWeights; + } + + + @Override + public boolean canHandle(VirtualMachineProfile vm, DeploymentPlan plan, ExcludeList avoid) { + if(vm.getHypervisorType() != HypervisorType.BareMetal){ + //check the allocation strategy + if (_allocationAlgorithm != null && _allocationAlgorithm.equals(AllocationAlgorithm.userdispersing.toString())) { + return true; + } + } + return false; + } + + float _userDispersionWeight; + + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + + String weight = _configDao.getValue(Config.VmUserDispersionWeight.key()); + _userDispersionWeight = NumbersUtil.parseFloat(weight, 1.0f); + + + return true; + } + +} diff --git a/server/src/com/cloud/domain/DomainVO.java b/server/src/com/cloud/domain/DomainVO.java index f48b86138fe..53ed0753244 100644 --- a/server/src/com/cloud/domain/DomainVO.java +++ b/server/src/com/cloud/domain/DomainVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.domain; - +package com.cloud.domain; + import java.util.Date; import java.util.UUID; @@ -26,42 +26,42 @@ import org.apache.log4j.Logger; import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="domain") + +@Entity +@Table(name="domain") public class DomainVO implements Domain, Identity { public static final Logger s_logger = Logger.getLogger(DomainVO.class.getName()); - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="parent") - private Long parent = null; - - @Column(name="name") - private String name = null; - - @Column(name="owner") - private long accountId; - - @Column(name="path") - private String path = null; - - @Column(name="level") - private int level; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - @Column(name="child_count") - private int childCount = 0; - - @Column(name="next_child_seq") + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="parent") + private Long parent = null; + + @Column(name="name") + private String name = null; + + @Column(name="owner") + private long accountId; + + @Column(name="path") + private String path = null; + + @Column(name="level") + private int level; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="child_count") + private int childCount = 0; + + @Column(name="next_child_seq") private long nextChildSeq = 1L; - @Column(name="state") + @Column(name="state") private Domain.State state; @Column(name="network_domain") @@ -69,103 +69,103 @@ public class DomainVO implements Domain, Identity { @Column(name="uuid") private String uuid; - + 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) { - this.parent = parentId; - this.name = name; - this.accountId = owner; - this.path =""; + } + + public DomainVO(String name, long owner, Long parentId, String networkDomain) { + 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.randomUUID().toString(); - } - + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public Long getParent() { - return parent; - } - + public Long getParent() { + return parent; + } + @Override - public void setParent(Long parent) { - if(parent == null) { - this.parent = DomainVO.ROOT_DOMAIN; - } else { - if(parent.longValue() <= DomainVO.ROOT_DOMAIN) - this.parent = DomainVO.ROOT_DOMAIN; - else - this.parent = parent; - } - } - + public void setParent(Long parent) { + if(parent == null) { + this.parent = DomainVO.ROOT_DOMAIN; + } else { + if(parent.longValue() <= DomainVO.ROOT_DOMAIN) + this.parent = DomainVO.ROOT_DOMAIN; + else + this.parent = parent; + } + } + @Override - public String getName() { - return name; - } - + public String getName() { + return name; + } + @Override - public void setName(String name) { - this.name = name; - } - + public void setName(String name) { + this.name = name; + } + @Override - public long getAccountId() { - return accountId; - } - + public long getAccountId() { + return accountId; + } + @Override - public Date getRemoved() { - return removed; - } - + public Date getRemoved() { + return removed; + } + @Override - public String getPath() { - return path; - } - + public String getPath() { + return path; + } + @Override - public void setPath(String path) { - this.path = path; - } - + public void setPath(String path) { + this.path = path; + } + @Override - public int getLevel() { - return level; - } - - public void setLevel(int level) { - this.level = level; - } - + public int getLevel() { + return level; + } + + public void setLevel(int level) { + this.level = level; + } + @Override - public int getChildCount() { - return childCount; - } - - public void setChildCount(int count) { - childCount = count; - } - + public int getChildCount() { + return childCount; + } + + public void setChildCount(int count) { + childCount = count; + } + @Override - public long getNextChildSeq() { - return nextChildSeq; - } - - public void setNextChildSeq(long seq) { - nextChildSeq = seq; + public long getNextChildSeq() { + return nextChildSeq; + } + + public void setNextChildSeq(long seq) { + nextChildSeq = seq; } @Override @@ -199,6 +199,6 @@ public class DomainVO implements Domain, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } -} - + } +} + diff --git a/server/src/com/cloud/domain/dao/DomainDao.java b/server/src/com/cloud/domain/dao/DomainDao.java index 54ecc95bfb3..af752909edf 100644 --- a/server/src/com/cloud/domain/dao/DomainDao.java +++ b/server/src/com/cloud/domain/dao/DomainDao.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.domain.dao; - +package com.cloud.domain.dao; + import java.util.List; import java.util.Set; import com.cloud.domain.DomainVO; import com.cloud.utils.db.GenericDao; - -public interface DomainDao extends GenericDao { + +public interface DomainDao extends GenericDao { public DomainVO create(DomainVO domain); public DomainVO findDomainByPath(String domainPath); public boolean isChildDomain(Long parentId, Long childId); @@ -26,5 +26,5 @@ public interface DomainDao extends GenericDao { List findImmediateChildrenForParent(Long parentId); List findAllChildren(String path, Long parentId); List findInactiveDomains(); - Set getDomainParentIds(long domainId); -} + Set getDomainParentIds(long domainId); +} diff --git a/server/src/com/cloud/domain/dao/DomainDaoImpl.java b/server/src/com/cloud/domain/dao/DomainDaoImpl.java index 4dd0391fed5..c5709693b0f 100644 --- a/server/src/com/cloud/domain/dao/DomainDaoImpl.java +++ b/server/src/com/cloud/domain/dao/DomainDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.domain.dao; - +package com.cloud.domain.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,30 +31,30 @@ import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value={DomainDao.class}) -public class DomainDaoImpl extends GenericDaoBase implements DomainDao { + +@Local(value={DomainDao.class}) +public class DomainDaoImpl extends GenericDaoBase implements DomainDao { private static final Logger s_logger = Logger.getLogger(DomainDaoImpl.class); - protected SearchBuilder DomainNameLikeSearch; - protected SearchBuilder ParentDomainNameLikeSearch; + protected SearchBuilder DomainNameLikeSearch; + protected SearchBuilder ParentDomainNameLikeSearch; protected SearchBuilder DomainPairSearch; - protected SearchBuilder ImmediateChildDomainSearch; + protected SearchBuilder ImmediateChildDomainSearch; protected SearchBuilder FindAllChildrenSearch; protected SearchBuilder AllFieldsSearch; - - public DomainDaoImpl () { - DomainNameLikeSearch = createSearchBuilder(); - DomainNameLikeSearch.and("name", DomainNameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE); - DomainNameLikeSearch.done(); - - ParentDomainNameLikeSearch = createSearchBuilder(); - ParentDomainNameLikeSearch.and("name", ParentDomainNameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE); - ParentDomainNameLikeSearch.and("parent", ParentDomainNameLikeSearch.entity().getName(), SearchCriteria.Op.EQ); - ParentDomainNameLikeSearch.done(); - - DomainPairSearch = createSearchBuilder(); - DomainPairSearch.and("id", DomainPairSearch.entity().getId(), SearchCriteria.Op.IN); + + public DomainDaoImpl () { + DomainNameLikeSearch = createSearchBuilder(); + DomainNameLikeSearch.and("name", DomainNameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE); + DomainNameLikeSearch.done(); + + ParentDomainNameLikeSearch = createSearchBuilder(); + ParentDomainNameLikeSearch.and("name", ParentDomainNameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE); + ParentDomainNameLikeSearch.and("parent", ParentDomainNameLikeSearch.entity().getName(), SearchCriteria.Op.EQ); + ParentDomainNameLikeSearch.done(); + + DomainPairSearch = createSearchBuilder(); + DomainPairSearch.and("id", DomainPairSearch.entity().getId(), SearchCriteria.Op.IN); DomainPairSearch.done(); ImmediateChildDomainSearch = createSearchBuilder(); @@ -74,15 +74,15 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom AllFieldsSearch.and("parent", AllFieldsSearch.entity().getParent(), SearchCriteria.Op.EQ); AllFieldsSearch.done(); - } - - + } + + private static String allocPath(DomainVO parentDomain, String name) { String parentPath = parentDomain.getPath(); - return parentPath + name + "/"; - } - - @Override + return parentPath + name + "/"; + } + + @Override public synchronized DomainVO create(DomainVO domain) { // make sure domain name is valid String domainName = domain.getName(); @@ -94,19 +94,19 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom throw new IllegalArgumentException("Domain name is null. Please specify a valid domain name."); } - long parent = DomainVO.ROOT_DOMAIN; - if(domain.getParent() != null && domain.getParent().longValue() >= DomainVO.ROOT_DOMAIN) { - parent = domain.getParent().longValue(); - } - - DomainVO parentDomain = findById(parent); - if(parentDomain == null) { - s_logger.error("Unable to load parent domain: " + parent); - return null; - } - - Transaction txn = Transaction.currentTxn(); - try { + long parent = DomainVO.ROOT_DOMAIN; + if(domain.getParent() != null && domain.getParent().longValue() >= DomainVO.ROOT_DOMAIN) { + parent = domain.getParent().longValue(); + } + + DomainVO parentDomain = findById(parent); + if(parentDomain == null) { + s_logger.error("Unable to load parent domain: " + parent); + return null; + } + + Transaction txn = Transaction.currentTxn(); + try { txn.start(); parentDomain = this.lockRow(parent, true); @@ -114,49 +114,49 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom s_logger.error("Unable to lock parent domain: " + parent); return null; } - - domain.setPath(allocPath(parentDomain, domain.getName())); - domain.setLevel(parentDomain.getLevel() + 1); - - parentDomain.setNextChildSeq(parentDomain.getNextChildSeq() + 1); // FIXME: remove sequence number? - parentDomain.setChildCount(parentDomain.getChildCount() + 1); - persist(domain); - update(parentDomain.getId(), parentDomain); - - txn.commit(); - return domain; - } catch(Exception e) { - s_logger.error("Unable to create domain due to " + e.getMessage(), e); - txn.rollback(); - return null; + + domain.setPath(allocPath(parentDomain, domain.getName())); + domain.setLevel(parentDomain.getLevel() + 1); + + parentDomain.setNextChildSeq(parentDomain.getNextChildSeq() + 1); // FIXME: remove sequence number? + parentDomain.setChildCount(parentDomain.getChildCount() + 1); + persist(domain); + update(parentDomain.getId(), parentDomain); + + txn.commit(); + return domain; + } catch(Exception e) { + s_logger.error("Unable to create domain due to " + e.getMessage(), e); + txn.rollback(); + return null; } - } - - @Override - @DB - public boolean remove(Long id) { - // check for any active users / domains assigned to the given domain id and don't remove the domain if there are any - if (id != null && id.longValue() == DomainVO.ROOT_DOMAIN) { - s_logger.error("Can not remove domain " + id + " as it is ROOT domain"); - return false; - } - - DomainVO domain = findById(id); - if(domain == null) { - s_logger.error("Unable to remove domain as domain " + id + " no longer exists"); - return false; - } - - if(domain.getParent() == null) { - s_logger.error("Invalid domain " + id + ", orphan?"); - return false; - } - - String sql = "SELECT * from account where domain_id = " + id + " and removed is null"; - String sql1 = "SELECT * from domain where parent = " + id + " and removed is null"; + } - boolean success = false; - Transaction txn = Transaction.currentTxn(); + @Override + @DB + public boolean remove(Long id) { + // check for any active users / domains assigned to the given domain id and don't remove the domain if there are any + if (id != null && id.longValue() == DomainVO.ROOT_DOMAIN) { + s_logger.error("Can not remove domain " + id + " as it is ROOT domain"); + return false; + } + + DomainVO domain = findById(id); + if(domain == null) { + s_logger.error("Unable to remove domain as domain " + id + " no longer exists"); + return false; + } + + if(domain.getParent() == null) { + s_logger.error("Invalid domain " + id + ", orphan?"); + return false; + } + + String sql = "SELECT * from account where domain_id = " + id + " and removed is null"; + String sql1 = "SELECT * from domain where parent = " + id + " and removed is null"; + + boolean success = false; + Transaction txn = Transaction.currentTxn(); try { txn.start(); DomainVO parentDomain = super.lockRow(domain.getParent(), true); @@ -165,29 +165,29 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom return false; } - PreparedStatement stmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = stmt.executeQuery(); - if (rs.next()) { - return false; - } - stmt = txn.prepareAutoCloseStatement(sql1); - rs = stmt.executeQuery(); - if (rs.next()) { - return false; - } - - parentDomain.setChildCount(parentDomain.getChildCount() - 1); - update(parentDomain.getId(), parentDomain); - success = super.remove(id); - txn.commit(); + PreparedStatement stmt = txn.prepareAutoCloseStatement(sql); + ResultSet rs = stmt.executeQuery(); + if (rs.next()) { + return false; + } + stmt = txn.prepareAutoCloseStatement(sql1); + rs = stmt.executeQuery(); + if (rs.next()) { + return false; + } + + parentDomain.setChildCount(parentDomain.getChildCount() - 1); + update(parentDomain.getId(), parentDomain); + success = super.remove(id); + txn.commit(); } catch (SQLException ex) { - success = false; - s_logger.error("error removing domain: " + id, ex); - txn.rollback(); - } - return success; - } - + success = false; + s_logger.error("error removing domain: " + id, ex); + txn.rollback(); + } + return success; + } + @Override public DomainVO findDomainByPath(String domainPath) { SearchCriteria sc = createSearchCriteria(); @@ -217,33 +217,33 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom return listBy(sc); } - @Override - public boolean isChildDomain(Long parentId, Long childId) { - if ((parentId == null) || (childId == null)) { - return false; - } - - if (parentId.equals(childId)) { - return true; - } - - boolean result = false; - SearchCriteria sc = DomainPairSearch.create(); - sc.setParameters("id", parentId, childId); - - List domainPair = listBy(sc); - - if ((domainPair != null) && (domainPair.size() == 2)) { - DomainVO d1 = domainPair.get(0); - DomainVO d2 = domainPair.get(1); - - if (d1.getId() == parentId) { - result = d2.getPath().startsWith(d1.getPath()); - } else { - result = d1.getPath().startsWith(d2.getPath()); - } - } - return result; + @Override + public boolean isChildDomain(Long parentId, Long childId) { + if ((parentId == null) || (childId == null)) { + return false; + } + + if (parentId.equals(childId)) { + return true; + } + + boolean result = false; + SearchCriteria sc = DomainPairSearch.create(); + sc.setParameters("id", parentId, childId); + + List domainPair = listBy(sc); + + if ((domainPair != null) && (domainPair.size() == 2)) { + DomainVO d1 = domainPair.get(0); + DomainVO d2 = domainPair.get(1); + + if (d1.getId() == parentId) { + result = d2.getPath().startsWith(d1.getPath()); + } else { + result = d1.getPath().startsWith(d2.getPath()); + } + } + return result; } @Override @@ -265,5 +265,5 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom } return parentDomains; - } -} + } +} diff --git a/server/src/com/cloud/ha/AbstractInvestigatorImpl.java b/server/src/com/cloud/ha/AbstractInvestigatorImpl.java index 448e9faf1d4..959dd4211cc 100755 --- a/server/src/com/cloud/ha/AbstractInvestigatorImpl.java +++ b/server/src/com/cloud/ha/AbstractInvestigatorImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.ha; - +package com.cloud.ha; + import java.util.ArrayList; import java.util.List; @@ -36,39 +36,39 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteriaService; - -public abstract class AbstractInvestigatorImpl implements Investigator { - private static final Logger s_logger = Logger.getLogger(AbstractInvestigatorImpl.class); - - private String _name = null; - @Inject private HostDao _hostDao = null; + +public abstract class AbstractInvestigatorImpl implements Investigator { + private static final Logger s_logger = Logger.getLogger(AbstractInvestigatorImpl.class); + + private String _name = null; + @Inject private HostDao _hostDao = null; @Inject private AgentManager _agentMgr = null; @Inject private ResourceManager _resourceMgr = null; - - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; + + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + return true; } - - // Host.status is up and Host.type is routing + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + // Host.status is up and Host.type is routing protected List findHostByPod(long podId, Long excludeHostId) { SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Type.Routing); @@ -86,34 +86,34 @@ public abstract class AbstractInvestigatorImpl implements Investigator { } return hostIds; - } - - protected Status testIpAddress(Long hostId, String testHostIp) { - try { - Answer pingTestAnswer = _agentMgr.send(hostId, new PingTestCommand(testHostIp)); - if(pingTestAnswer == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("host (" + testHostIp + ") returns null answer"); - } - return null; - } - - if (pingTestAnswer.getResult()) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("host (" + testHostIp + ") has been successfully pinged, returning that host is up"); - } - // computing host is available, but could not reach agent, return false - return Status.Up; - } else { + } + + protected Status testIpAddress(Long hostId, String testHostIp) { + try { + Answer pingTestAnswer = _agentMgr.send(hostId, new PingTestCommand(testHostIp)); + if(pingTestAnswer == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("host (" + testHostIp + ") returns null answer"); + } + return null; + } + + if (pingTestAnswer.getResult()) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("host (" + testHostIp + ") has been successfully pinged, returning that host is up"); + } + // computing host is available, but could not reach agent, return false + return Status.Up; + } else { if (s_logger.isDebugEnabled()) { s_logger.debug("host (" + testHostIp + ") cannot be pinged, returning null ('I don't know')"); } - return null; - } - } catch (AgentUnavailableException e) { - return null; - } catch (OperationTimedoutException e) { - return null; - } - } -} + return null; + } + } catch (AgentUnavailableException e) { + return null; + } catch (OperationTimedoutException e) { + return null; + } + } +} diff --git a/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java b/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java index 288e5cfc6b1..1404787c715 100644 --- a/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java +++ b/server/src/com/cloud/ha/ManagementIPSystemVMInvestigator.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.ha; - +package com.cloud.ha; + import java.util.List; import java.util.Map; @@ -29,17 +29,17 @@ import com.cloud.utils.component.Inject; import com.cloud.vm.Nic; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; - -@Local(value={Investigator.class}) -public class ManagementIPSystemVMInvestigator extends AbstractInvestigatorImpl { - private static final Logger s_logger = Logger.getLogger(ManagementIPSystemVMInvestigator.class); - - private String _name = null; - @Inject private HostDao _hostDao = null; + +@Local(value={Investigator.class}) +public class ManagementIPSystemVMInvestigator extends AbstractInvestigatorImpl { + private static final Logger s_logger = Logger.getLogger(ManagementIPSystemVMInvestigator.class); + + private String _name = null; + @Inject private HostDao _hostDao = null; @Inject private NetworkManager _networkMgr = null; - - - @Override + + + @Override public Boolean isVmAlive(VMInstanceVO vm, HostVO host) { if (!VirtualMachine.Type.isSystemVM(vm.getType())) { s_logger.debug("Not a System Vm, unable to determine state of " + vm + " returning null"); @@ -78,10 +78,10 @@ public class ManagementIPSystemVMInvestigator extends AbstractInvestigatorImpl { Status vmState = testIpAddress(otherHost, nic.getIp4Address()); if (vmState == null) { // can't get information from that host, try the next one - continue; - } - if (vmState == Status.Up) { - if (s_logger.isDebugEnabled()) { + continue; + } + if (vmState == Status.Up) { + if (s_logger.isDebugEnabled()) { s_logger.debug("successfully pinged vm's private IP (" + vm.getPrivateIpAddress() + "), returning that the VM is up"); } return Boolean.TRUE; @@ -93,43 +93,43 @@ public class ManagementIPSystemVMInvestigator extends AbstractInvestigatorImpl { if (s_logger.isDebugEnabled()) { s_logger.debug("successfully pinged vm's host IP (" + vmHost.getPrivateIpAddress() + "), but could not ping VM, returning that the VM is down"); } - return Boolean.FALSE; - } - } + return Boolean.FALSE; + } + } } - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("unable to determine state of " + vm + " returning null"); - } - return null; - } - - @Override + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("unable to determine state of " + vm + " returning null"); + } + return null; + } + + @Override public Status isAgentAlive(HostVO agent) { return null; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - -} + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _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/server/src/com/cloud/ha/UserVmDomRInvestigator.java b/server/src/com/cloud/ha/UserVmDomRInvestigator.java index 83fa0a64e98..9180e6d7cfe 100644 --- a/server/src/com/cloud/ha/UserVmDomRInvestigator.java +++ b/server/src/com/cloud/ha/UserVmDomRInvestigator.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.ha; - +package com.cloud.ha; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -37,18 +37,18 @@ import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.UserVmDao; - -@Local(value={Investigator.class}) -public class UserVmDomRInvestigator extends AbstractInvestigatorImpl { - private static final Logger s_logger = Logger.getLogger(UserVmDomRInvestigator.class); - - private String _name = null; - @Inject private final UserVmDao _userVmDao = null; + +@Local(value={Investigator.class}) +public class UserVmDomRInvestigator extends AbstractInvestigatorImpl { + private static final Logger s_logger = Logger.getLogger(UserVmDomRInvestigator.class); + + private String _name = null; + @Inject private final UserVmDao _userVmDao = null; @Inject private final AgentManager _agentMgr = null; @Inject private final NetworkManager _networkMgr = null; - @Inject private final VirtualNetworkApplianceManager _vnaMgr = null; - - @Override + @Inject private final VirtualNetworkApplianceManager _vnaMgr = null; + + @Override public Boolean isVmAlive(VMInstanceVO vm, HostVO host) { if (vm.getType() != VirtualMachine.Type.User) { if (s_logger.isDebugEnabled()) { @@ -57,9 +57,9 @@ public class UserVmDomRInvestigator extends AbstractInvestigatorImpl { return null; } - if (s_logger.isDebugEnabled()) { - s_logger.debug("testing if " + vm + " is alive"); - } + if (s_logger.isDebugEnabled()) { + s_logger.debug("testing if " + vm + " is alive"); + } // to verify that the VM is alive, we ask the domR (router) to ping the VM (private IP) UserVmVO userVm = _userVmDao.findById(vm.getId()); @@ -93,76 +93,76 @@ public class UserVmDomRInvestigator extends AbstractInvestigatorImpl { return result; } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Returning null since we're unable to determine state of " + vm); - } - return null; - } - - @Override - public Status isAgentAlive(HostVO agent) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("checking if agent (" + agent.getId() + ") is alive"); - } - - if (agent.getPodId() == null) { - return null; - } - - List otherHosts = findHostByPod(agent.getPodId(), agent.getId()); - - for (Long hostId : otherHosts) { - - if (s_logger.isDebugEnabled()) { - s_logger.debug("sending ping from (" + hostId + ") to agent's host ip address (" + agent.getPrivateIpAddress() + ")"); - } - Status hostState = testIpAddress(hostId, agent.getPrivateIpAddress()); - if (hostState == null) { - continue; - } - if (hostState == Status.Up) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("ping from (" + hostId + ") to agent's host ip address (" + agent.getPrivateIpAddress() + ") successful, returning that agent is disconnected"); - } - return Status.Disconnected; // the computing host ip is ping-able, but the computing agent is down, report that the agent is disconnected - } else if (hostState == Status.Down) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("returning host state: " + hostState); - } - return hostState; - } - } - - // could not reach agent, could not reach agent's host, unclear what the problem is but it'll require more investigation... - if (s_logger.isDebugEnabled()) { - s_logger.debug("could not reach agent, could not reach agent's host, returning that we don't have enough information"); - } - return null; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; + if (s_logger.isDebugEnabled()) { + s_logger.debug("Returning null since we're unable to determine state of " + vm); + } + return null; } - private Boolean testUserVM(VMInstanceVO vm, Nic nic, VirtualRouter router) { + @Override + public Status isAgentAlive(HostVO agent) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("checking if agent (" + agent.getId() + ") is alive"); + } + + if (agent.getPodId() == null) { + return null; + } + + List otherHosts = findHostByPod(agent.getPodId(), agent.getId()); + + for (Long hostId : otherHosts) { + + if (s_logger.isDebugEnabled()) { + s_logger.debug("sending ping from (" + hostId + ") to agent's host ip address (" + agent.getPrivateIpAddress() + ")"); + } + Status hostState = testIpAddress(hostId, agent.getPrivateIpAddress()); + if (hostState == null) { + continue; + } + if (hostState == Status.Up) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("ping from (" + hostId + ") to agent's host ip address (" + agent.getPrivateIpAddress() + ") successful, returning that agent is disconnected"); + } + return Status.Disconnected; // the computing host ip is ping-able, but the computing agent is down, report that the agent is disconnected + } else if (hostState == Status.Down) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("returning host state: " + hostState); + } + return hostState; + } + } + + // could not reach agent, could not reach agent's host, unclear what the problem is but it'll require more investigation... + if (s_logger.isDebugEnabled()) { + s_logger.debug("could not reach agent, could not reach agent's host, returning that we don't have enough information"); + } + return null; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + private Boolean testUserVM(VMInstanceVO vm, Nic nic, VirtualRouter router) { String privateIp = nic.getIp4Address(); String routerPrivateIp = router.getPrivateIpAddress(); @@ -194,5 +194,5 @@ public class UserVmDomRInvestigator extends AbstractInvestigatorImpl { } return null; - } -} + } +} diff --git a/server/src/com/cloud/host/dao/HostDao.java b/server/src/com/cloud/host/dao/HostDao.java index 75ac0c1c52e..76ad5d2204d 100755 --- a/server/src/com/cloud/host/dao/HostDao.java +++ b/server/src/com/cloud/host/dao/HostDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.host.dao; - +package com.cloud.host.dao; + import java.util.Date; import java.util.List; @@ -25,11 +25,11 @@ import com.cloud.info.RunningHostCountInfo; import com.cloud.resource.ResourceState; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; - -/** - * Data Access Object for server - * - */ + +/** + * Data Access Object for server + * + */ public interface HostDao extends GenericDao, StateDao { long countBy(long clusterId, ResourceState... states); @@ -38,17 +38,17 @@ public interface HostDao extends GenericDao, StateDao findLostHosts(long timeout); - + */ + void markHostsAsDisconnected(long msId, long lastPing); + + List findLostHosts(long timeout); + List findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId); - - List getRunningHostCounts(Date cutTime); - - long getNextSequence(long hostId); - + + List getRunningHostCounts(Date cutTime); + + long getNextSequence(long hostId); + void loadDetails(HostVO host); void saveDetails(HostVO host); @@ -65,5 +65,5 @@ public interface HostDao extends GenericDao, StateDao implements HostDao return findOneBy(sc); } - @Override @DB + @Override @DB public List findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) { Transaction txn = Transaction.currentTxn(); - txn.start(); + txn.start(); SearchCriteria sc = UnmanagedDirectConnectSearch.create(); sc.setParameters("lastPinged", lastPingSecondsAfter); //sc.setParameters("resourceStates", ResourceState.ErrorInMaintenance, ResourceState.Maintenance, ResourceState.PrepareForMaintenance, ResourceState.Disabled); - sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed); + sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed); List hosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit), true); for (HostVO host : hosts) { @@ -340,7 +340,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao txn.commit(); - return hosts; + return hosts; } @Override @DB @@ -362,12 +362,12 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return hosts; } - - @Override - public void markHostsAsDisconnected(long msId, long lastPing) { - SearchCriteria sc = MsStatusSearch.create(); + + @Override + public void markHostsAsDisconnected(long msId, long lastPing) { + SearchCriteria sc = MsStatusSearch.create(); sc.setParameters("ms", msId); - + HostVO host = createForUpdate(); host.setLastPinged(lastPing); host.setDisconnectedOn(new Date()); diff --git a/server/src/com/cloud/host/dao/HostTagsDao.java b/server/src/com/cloud/host/dao/HostTagsDao.java index 0a602cb3f84..ef2729052a8 100644 --- a/server/src/com/cloud/host/dao/HostTagsDao.java +++ b/server/src/com/cloud/host/dao/HostTagsDao.java @@ -10,17 +10,17 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.host.dao; - -import java.util.List; -import com.cloud.host.HostTagVO; -import com.cloud.utils.db.GenericDao; - -public interface HostTagsDao extends GenericDao { - - void persist(long hostId, List hostTags); - - List gethostTags(long hostId); - -} - +package com.cloud.host.dao; + +import java.util.List; +import com.cloud.host.HostTagVO; +import com.cloud.utils.db.GenericDao; + +public interface HostTagsDao extends GenericDao { + + void persist(long hostId, List hostTags); + + List gethostTags(long hostId); + +} + diff --git a/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDao.java b/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDao.java index 0e9e64a968b..270a67d1633 100644 --- a/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDao.java +++ b/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDao.java @@ -10,20 +10,20 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.dao; - -import java.util.List; - -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.HypervisorCapabilitiesVO; -import com.cloud.utils.db.GenericDao; - -public interface HypervisorCapabilitiesDao extends GenericDao { - - List listAllByHypervisorType(HypervisorType hypervisorType); - - HypervisorCapabilitiesVO findByHypervisorTypeAndVersion(HypervisorType hypervisorType, String hypervisorVersion); - - Long getMaxGuestsLimit(HypervisorType hypervisorType, String hypervisorVersion); - -} +package com.cloud.hypervisor.dao; + +import java.util.List; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.hypervisor.HypervisorCapabilitiesVO; +import com.cloud.utils.db.GenericDao; + +public interface HypervisorCapabilitiesDao extends GenericDao { + + List listAllByHypervisorType(HypervisorType hypervisorType); + + HypervisorCapabilitiesVO findByHypervisorTypeAndVersion(HypervisorType hypervisorType, String hypervisorVersion); + + Long getMaxGuestsLimit(HypervisorType hypervisorType, String hypervisorVersion); + +} diff --git a/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java b/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java index 5fa8fe0c96d..f15fec3405a 100644 --- a/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java +++ b/server/src/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java @@ -10,94 +10,94 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.dao; - -import java.util.List; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.HypervisorCapabilitiesVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.GenericSearchBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; - -@Local(value=HypervisorCapabilitiesDao.class) -public class HypervisorCapabilitiesDaoImpl extends GenericDaoBase implements HypervisorCapabilitiesDao { - - private static final Logger s_logger = Logger.getLogger(HypervisorCapabilitiesDaoImpl.class); - - protected final SearchBuilder HypervisorTypeSearch; - protected final SearchBuilder HypervisorTypeAndVersionSearch; - protected final GenericSearchBuilder MaxGuestLimitByHypervisorSearch; - - private static final String DEFAULT_VERSION = "default"; - - protected HypervisorCapabilitiesDaoImpl() { - HypervisorTypeSearch = createSearchBuilder(); - HypervisorTypeSearch.and("hypervisorType", HypervisorTypeSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); - HypervisorTypeSearch.done(); - - HypervisorTypeAndVersionSearch = createSearchBuilder(); - HypervisorTypeAndVersionSearch.and("hypervisorType", HypervisorTypeAndVersionSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); - HypervisorTypeAndVersionSearch.and("hypervisorVersion", HypervisorTypeAndVersionSearch.entity().getHypervisorVersion(), SearchCriteria.Op.EQ); - HypervisorTypeAndVersionSearch.done(); - - MaxGuestLimitByHypervisorSearch = createSearchBuilder(Long.class); - MaxGuestLimitByHypervisorSearch.selectField(MaxGuestLimitByHypervisorSearch.entity().getMaxGuestsLimit()); - MaxGuestLimitByHypervisorSearch.and("hypervisorType", MaxGuestLimitByHypervisorSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); - MaxGuestLimitByHypervisorSearch.and("hypervisorVersion", MaxGuestLimitByHypervisorSearch.entity().getHypervisorVersion(), SearchCriteria.Op.EQ); - MaxGuestLimitByHypervisorSearch.done(); - } - - @Override - public List listAllByHypervisorType(HypervisorType hypervisorType){ - SearchCriteria sc = HypervisorTypeSearch.create(); - sc.setParameters("hypervisorType", hypervisorType); - return search(sc, null); - } - - @Override - public HypervisorCapabilitiesVO findByHypervisorTypeAndVersion(HypervisorType hypervisorType, String hypervisorVersion){ - SearchCriteria sc = HypervisorTypeAndVersionSearch.create(); - sc.setParameters("hypervisorType", hypervisorType); - sc.setParameters("hypervisorVersion", hypervisorVersion); - return findOneBy(sc); - } - - @Override - public Long getMaxGuestsLimit(HypervisorType hypervisorType, String hypervisorVersion){ - Long defaultLimit = new Long(50); - Long result = null; - boolean useDefault = false; - if(hypervisorVersion != null){ - SearchCriteria sc = MaxGuestLimitByHypervisorSearch.create(); - sc.setParameters("hypervisorType", hypervisorType); - sc.setParameters("hypervisorVersion", hypervisorVersion); - List limitList = customSearch(sc, null); - if(!limitList.isEmpty()){ - result = limitList.get(0); - }else{ - useDefault = true; - } - }else{ - useDefault = true; - } - if(useDefault){ - SearchCriteria sc = MaxGuestLimitByHypervisorSearch.create(); - sc.setParameters("hypervisorType", hypervisorType); - sc.setParameters("hypervisorVersion", DEFAULT_VERSION); - List limitList = customSearch(sc, null); - if(!limitList.isEmpty()){ - result = limitList.get(0); - } - } - if(result == null){ - return defaultLimit; - } - return result; - } +package com.cloud.hypervisor.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.hypervisor.HypervisorCapabilitiesVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value=HypervisorCapabilitiesDao.class) +public class HypervisorCapabilitiesDaoImpl extends GenericDaoBase implements HypervisorCapabilitiesDao { + + private static final Logger s_logger = Logger.getLogger(HypervisorCapabilitiesDaoImpl.class); + + protected final SearchBuilder HypervisorTypeSearch; + protected final SearchBuilder HypervisorTypeAndVersionSearch; + protected final GenericSearchBuilder MaxGuestLimitByHypervisorSearch; + + private static final String DEFAULT_VERSION = "default"; + + protected HypervisorCapabilitiesDaoImpl() { + HypervisorTypeSearch = createSearchBuilder(); + HypervisorTypeSearch.and("hypervisorType", HypervisorTypeSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); + HypervisorTypeSearch.done(); + + HypervisorTypeAndVersionSearch = createSearchBuilder(); + HypervisorTypeAndVersionSearch.and("hypervisorType", HypervisorTypeAndVersionSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); + HypervisorTypeAndVersionSearch.and("hypervisorVersion", HypervisorTypeAndVersionSearch.entity().getHypervisorVersion(), SearchCriteria.Op.EQ); + HypervisorTypeAndVersionSearch.done(); + + MaxGuestLimitByHypervisorSearch = createSearchBuilder(Long.class); + MaxGuestLimitByHypervisorSearch.selectField(MaxGuestLimitByHypervisorSearch.entity().getMaxGuestsLimit()); + MaxGuestLimitByHypervisorSearch.and("hypervisorType", MaxGuestLimitByHypervisorSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); + MaxGuestLimitByHypervisorSearch.and("hypervisorVersion", MaxGuestLimitByHypervisorSearch.entity().getHypervisorVersion(), SearchCriteria.Op.EQ); + MaxGuestLimitByHypervisorSearch.done(); + } + + @Override + public List listAllByHypervisorType(HypervisorType hypervisorType){ + SearchCriteria sc = HypervisorTypeSearch.create(); + sc.setParameters("hypervisorType", hypervisorType); + return search(sc, null); + } + + @Override + public HypervisorCapabilitiesVO findByHypervisorTypeAndVersion(HypervisorType hypervisorType, String hypervisorVersion){ + SearchCriteria sc = HypervisorTypeAndVersionSearch.create(); + sc.setParameters("hypervisorType", hypervisorType); + sc.setParameters("hypervisorVersion", hypervisorVersion); + return findOneBy(sc); + } + + @Override + public Long getMaxGuestsLimit(HypervisorType hypervisorType, String hypervisorVersion){ + Long defaultLimit = new Long(50); + Long result = null; + boolean useDefault = false; + if(hypervisorVersion != null){ + SearchCriteria sc = MaxGuestLimitByHypervisorSearch.create(); + sc.setParameters("hypervisorType", hypervisorType); + sc.setParameters("hypervisorVersion", hypervisorVersion); + List limitList = customSearch(sc, null); + if(!limitList.isEmpty()){ + result = limitList.get(0); + }else{ + useDefault = true; + } + }else{ + useDefault = true; + } + if(useDefault){ + SearchCriteria sc = MaxGuestLimitByHypervisorSearch.create(); + sc.setParameters("hypervisorType", hypervisorType); + sc.setParameters("hypervisorVersion", DEFAULT_VERSION); + List limitList = customSearch(sc, null); + if(!limitList.isEmpty()){ + result = limitList.get(0); + } + } + if(result == null){ + return defaultLimit; + } + return result; + } } \ No newline at end of file diff --git a/server/src/com/cloud/hypervisor/guru/VMwareGuru.java b/server/src/com/cloud/hypervisor/guru/VMwareGuru.java index aeb785af5da..4f936beba91 100644 --- a/server/src/com/cloud/hypervisor/guru/VMwareGuru.java +++ b/server/src/com/cloud/hypervisor/guru/VMwareGuru.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.guru; - +package com.cloud.hypervisor.guru; + import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -66,34 +66,34 @@ import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VmDetailConstants; - -@Local(value=HypervisorGuru.class) -public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { - private static final Logger s_logger = Logger.getLogger(VMwareGuru.class); - + +@Local(value=HypervisorGuru.class) +public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { + private static final Logger s_logger = Logger.getLogger(VMwareGuru.class); + @Inject NetworkDao _networkDao; - @Inject GuestOSDao _guestOsDao; - @Inject HostDao _hostDao; - @Inject HostDetailsDao _hostDetailsDao; - @Inject CommandExecLogDao _cmdExecLogDao; - @Inject ClusterManager _clusterMgr; - @Inject VmwareManager _vmwareMgr; + @Inject GuestOSDao _guestOsDao; + @Inject HostDao _hostDao; + @Inject HostDetailsDao _hostDetailsDao; + @Inject CommandExecLogDao _cmdExecLogDao; + @Inject ClusterManager _clusterMgr; + @Inject VmwareManager _vmwareMgr; @Inject SecondaryStorageVmManager _secStorageMgr; @Inject CheckPointManager _checkPointMgr; - @Inject NetworkManager _networkMgr; - - protected VMwareGuru() { - super(); - } - - @Override - public HypervisorType getHypervisorType() { - return HypervisorType.VMware; - } - - @Override + @Inject NetworkManager _networkMgr; + + protected VMwareGuru() { + super(); + } + + @Override + public HypervisorType getHypervisorType() { + return HypervisorType.VMware; + } + + @Override public VirtualMachineTO implement(VirtualMachineProfile vm) { - VirtualMachineTO to = toVirtualMachineTO(vm); + VirtualMachineTO to = toVirtualMachineTO(vm); to.setBootloader(BootloaderType.HVM); Map details = to.getDetails(); @@ -126,7 +126,7 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString()); } } - } + } to.setDetails(details); if(vm.getVirtualMachine() instanceof DomainRouterVO) { @@ -200,12 +200,12 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { String bootArgs = to.getBootArgs(); to.setBootArgs(bootArgs + " nic_macs=" + sbMacSequence.toString()); } - - // Determine the VM's OS description - GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine().getGuestOSId()); - to.setOs(guestOS.getDisplayName()); - return to; - } + + // Determine the VM's OS description + GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine().getGuestOSId()); + to.setOs(guestOS.getDisplayName()); + return to; + } private NicTO[] sortNicsByDeviceId(NicTO[] nics) { @@ -229,39 +229,39 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { return listForSort.toArray(new NicTO[0]); } - - @Override @DB - public long getCommandHostDelegation(long hostId, Command cmd) { - boolean needDelegation = false; - - if(cmd instanceof PrimaryStorageDownloadCommand || - cmd instanceof BackupSnapshotCommand || - cmd instanceof CreatePrivateTemplateFromVolumeCommand || - cmd instanceof CreatePrivateTemplateFromSnapshotCommand || - cmd instanceof CopyVolumeCommand || - cmd instanceof CreateVolumeFromSnapshotCommand) { - needDelegation = true; - } - - if(needDelegation) { - HostVO host = _hostDao.findById(hostId); - assert(host != null); - assert(host.getHypervisorType() == HypervisorType.VMware); - long dcId = host.getDataCenterId(); - - Pair cmdTarget = _secStorageMgr.assignSecStorageVm(dcId, cmd); - if(cmdTarget != null) { - // TODO, we need to make sure agent is actually connected too - cmd.setContextParam("hypervisor", HypervisorType.VMware.toString()); - Map hostDetails = _hostDetailsDao.findDetails(hostId); - cmd.setContextParam("guid", resolveNameInGuid(hostDetails.get("guid"))); - cmd.setContextParam("username", hostDetails.get("username")); - cmd.setContextParam("password", hostDetails.get("password")); - cmd.setContextParam("serviceconsole", _vmwareMgr.getServiceConsolePortGroupName()); + + @Override @DB + public long getCommandHostDelegation(long hostId, Command cmd) { + boolean needDelegation = false; + + if(cmd instanceof PrimaryStorageDownloadCommand || + cmd instanceof BackupSnapshotCommand || + cmd instanceof CreatePrivateTemplateFromVolumeCommand || + cmd instanceof CreatePrivateTemplateFromSnapshotCommand || + cmd instanceof CopyVolumeCommand || + cmd instanceof CreateVolumeFromSnapshotCommand) { + needDelegation = true; + } + + if(needDelegation) { + HostVO host = _hostDao.findById(hostId); + assert(host != null); + assert(host.getHypervisorType() == HypervisorType.VMware); + long dcId = host.getDataCenterId(); + + Pair cmdTarget = _secStorageMgr.assignSecStorageVm(dcId, cmd); + if(cmdTarget != null) { + // TODO, we need to make sure agent is actually connected too + cmd.setContextParam("hypervisor", HypervisorType.VMware.toString()); + Map hostDetails = _hostDetailsDao.findDetails(hostId); + cmd.setContextParam("guid", resolveNameInGuid(hostDetails.get("guid"))); + cmd.setContextParam("username", hostDetails.get("username")); + cmd.setContextParam("password", hostDetails.get("password")); + cmd.setContextParam("serviceconsole", _vmwareMgr.getServiceConsolePortGroupName()); cmd.setContextParam("manageportgroup", _vmwareMgr.getManagementPortGroupName()); - - CommandExecLogVO execLog = new CommandExecLogVO(cmdTarget.first().getId(), cmdTarget.second().getId(), cmd.getClass().getSimpleName(), 1); - _cmdExecLogDao.persist(execLog); + + CommandExecLogVO execLog = new CommandExecLogVO(cmdTarget.first().getId(), cmdTarget.second().getId(), cmd.getClass().getSimpleName(), 1); + _cmdExecLogDao.persist(execLog); cmd.setContextParam("execid", String.valueOf(execLog.getId())); if(cmd instanceof BackupSnapshotCommand || @@ -281,31 +281,31 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { cmd.setContextParam("worker2", workerName2); cmd.setContextParam("checkpoint2", String.valueOf(checkPointId2)); } - - return cmdTarget.first().getId(); - } - } - - return hostId; + + return cmdTarget.first().getId(); + } + } + + return hostId; } public boolean trackVmHostChange() { return true; } - - private static String resolveNameInGuid(String guid) { - String tokens[] = guid.split("@"); - assert(tokens.length == 2); - - String vCenterIp = NetUtils.resolveToIp(tokens[1]); - if(vCenterIp == null) { - s_logger.error("Fatal : unable to resolve vCenter address " + tokens[1] + ", please check your DNS configuration"); - return guid; - } - - if(vCenterIp.equals(tokens[1])) - return guid; - - return tokens[0] + "@" + vCenterIp; - } -} + + private static String resolveNameInGuid(String guid) { + String tokens[] = guid.split("@"); + assert(tokens.length == 2); + + String vCenterIp = NetUtils.resolveToIp(tokens[1]); + if(vCenterIp == null) { + s_logger.error("Fatal : unable to resolve vCenter address " + tokens[1] + ", please check your DNS configuration"); + return guid; + } + + if(vCenterIp.equals(tokens[1])) + return guid; + + return tokens[0] + "@" + vCenterIp; + } +} diff --git a/server/src/com/cloud/hypervisor/vmware/VmwareManagerImpl.java b/server/src/com/cloud/hypervisor/vmware/VmwareManagerImpl.java index 8b8968c5117..9a9c71609ec 100755 --- a/server/src/com/cloud/hypervisor/vmware/VmwareManagerImpl.java +++ b/server/src/com/cloud/hypervisor/vmware/VmwareManagerImpl.java @@ -817,9 +817,9 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis } } } - + protected final int DEFAULT_DOMR_SSHPORT = 3922; - + protected boolean shutdownRouterVM(DomainRouterVO router) { if (s_logger.isDebugEnabled()) { s_logger.debug("Try to shutdown router VM " + router.getInstanceName() + " directly."); diff --git a/server/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/server/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java index 8b2bf6eef18..5dc006d3494 100755 --- a/server/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java +++ b/server/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java @@ -10,87 +10,87 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware; - -import java.net.URI; -import java.net.URLDecoder; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - +package com.cloud.hypervisor.vmware; + +import java.net.URI; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.alert.AlertManager; -import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; +import com.cloud.alert.AlertManager; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.ClusterDetailsDao; +import com.cloud.dc.ClusterVO; +import com.cloud.dc.dao.ClusterDao; import com.cloud.exception.DiscoveredWithErrorException; -import com.cloud.exception.DiscoveryException; -import com.cloud.host.HostVO; +import com.cloud.exception.DiscoveryException; +import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.vmware.manager.VmwareManager; -import com.cloud.hypervisor.vmware.mo.ClusterMO; -import com.cloud.hypervisor.vmware.mo.HostMO; -import com.cloud.hypervisor.vmware.resource.VmwareContextFactory; -import com.cloud.hypervisor.vmware.resource.VmwareResource; -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.cloud.resource.Discoverer; -import com.cloud.resource.DiscovererBase; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.hypervisor.vmware.manager.VmwareManager; +import com.cloud.hypervisor.vmware.mo.ClusterMO; +import com.cloud.hypervisor.vmware.mo.HostMO; +import com.cloud.hypervisor.vmware.resource.VmwareContextFactory; +import com.cloud.hypervisor.vmware.resource.VmwareResource; +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.cloud.resource.Discoverer; +import com.cloud.resource.DiscovererBase; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; +import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; import com.cloud.resource.ResourceStateAdapter.DeleteHostAnswer; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.Storage.TemplateType; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.user.Account; -import com.cloud.utils.UriUtils; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.Inject; -import com.vmware.vim25.ClusterDasConfigInfo; -import com.vmware.vim25.ManagedObjectReference; - -@Local(value=Discoverer.class) -public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter { - private static final Logger s_logger = Logger.getLogger(VmwareServerDiscoverer.class); - - @Inject ClusterDao _clusterDao; - @Inject VmwareManager _vmwareMgr; - @Inject AlertManager _alertMgr; - @Inject VMTemplateDao _tmpltDao; +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.storage.Storage.TemplateType; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.user.Account; +import com.cloud.utils.UriUtils; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; +import com.vmware.vim25.ClusterDasConfigInfo; +import com.vmware.vim25.ManagedObjectReference; + +@Local(value=Discoverer.class) +public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter { + private static final Logger s_logger = Logger.getLogger(VmwareServerDiscoverer.class); + + @Inject ClusterDao _clusterDao; + @Inject VmwareManager _vmwareMgr; + @Inject AlertManager _alertMgr; + @Inject VMTemplateDao _tmpltDao; @Inject ClusterDetailsDao _clusterDetailsDao; - @Inject HostDao _hostDao; + @Inject HostDao _hostDao; @Inject ResourceManager _resourceMgr; - - @Override - public Map> find(long dcId, Long podId, Long clusterId, URI url, - String username, String password, List hostTags) throws DiscoveryException { - - if(s_logger.isInfoEnabled()) - s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost()); - - if(podId == null) { - if(s_logger.isInfoEnabled()) - s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer"); - return null; - } - - ClusterVO cluster = _clusterDao.findById(clusterId); - if(cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) { - if(s_logger.isInfoEnabled()) - s_logger.info("invalid cluster id or cluster is not for VMware hypervisors"); - return null; + + @Override + public Map> find(long dcId, Long podId, Long clusterId, URI url, + String username, String password, List hostTags) throws DiscoveryException { + + if(s_logger.isInfoEnabled()) + s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost()); + + if(podId == null) { + if(s_logger.isInfoEnabled()) + s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer"); + return null; + } + + ClusterVO cluster = _clusterDao.findById(clusterId); + if(cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) { + if(s_logger.isInfoEnabled()) + s_logger.info("invalid cluster id or cluster is not for VMware hypervisors"); + return null; } List hosts = _resourceMgr.listAllHostsInCluster(clusterId); @@ -99,169 +99,169 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer s_logger.error(msg); throw new DiscoveredWithErrorException(msg); } - - VmwareContext context = null; - try { - context = VmwareContextFactory.create(url.getHost(), username, password); - List morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId, - URLDecoder.decode(url.getPath())); - if(morHosts == null) { - s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath())); - return null; - } - - ManagedObjectReference morCluster = null; - Map clusterDetails = _clusterDetailsDao.findDetails(clusterId); - if(clusterDetails.get("url") != null) { - URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url"))); - morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath())); - - if(morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) { - s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url")); - return null; - } else { - ClusterMO clusterMo = new ClusterMO(context, morCluster); - ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig(); - if(dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) { - clusterDetails.put("NativeHA", "true"); - _clusterDetailsDao.persist(clusterId, clusterDetails); - } - } - } - - if(!validateDiscoveredHosts(context, morCluster, morHosts)) { - if(morCluster == null) - s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster"); - else - s_logger.warn("The discovered host does not belong to the cluster"); - return null; - } - - Map> resources = new HashMap>(); - for(ManagedObjectReference morHost : morHosts) { - Map details = new HashMap(); - Map params = new HashMap(); - - HostMO hostMo = new HostMO(context, morHost); - details.put("url", hostMo.getHostName()); - details.put("username", username); - details.put("password", password); - String guid = morHost.getType() + ":" + morHost.get_value() + "@"+ url.getHost(); - details.put("guid", guid); - - params.put("url", hostMo.getHostName()); - params.put("username", username); - params.put("password", password); - params.put("zone", Long.toString(dcId)); - params.put("pod", Long.toString(podId)); - params.put("cluster", Long.toString(clusterId)); - params.put("guid", guid); - - VmwareResource resource = new VmwareResource(); - try { - resource.configure("VMware", params); - } catch (ConfigurationException e) { - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage()); - s_logger.warn("Unable to instantiate " + url.getHost(), e); - } - resource.start(); - - resources.put(resource, details); - } - - // place a place holder guid derived from cluster ID - cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString()); - _clusterDao.update(clusterId, cluster); - - return resources; + + VmwareContext context = null; + try { + context = VmwareContextFactory.create(url.getHost(), username, password); + List morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId, + URLDecoder.decode(url.getPath())); + if(morHosts == null) { + s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath())); + return null; + } + + ManagedObjectReference morCluster = null; + Map clusterDetails = _clusterDetailsDao.findDetails(clusterId); + if(clusterDetails.get("url") != null) { + URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url"))); + morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath())); + + if(morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) { + s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url")); + return null; + } else { + ClusterMO clusterMo = new ClusterMO(context, morCluster); + ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig(); + if(dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) { + clusterDetails.put("NativeHA", "true"); + _clusterDetailsDao.persist(clusterId, clusterDetails); + } + } + } + + if(!validateDiscoveredHosts(context, morCluster, morHosts)) { + if(morCluster == null) + s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster"); + else + s_logger.warn("The discovered host does not belong to the cluster"); + return null; + } + + Map> resources = new HashMap>(); + for(ManagedObjectReference morHost : morHosts) { + Map details = new HashMap(); + Map params = new HashMap(); + + HostMO hostMo = new HostMO(context, morHost); + details.put("url", hostMo.getHostName()); + details.put("username", username); + details.put("password", password); + String guid = morHost.getType() + ":" + morHost.get_value() + "@"+ url.getHost(); + details.put("guid", guid); + + params.put("url", hostMo.getHostName()); + params.put("username", username); + params.put("password", password); + params.put("zone", Long.toString(dcId)); + params.put("pod", Long.toString(podId)); + params.put("cluster", Long.toString(clusterId)); + params.put("guid", guid); + + VmwareResource resource = new VmwareResource(); + try { + resource.configure("VMware", params); + } catch (ConfigurationException e) { + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage()); + s_logger.warn("Unable to instantiate " + url.getHost(), e); + } + resource.start(); + + resources.put(resource, details); + } + + // place a place holder guid derived from cluster ID + cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString()); + _clusterDao.update(clusterId, cluster); + + return resources; } catch (DiscoveredWithErrorException e) { throw e; - } catch (Exception e) { - s_logger.warn("Unable to connect to Vmware vSphere server. service address: " + url.getHost()); - return null; - } finally { - if(context != null) - context.close(); - } - } - - private boolean validateDiscoveredHosts(VmwareContext context, ManagedObjectReference morCluster, List morHosts) throws Exception { - if(morCluster == null) { - for(ManagedObjectReference morHost : morHosts) { - ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent"); - if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) - return false; - } - } else { - for(ManagedObjectReference morHost : morHosts) { - ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent"); - if(!morParent.getType().equalsIgnoreCase("ClusterComputeResource")) - return false; - - if(!morParent.get_value().equals(morCluster.get_value())) - return false; - } - } - - return true; - } - - @Override - public void postDiscovery(List hosts, long msId) { - // do nothing - } - - @Override - public boolean matchHypervisor(String hypervisor) { - if(hypervisor == null) - return true; - - return Hypervisor.HypervisorType.VMware.toString().equalsIgnoreCase(hypervisor); - } - - @Override - public Hypervisor.HypervisorType getHypervisorType() { - return Hypervisor.HypervisorType.VMware; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - if(s_logger.isInfoEnabled()) - s_logger.info("Configure VmwareServerDiscoverer, discover name: " + name); - - super.configure(name, params); - - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - if (configDao == null) { - throw new ConfigurationException("Unable to get the configuration dao."); - } - - createVmwareToolsIso(); - - if(s_logger.isInfoEnabled()) { + } catch (Exception e) { + s_logger.warn("Unable to connect to Vmware vSphere server. service address: " + url.getHost()); + return null; + } finally { + if(context != null) + context.close(); + } + } + + private boolean validateDiscoveredHosts(VmwareContext context, ManagedObjectReference morCluster, List morHosts) throws Exception { + if(morCluster == null) { + for(ManagedObjectReference morHost : morHosts) { + ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent"); + if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) + return false; + } + } else { + for(ManagedObjectReference morHost : morHosts) { + ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent"); + if(!morParent.getType().equalsIgnoreCase("ClusterComputeResource")) + return false; + + if(!morParent.get_value().equals(morCluster.get_value())) + return false; + } + } + + return true; + } + + @Override + public void postDiscovery(List hosts, long msId) { + // do nothing + } + + @Override + public boolean matchHypervisor(String hypervisor) { + if(hypervisor == null) + return true; + + return Hypervisor.HypervisorType.VMware.toString().equalsIgnoreCase(hypervisor); + } + + @Override + public Hypervisor.HypervisorType getHypervisorType() { + return Hypervisor.HypervisorType.VMware; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + if(s_logger.isInfoEnabled()) + s_logger.info("Configure VmwareServerDiscoverer, discover name: " + name); + + super.configure(name, params); + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + if (configDao == null) { + throw new ConfigurationException("Unable to get the configuration dao."); + } + + createVmwareToolsIso(); + + if(s_logger.isInfoEnabled()) { s_logger.info("VmwareServerDiscoverer has been successfully configured"); } - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); - return true; - } - - private void createVmwareToolsIso() { - String isoName = "vmware-tools.iso"; - VMTemplateVO tmplt = _tmpltDao.findByTemplateName(isoName); - Long id; - if (tmplt == null) { - id = _tmpltDao.getNextInSequence(Long.class, "id"); - VMTemplateVO template = new VMTemplateVO(id, isoName, isoName, ImageFormat.ISO, true, true, - TemplateType.PERHOST, null, null, true, 64, - Account.ACCOUNT_ID_SYSTEM, null, "VMware Tools Installer ISO", false, 1, false, HypervisorType.VMware); - _tmpltDao.persist(template); - } else { - id = tmplt.getId(); - tmplt.setTemplateType(TemplateType.PERHOST); - tmplt.setUrl(null); - _tmpltDao.update(id, tmplt); - } + _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); + return true; + } + + private void createVmwareToolsIso() { + String isoName = "vmware-tools.iso"; + VMTemplateVO tmplt = _tmpltDao.findByTemplateName(isoName); + Long id; + if (tmplt == null) { + id = _tmpltDao.getNextInSequence(Long.class, "id"); + VMTemplateVO template = new VMTemplateVO(id, isoName, isoName, ImageFormat.ISO, true, true, + TemplateType.PERHOST, null, null, true, 64, + Account.ACCOUNT_ID_SYSTEM, null, "VMware Tools Installer ISO", false, 1, false, HypervisorType.VMware); + _tmpltDao.persist(template); + } else { + id = tmplt.getId(); + tmplt.setTemplateType(TemplateType.PERHOST); + tmplt.setUrl(null); + _tmpltDao.update(id, tmplt); + } } @Override @@ -300,6 +300,6 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer public boolean stop() { _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); return super.stop(); - } -} - + } +} + diff --git a/server/src/com/cloud/migration/DiskOffering20Dao.java b/server/src/com/cloud/migration/DiskOffering20Dao.java index c5ed5ea9eb7..c3b0037b321 100644 --- a/server/src/com/cloud/migration/DiskOffering20Dao.java +++ b/server/src/com/cloud/migration/DiskOffering20Dao.java @@ -10,9 +10,9 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import com.cloud.utils.db.GenericDao; - -public interface DiskOffering20Dao extends GenericDao { -} +package com.cloud.migration; + +import com.cloud.utils.db.GenericDao; + +public interface DiskOffering20Dao extends GenericDao { +} diff --git a/server/src/com/cloud/migration/DiskOffering20DaoImpl.java b/server/src/com/cloud/migration/DiskOffering20DaoImpl.java index 581ef208d83..af07f01c65f 100644 --- a/server/src/com/cloud/migration/DiskOffering20DaoImpl.java +++ b/server/src/com/cloud/migration/DiskOffering20DaoImpl.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import javax.ejb.Local; - -import com.cloud.utils.db.GenericDaoBase; - -@Local(value={DiskOffering20Dao.class}) -public class DiskOffering20DaoImpl extends GenericDaoBase implements DiskOffering20Dao { -} +package com.cloud.migration; + +import javax.ejb.Local; + +import com.cloud.utils.db.GenericDaoBase; + +@Local(value={DiskOffering20Dao.class}) +public class DiskOffering20DaoImpl extends GenericDaoBase implements DiskOffering20Dao { +} diff --git a/server/src/com/cloud/migration/DiskOffering20VO.java b/server/src/com/cloud/migration/DiskOffering20VO.java index 7450b585961..b9c5d8729c2 100644 --- a/server/src/com/cloud/migration/DiskOffering20VO.java +++ b/server/src/com/cloud/migration/DiskOffering20VO.java @@ -10,99 +10,99 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="disk_offering") -public class DiskOffering20VO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - Long id; - - @Column(name="domain_id") - long domainId; - - @Column(name="name") - private String name = null; - - @Column(name="display_text") - private String displayText = null; - - @Column(name="disk_size") - long diskSize; - - @Column(name="mirrored") - boolean mirrored; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - public DiskOffering20VO() { - } - - public DiskOffering20VO(long domainId, String name, String displayText, long diskSize, boolean mirrored) { - this.domainId = domainId; - this.name = name; - this.displayText = displayText; - this.diskSize = diskSize; - this.mirrored = mirrored; - } - - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public long getDomainId() { - return domainId; - } - public void setDomainId(long domainId) { - this.domainId = domainId; - } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - public String getDisplayText() { - return displayText; - } - public void setDisplayText(String displayText) { - this.displayText = displayText; - } - - public long getDiskSize() { - return diskSize; - } - public void setDiskSize(long diskSize) { - this.diskSize = diskSize; - } - - public boolean getMirrored() { - return mirrored; - } - public void setMirrored(boolean mirrored) { - this.mirrored = mirrored; - } - - public Date getRemoved() { - return removed; - } -} +package com.cloud.migration; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name="disk_offering") +public class DiskOffering20VO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + Long id; + + @Column(name="domain_id") + long domainId; + + @Column(name="name") + private String name = null; + + @Column(name="display_text") + private String displayText = null; + + @Column(name="disk_size") + long diskSize; + + @Column(name="mirrored") + boolean mirrored; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + public DiskOffering20VO() { + } + + public DiskOffering20VO(long domainId, String name, String displayText, long diskSize, boolean mirrored) { + this.domainId = domainId; + this.name = name; + this.displayText = displayText; + this.diskSize = diskSize; + this.mirrored = mirrored; + } + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + public long getDomainId() { + return domainId; + } + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getDisplayText() { + return displayText; + } + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public long getDiskSize() { + return diskSize; + } + public void setDiskSize(long diskSize) { + this.diskSize = diskSize; + } + + public boolean getMirrored() { + return mirrored; + } + public void setMirrored(boolean mirrored) { + this.mirrored = mirrored; + } + + public Date getRemoved() { + return removed; + } +} diff --git a/server/src/com/cloud/migration/DiskOffering21Dao.java b/server/src/com/cloud/migration/DiskOffering21Dao.java index 3e254fb199d..a70d804cfc9 100644 --- a/server/src/com/cloud/migration/DiskOffering21Dao.java +++ b/server/src/com/cloud/migration/DiskOffering21Dao.java @@ -10,10 +10,10 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import com.cloud.utils.db.GenericDao; - -public interface DiskOffering21Dao extends GenericDao { -} - +package com.cloud.migration; + +import com.cloud.utils.db.GenericDao; + +public interface DiskOffering21Dao extends GenericDao { +} + diff --git a/server/src/com/cloud/migration/DiskOffering21DaoImpl.java b/server/src/com/cloud/migration/DiskOffering21DaoImpl.java index eec6061f7e3..b74861bc7f8 100644 --- a/server/src/com/cloud/migration/DiskOffering21DaoImpl.java +++ b/server/src/com/cloud/migration/DiskOffering21DaoImpl.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import javax.ejb.Local; - -import com.cloud.utils.db.GenericDaoBase; - -@Local(value={DiskOffering21Dao.class}) -public class DiskOffering21DaoImpl extends GenericDaoBase implements DiskOffering21Dao { -} +package com.cloud.migration; + +import javax.ejb.Local; + +import com.cloud.utils.db.GenericDaoBase; + +@Local(value={DiskOffering21Dao.class}) +public class DiskOffering21DaoImpl extends GenericDaoBase implements DiskOffering21Dao { +} diff --git a/server/src/com/cloud/migration/DiskOffering21VO.java b/server/src/com/cloud/migration/DiskOffering21VO.java index e480d23849b..3c71aae636c 100644 --- a/server/src/com/cloud/migration/DiskOffering21VO.java +++ b/server/src/com/cloud/migration/DiskOffering21VO.java @@ -10,116 +10,116 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import java.util.Date; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.Table; -import javax.persistence.Transient; - -import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="disk_offering_21") -@Inheritance(strategy=InheritanceType.JOINED) -@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) -public class DiskOffering21VO { - public enum Type { - Disk, - Service - }; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - long id; - - @Column(name="domain_id") - Long domainId; - - @Column(name="unique_name") - private String uniqueName; - - @Column(name="name") - private String name = null; - - @Column(name="display_text") - private String displayText = null; - - @Column(name="disk_size") - long diskSize; - - @Column(name="mirrored") - boolean mirrored; - - @Column(name="tags") - String tags; - - @Column(name="type") - Type type; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date created; - - @Column(name="recreatable") - private boolean recreatable; - - @Column(name="use_local_storage") - private boolean useLocalStorage; +package com.cloud.migration; + +import java.util.Date; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name="disk_offering_21") +@Inheritance(strategy=InheritanceType.JOINED) +@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) +public class DiskOffering21VO { + public enum Type { + Disk, + Service + }; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + long id; + + @Column(name="domain_id") + Long domainId; + + @Column(name="unique_name") + private String uniqueName; + + @Column(name="name") + private String name = null; + + @Column(name="display_text") + private String displayText = null; + + @Column(name="disk_size") + long diskSize; + + @Column(name="mirrored") + boolean mirrored; + + @Column(name="tags") + String tags; + + @Column(name="type") + Type type; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name="recreatable") + private boolean recreatable; + + @Column(name="use_local_storage") + private boolean useLocalStorage; @Column(name="system_use") protected boolean systemUse; - - public DiskOffering21VO() { - } - - public DiskOffering21VO(long domainId, String name, String displayText, long diskSize, boolean mirrored, String tags) { - this.domainId = domainId; - this.name = name; - this.displayText = displayText; - this.diskSize = diskSize; - this.mirrored = mirrored; - this.tags = tags; - this.recreatable = false; - this.type = Type.Disk; - this.useLocalStorage = false; - } - - public DiskOffering21VO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, boolean useLocalStorage) { - this.domainId = null; - this.type = Type.Service; - this.name = name; - this.displayText = displayText; - this.mirrored = mirrored; - this.tags = tags; - this.recreatable = recreatable; - this.useLocalStorage = useLocalStorage; - } - - public long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUniqueName() { - return uniqueName; + + public DiskOffering21VO() { + } + + public DiskOffering21VO(long domainId, String name, String displayText, long diskSize, boolean mirrored, String tags) { + this.domainId = domainId; + this.name = name; + this.displayText = displayText; + this.diskSize = diskSize; + this.mirrored = mirrored; + this.tags = tags; + this.recreatable = false; + this.type = Type.Disk; + this.useLocalStorage = false; + } + + public DiskOffering21VO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, boolean useLocalStorage) { + this.domainId = null; + this.type = Type.Service; + this.name = name; + this.displayText = displayText; + this.mirrored = mirrored; + this.tags = tags; + this.recreatable = recreatable; + this.useLocalStorage = useLocalStorage; + } + + public long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUniqueName() { + return uniqueName; } public boolean getSystemUse() { @@ -128,125 +128,125 @@ public class DiskOffering21VO { public void setSystemUse(boolean systemUse) { this.systemUse = systemUse; - } - - public boolean getUseLocalStorage() { - return useLocalStorage; - } - - public void setUserLocalStorage(boolean useLocalStorage) { - this.useLocalStorage = useLocalStorage; - } - - public Long getDomainId() { - return domainId; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } - - public boolean isRecreatable() { - return recreatable; - } - - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDisplayText() { - return displayText; - } - public void setDisplayText(String displayText) { - this.displayText = displayText; - } - - public long getDiskSizeInBytes() { - return diskSize * 1024 * 1024; - } - - public void setDiskSize(long diskSize) { - this.diskSize = diskSize; - } - - public boolean isMirrored() { - return mirrored; - } - public void setMirrored(boolean mirrored) { - this.mirrored = mirrored; - } - - public Date getRemoved() { - return removed; - } - - public Date getCreated() { - return created; - } - - protected void setTags(String tags) { - this.tags = tags; - } - - public String getTags() { - return tags; - } - - public void setUniqueName(String name) { - this.uniqueName = name; - } - - @Transient - public String[] getTagsArray() { - String tags = getTags(); - if (tags == null || tags.isEmpty()) { - return new String[0]; - } - - return tags.split(","); - } - - @Transient - public boolean containsTag(String... tags) { - if (this.tags == null) { - return false; - } - - for (String tag : tags) { - if (!this.tags.matches(tag)) { - return false; - } - } - - return true; - } - - @Transient - public void setTagsArray(List newTags) { - if (newTags.isEmpty()) { - setTags(null); - return; - } - - StringBuilder buf = new StringBuilder(); - for (String tag : newTags) { - buf.append(tag).append(","); - } - - buf.delete(buf.length() - 1, buf.length()); - - setTags(buf.toString()); - } -} + } + + public boolean getUseLocalStorage() { + return useLocalStorage; + } + + public void setUserLocalStorage(boolean useLocalStorage) { + this.useLocalStorage = useLocalStorage; + } + + public Long getDomainId() { + return domainId; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + public boolean isRecreatable() { + return recreatable; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayText() { + return displayText; + } + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public long getDiskSizeInBytes() { + return diskSize * 1024 * 1024; + } + + public void setDiskSize(long diskSize) { + this.diskSize = diskSize; + } + + public boolean isMirrored() { + return mirrored; + } + public void setMirrored(boolean mirrored) { + this.mirrored = mirrored; + } + + public Date getRemoved() { + return removed; + } + + public Date getCreated() { + return created; + } + + protected void setTags(String tags) { + this.tags = tags; + } + + public String getTags() { + return tags; + } + + public void setUniqueName(String name) { + this.uniqueName = name; + } + + @Transient + public String[] getTagsArray() { + String tags = getTags(); + if (tags == null || tags.isEmpty()) { + return new String[0]; + } + + return tags.split(","); + } + + @Transient + public boolean containsTag(String... tags) { + if (this.tags == null) { + return false; + } + + for (String tag : tags) { + if (!this.tags.matches(tag)) { + return false; + } + } + + return true; + } + + @Transient + public void setTagsArray(List newTags) { + if (newTags.isEmpty()) { + setTags(null); + return; + } + + StringBuilder buf = new StringBuilder(); + for (String tag : newTags) { + buf.append(tag).append(","); + } + + buf.delete(buf.length() - 1, buf.length()); + + setTags(buf.toString()); + } +} diff --git a/server/src/com/cloud/migration/ServiceOffering20Dao.java b/server/src/com/cloud/migration/ServiceOffering20Dao.java index d6dd9115437..5eab55c8bd7 100644 --- a/server/src/com/cloud/migration/ServiceOffering20Dao.java +++ b/server/src/com/cloud/migration/ServiceOffering20Dao.java @@ -10,9 +10,9 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import com.cloud.utils.db.GenericDao; - -public interface ServiceOffering20Dao extends GenericDao { -} +package com.cloud.migration; + +import com.cloud.utils.db.GenericDao; + +public interface ServiceOffering20Dao extends GenericDao { +} diff --git a/server/src/com/cloud/migration/ServiceOffering20DaoImpl.java b/server/src/com/cloud/migration/ServiceOffering20DaoImpl.java index 9efdb7730c8..d2eefbc9da8 100644 --- a/server/src/com/cloud/migration/ServiceOffering20DaoImpl.java +++ b/server/src/com/cloud/migration/ServiceOffering20DaoImpl.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import javax.ejb.Local; - -import com.cloud.utils.db.GenericDaoBase; - -@Local(value={ServiceOffering20Dao.class}) -public class ServiceOffering20DaoImpl extends GenericDaoBase implements ServiceOffering20Dao { -} +package com.cloud.migration; + +import javax.ejb.Local; + +import com.cloud.utils.db.GenericDaoBase; + +@Local(value={ServiceOffering20Dao.class}) +public class ServiceOffering20DaoImpl extends GenericDaoBase implements ServiceOffering20Dao { +} diff --git a/server/src/com/cloud/migration/ServiceOffering20VO.java b/server/src/com/cloud/migration/ServiceOffering20VO.java index 4c2ced9928c..c238bc45bc8 100644 --- a/server/src/com/cloud/migration/ServiceOffering20VO.java +++ b/server/src/com/cloud/migration/ServiceOffering20VO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - +package com.cloud.migration; + import java.util.Date; import javax.persistence.Column; @@ -26,169 +26,169 @@ import javax.persistence.Table; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="service_offering") -public class ServiceOffering20VO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id = null; - - @Column(name="name") - private String name = null; - - @Column(name="cpu") - private int cpu; - - @Column(name="speed") - private int speed; - - @Column(name="ram_size") - private int ramSize; - - @Column(name="nw_rate") - private int rateMbps; - - @Column(name="mc_rate") - private int multicastRateMbps; - - @Column(name="mirrored") - private boolean mirroredVolumes; - - @Column(name="ha_enabled") - private boolean offerHA; - - @Column(name="display_text") - private String displayText = null; - - @Column(name="guest_ip_type") - @Enumerated(EnumType.STRING) - private Vlan.VlanType guestIpType = Vlan.VlanType.VirtualNetwork; - - @Column(name="use_local_storage") - private boolean useLocalStorage; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date created; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - protected ServiceOffering20VO() { - } - - public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, boolean localStorageRequired) { - this(id, name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, Vlan.VlanType.VirtualNetwork, localStorageRequired); - } - - public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, VlanType guestIpType, boolean useLocalStorage) { - this.id = id; - this.name = name; - this.cpu = cpu; - this.ramSize = ramSize; - this.speed = speed; - this.rateMbps = rateMbps; - this.multicastRateMbps = multicastRateMbps; - this.offerHA = offerHA; - this.displayText = displayText; - this.guestIpType = guestIpType; - this.useLocalStorage = useLocalStorage; - } - - public boolean getOfferHA() { - return offerHA; - } - - public void setOfferHA(boolean offerHA) { - this.offerHA = offerHA; - } - - public Long getId() { - return id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getCpu() { - return cpu; - } - - public void setCpu(int cpu) { - this.cpu = cpu; - } - - public void setSpeed(int speed) { - this.speed = speed; - } - - public void setRamSize(int ramSize) { - this.ramSize = ramSize; - } - - public int getSpeed() { - return speed; - } - - public int getRamSize() { - return ramSize; - } - - public Date getCreated() { - return created; - } - - public Date getRemoved() { - return removed; - } - - public void setMirroredVolumes(boolean mirroredVolumes) { - this.mirroredVolumes = mirroredVolumes; - } - - public boolean isMirroredVolumes() { - return mirroredVolumes; - } - - public String getDisplayText() { - return displayText; - } - - public void setDisplayText(String displayText) { - this.displayText = displayText; - } - - public void setRateMbps(int rateMbps) { - this.rateMbps = rateMbps; - } - - public int getRateMbps() { - return rateMbps; - } - - public void setMulticastRateMbps(int multicastRateMbps) { - this.multicastRateMbps = multicastRateMbps; - } - - public int getMulticastRateMbps() { - return multicastRateMbps; - } - - public void setGuestIpType(Vlan.VlanType guestIpType) { - this.guestIpType = guestIpType; - } - - public Vlan.VlanType getGuestIpType() { - return guestIpType; - } - - public boolean getUseLocalStorage() { - return useLocalStorage; - } -} + +@Entity +@Table(name="service_offering") +public class ServiceOffering20VO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id = null; + + @Column(name="name") + private String name = null; + + @Column(name="cpu") + private int cpu; + + @Column(name="speed") + private int speed; + + @Column(name="ram_size") + private int ramSize; + + @Column(name="nw_rate") + private int rateMbps; + + @Column(name="mc_rate") + private int multicastRateMbps; + + @Column(name="mirrored") + private boolean mirroredVolumes; + + @Column(name="ha_enabled") + private boolean offerHA; + + @Column(name="display_text") + private String displayText = null; + + @Column(name="guest_ip_type") + @Enumerated(EnumType.STRING) + private Vlan.VlanType guestIpType = Vlan.VlanType.VirtualNetwork; + + @Column(name="use_local_storage") + private boolean useLocalStorage; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + protected ServiceOffering20VO() { + } + + public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, boolean localStorageRequired) { + this(id, name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, Vlan.VlanType.VirtualNetwork, localStorageRequired); + } + + public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, VlanType guestIpType, boolean useLocalStorage) { + this.id = id; + this.name = name; + this.cpu = cpu; + this.ramSize = ramSize; + this.speed = speed; + this.rateMbps = rateMbps; + this.multicastRateMbps = multicastRateMbps; + this.offerHA = offerHA; + this.displayText = displayText; + this.guestIpType = guestIpType; + this.useLocalStorage = useLocalStorage; + } + + public boolean getOfferHA() { + return offerHA; + } + + public void setOfferHA(boolean offerHA) { + this.offerHA = offerHA; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getCpu() { + return cpu; + } + + public void setCpu(int cpu) { + this.cpu = cpu; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + + public void setRamSize(int ramSize) { + this.ramSize = ramSize; + } + + public int getSpeed() { + return speed; + } + + public int getRamSize() { + return ramSize; + } + + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } + + public void setMirroredVolumes(boolean mirroredVolumes) { + this.mirroredVolumes = mirroredVolumes; + } + + public boolean isMirroredVolumes() { + return mirroredVolumes; + } + + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public void setRateMbps(int rateMbps) { + this.rateMbps = rateMbps; + } + + public int getRateMbps() { + return rateMbps; + } + + public void setMulticastRateMbps(int multicastRateMbps) { + this.multicastRateMbps = multicastRateMbps; + } + + public int getMulticastRateMbps() { + return multicastRateMbps; + } + + public void setGuestIpType(Vlan.VlanType guestIpType) { + this.guestIpType = guestIpType; + } + + public Vlan.VlanType getGuestIpType() { + return guestIpType; + } + + public boolean getUseLocalStorage() { + return useLocalStorage; + } +} diff --git a/server/src/com/cloud/migration/ServiceOffering21Dao.java b/server/src/com/cloud/migration/ServiceOffering21Dao.java index eea0d410b5f..c2c3286481c 100644 --- a/server/src/com/cloud/migration/ServiceOffering21Dao.java +++ b/server/src/com/cloud/migration/ServiceOffering21Dao.java @@ -10,9 +10,9 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import com.cloud.utils.db.GenericDao; - -public interface ServiceOffering21Dao extends GenericDao { -} +package com.cloud.migration; + +import com.cloud.utils.db.GenericDao; + +public interface ServiceOffering21Dao extends GenericDao { +} diff --git a/server/src/com/cloud/migration/ServiceOffering21DaoImpl.java b/server/src/com/cloud/migration/ServiceOffering21DaoImpl.java index 31cae64cfb3..9aaa3a9476a 100644 --- a/server/src/com/cloud/migration/ServiceOffering21DaoImpl.java +++ b/server/src/com/cloud/migration/ServiceOffering21DaoImpl.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - -import javax.ejb.Local; - -import com.cloud.utils.db.GenericDaoBase; - -@Local(value={ServiceOffering21Dao.class}) -public class ServiceOffering21DaoImpl extends GenericDaoBase implements ServiceOffering21Dao { -} +package com.cloud.migration; + +import javax.ejb.Local; + +import com.cloud.utils.db.GenericDaoBase; + +@Local(value={ServiceOffering21Dao.class}) +public class ServiceOffering21DaoImpl extends GenericDaoBase implements ServiceOffering21Dao { +} diff --git a/server/src/com/cloud/migration/ServiceOffering21VO.java b/server/src/com/cloud/migration/ServiceOffering21VO.java index b7a57349a94..f8b8f85fe55 100644 --- a/server/src/com/cloud/migration/ServiceOffering21VO.java +++ b/server/src/com/cloud/migration/ServiceOffering21VO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.migration; - +package com.cloud.migration; + import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -20,133 +20,133 @@ import javax.persistence.Table; import javax.persistence.Transient; import com.cloud.offering.ServiceOffering; - -@Entity -@Table(name="service_offering_21") -@DiscriminatorValue(value="Service") -@PrimaryKeyJoinColumn(name="id") -public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffering { - @Column(name="cpu") - private int cpu; - - @Column(name="speed") - private int speed; - - @Column(name="ram_size") - private int ramSize; - - @Column(name="nw_rate") - private Integer rateMbps; - - @Column(name="mc_rate") - private Integer multicastRateMbps; - - @Column(name="ha_enabled") - private boolean offerHA; - - @Column(name="host_tag") + +@Entity +@Table(name="service_offering_21") +@DiscriminatorValue(value="Service") +@PrimaryKeyJoinColumn(name="id") +public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffering { + @Column(name="cpu") + private int cpu; + + @Column(name="speed") + private int speed; + + @Column(name="ram_size") + private int ramSize; + + @Column(name="nw_rate") + private Integer rateMbps; + + @Column(name="mc_rate") + private Integer multicastRateMbps; + + @Column(name="ha_enabled") + private boolean offerHA; + + @Column(name="host_tag") private String hostTag; - - protected ServiceOffering21VO() { - super(); - } - - public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags) { - super(name, displayText, false, tags, recreatable, useLocalStorage); - this.cpu = cpu; - this.ramSize = ramSize; - this.speed = speed; - this.rateMbps = rateMbps; - this.multicastRateMbps = multicastRateMbps; - this.offerHA = offerHA; - } - - public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) { - this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, useLocalStorage, recreatable, tags); - this.hostTag = hostTag; + + protected ServiceOffering21VO() { + super(); } - - - @Override - public boolean getOfferHA() { - return offerHA; - } + + public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags) { + super(name, displayText, false, tags, recreatable, useLocalStorage); + this.cpu = cpu; + this.ramSize = ramSize; + this.speed = speed; + this.rateMbps = rateMbps; + this.multicastRateMbps = multicastRateMbps; + this.offerHA = offerHA; + } + + public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) { + this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, useLocalStorage, recreatable, tags); + this.hostTag = hostTag; + } + + + @Override + public boolean getOfferHA() { + return offerHA; + } @Override public boolean getLimitCpuUse() { return false; } - - public void setOfferHA(boolean offerHA) { - this.offerHA = offerHA; - } - - @Override - @Transient - public String[] getTagsArray() { - String tags = getTags(); - if (tags == null || tags.length() == 0) { - return new String[0]; - } - - return tags.split(","); - } - - @Override - public int getCpu() { - return cpu; - } - - public void setCpu(int cpu) { - this.cpu = cpu; - } - - public void setSpeed(int speed) { - this.speed = speed; - } - - public void setRamSize(int ramSize) { - this.ramSize = ramSize; - } - - @Override - public int getSpeed() { - return speed; - } - - @Override - public int getRamSize() { - return ramSize; - } - - public void setRateMbps(Integer rateMbps) { - this.rateMbps = rateMbps; - } - - @Override - public Integer getRateMbps() { - return rateMbps; - } - - public void setMulticastRateMbps(Integer multicastRateMbps) { - this.multicastRateMbps = multicastRateMbps; - } - - @Override - public Integer getMulticastRateMbps() { - return multicastRateMbps; - } - - public String gethypervisorType() { - return null; - } - - public void setHostTag(String hostTag) { - this.hostTag = hostTag; - } - - public String getHostTag() { - return hostTag; + + public void setOfferHA(boolean offerHA) { + this.offerHA = offerHA; + } + + @Override + @Transient + public String[] getTagsArray() { + String tags = getTags(); + if (tags == null || tags.length() == 0) { + return new String[0]; + } + + return tags.split(","); + } + + @Override + public int getCpu() { + return cpu; + } + + public void setCpu(int cpu) { + this.cpu = cpu; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + + public void setRamSize(int ramSize) { + this.ramSize = ramSize; + } + + @Override + public int getSpeed() { + return speed; + } + + @Override + public int getRamSize() { + return ramSize; + } + + public void setRateMbps(Integer rateMbps) { + this.rateMbps = rateMbps; + } + + @Override + public Integer getRateMbps() { + return rateMbps; + } + + public void setMulticastRateMbps(Integer multicastRateMbps) { + this.multicastRateMbps = multicastRateMbps; + } + + @Override + public Integer getMulticastRateMbps() { + return multicastRateMbps; + } + + public String gethypervisorType() { + return null; + } + + public void setHostTag(String hostTag) { + this.hostTag = hostTag; + } + + public String getHostTag() { + return hostTag; } @Override @@ -157,5 +157,5 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe @Override public String getSystemVmType() { return null; - } -} + } +} diff --git a/server/src/com/cloud/network/ExternalLoadBalancerUsageManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerUsageManagerImpl.java index 3480fa7fcc3..e6c47c4cb48 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerUsageManagerImpl.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerUsageManagerImpl.java @@ -10,549 +10,549 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -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.ExternalNetworkResourceUsageAnswer; -import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; -import com.cloud.configuration.Config; -import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.VlanDao; -import com.cloud.host.DetailVO; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.dao.ExternalFirewallDeviceDao; -import com.cloud.network.dao.ExternalLoadBalancerDeviceDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.InlineLoadBalancerNicMapDao; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkExternalFirewallDao; -import com.cloud.network.dao.NetworkExternalLoadBalancerDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.rules.dao.PortForwardingRulesDao; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.resource.ResourceManager; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.UserStatisticsVO; -import com.cloud.user.dao.AccountDao; -import com.cloud.user.dao.UserStatisticsDao; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.Inject; -import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.exception.ExecutionException; -import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.NicVO; -import com.cloud.vm.dao.DomainRouterDao; -import com.cloud.vm.dao.NicDao; - -@Local(value = { ExternalLoadBalancerUsageManager.class }) -public class ExternalLoadBalancerUsageManagerImpl implements ExternalLoadBalancerUsageManager { - - String _name; - @Inject - NetworkExternalLoadBalancerDao _networkExternalLBDao; - @Inject - ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; - @Inject - HostDao _hostDao; - @Inject - DataCenterDao _dcDao; - @Inject - NetworkManager _networkMgr; - @Inject - InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; - @Inject - NicDao _nicDao; - @Inject - AgentManager _agentMgr; - @Inject - ResourceManager _resourceMgr; - @Inject - IPAddressDao _ipAddressDao; - @Inject - VlanDao _vlanDao; - @Inject - NetworkOfferingDao _networkOfferingDao; - @Inject - AccountDao _accountDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - @Inject - AccountManager _accountMgr; - @Inject - UserStatisticsDao _userStatsDao; - @Inject - NetworkDao _networkDao; - @Inject - DomainRouterDao _routerDao; - @Inject - LoadBalancerDao _loadBalancerDao; - @Inject - PortForwardingRulesDao _portForwardingRulesDao; - @Inject - ConfigurationDao _configDao; - @Inject - HostDetailsDao _hostDetailDao; - @Inject - NetworkExternalLoadBalancerDao _networkLBDao; - @Inject - NetworkServiceMapDao _ntwkSrvcProviderDao; - @Inject - NetworkExternalFirewallDao _networkExternalFirewallDao; - @Inject - ExternalFirewallDeviceDao _externalFirewallDeviceDao; - @Inject - protected HostPodDao _podDao = null; - - ScheduledExecutorService _executor; - private int _externalNetworkStatsInterval; - private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerUsageManagerImpl.class); - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ExternalNetworkStatsInterval.key()), 300); - if (_externalNetworkStatsInterval > 0) { - _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor")); - } - return true; - - } - - @Override - public boolean start() { - if (_externalNetworkStatsInterval > 0) { - _executor.scheduleAtFixedRate(new ExternalLoadBalancerDeviceNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS); - } - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - private ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { - NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); - if (lbDeviceForNetwork != null) { - long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); - ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); - assert (lbDeviceVo != null); - return lbDeviceVo; - } - return null; - } - - private boolean externalLoadBalancerIsInline(HostVO externalLoadBalancer) { - DetailVO detail = _hostDetailDao.findDetail(externalLoadBalancer.getId(), "inline"); - return (detail != null && detail.getValue().equals("true")); - } - - @Override - public void updateExternalLoadBalancerNetworkUsageStats(long loadBalancerRuleId){ - - LoadBalancerVO lb = _loadBalancerDao.findById(loadBalancerRuleId); - if(lb == null){ - if(s_logger.isDebugEnabled()){ - s_logger.debug("Cannot update usage stats, LB rule is not found"); - } - return; - } - long networkId = lb.getNetworkId(); - Network network = _networkDao.findById(networkId); - if(network == null){ - if(s_logger.isDebugEnabled()){ - s_logger.debug("Cannot update usage stats, Network is not found"); - } - return; - } - ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); - if (lbDeviceVO == null) { - if(s_logger.isDebugEnabled()){ - s_logger.debug("Cannot update usage stats, No external LB device found"); - } - return; - } - - // Get network stats from the external load balancer - ExternalNetworkResourceUsageAnswer lbAnswer = null; - HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); - if (externalLoadBalancer != null) { - ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); - lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); - if (lbAnswer == null || !lbAnswer.getResult()) { - String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; - String msg = "Unable to get external load balancer stats for network" + networkId + " due to: " + details + "."; - s_logger.error(msg); - return; - } - } - - long accountId = lb.getAccountId(); - AccountVO account = _accountDao.findById(accountId); - if (account == null) { - s_logger.debug("Skipping stats update for external LB for account with ID " + accountId); - return; - } - - String publicIp = _networkMgr.getIp(lb.getSourceIpAddressId()).getAddress().addr(); - DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); - String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + externalLoadBalancer.getName(); - - long newCurrentBytesSent = 0; - long newCurrentBytesReceived = 0; - - if (publicIp != null) { - long[] bytesSentAndReceived = null; - statsEntryIdentifier += ", public IP: " + publicIp; - - if (externalLoadBalancer.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(externalLoadBalancer)) { - // Look up stats for the guest IP address that's mapped to the public IP address - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); - - if (mapping != null) { - NicVO nic = _nicDao.findById(mapping.getNicId()); - String loadBalancingIpAddress = nic.getIp4Address(); - bytesSentAndReceived = lbAnswer.ipBytes.get(loadBalancingIpAddress); - - if (bytesSentAndReceived != null) { - bytesSentAndReceived[0] = 0; - } - } - } else { - bytesSentAndReceived = lbAnswer.ipBytes.get(publicIp); - } - - if (bytesSentAndReceived == null) { - s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); - } else { - newCurrentBytesSent += bytesSentAndReceived[0]; - newCurrentBytesReceived += bytesSentAndReceived[1]; - } - - UserStatisticsVO userStats; - final Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - userStats = _userStatsDao.lock(accountId, zone.getId(), networkId, publicIp, externalLoadBalancer.getId(), externalLoadBalancer.getType().toString()); - - if(userStats != null){ - long oldNetBytesSent = userStats.getNetBytesSent(); - long oldNetBytesReceived = userStats.getNetBytesReceived(); - long oldCurrentBytesSent = userStats.getCurrentBytesSent(); - long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); - String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; - - userStats.setCurrentBytesSent(newCurrentBytesSent); - if (oldCurrentBytesSent > newCurrentBytesSent) { - s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); - userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); - } - - userStats.setCurrentBytesReceived(newCurrentBytesReceived); - if (oldCurrentBytesReceived > newCurrentBytesReceived) { - s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); - userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); - } - - if (_userStatsDao.update(userStats.getId(), userStats)) { - s_logger.debug("Successfully updated stats for " + statsEntryIdentifier); - } else { - s_logger.debug("Failed to update stats for " + statsEntryIdentifier); - } - }else { - s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); - } - - txn.commit(); - }catch (final Exception e) { - txn.rollback(); - throw new CloudRuntimeException("Problem getting stats after reboot/stop ", e); - } - } - } - - protected class ExternalLoadBalancerDeviceNetworkUsageTask implements Runnable { - - public ExternalLoadBalancerDeviceNetworkUsageTask() { - - } - - @Override - public void run() { - GlobalLock scanLock = GlobalLock.getInternLock("ExternalLoadBalancerUsageManagerImpl"); - try { - if (scanLock.lock(20)) { - try { - runExternalLoadBalancerNetworkUsageTask(); - } finally { - scanLock.unlock(); - } - } - } catch (Exception e) { - s_logger.warn("Problems while getting external load balancer device usage", e); - } finally { - scanLock.releaseRef(); - } - } - - private void runExternalLoadBalancerNetworkUsageTask() { - s_logger.debug("External load balancer devices stats collector is running..."); - - for (DataCenterVO zone : _dcDao.listAll()) { - List domainRoutersInZone = _routerDao.listByDataCenter(zone.getId()); - if (domainRoutersInZone == null) { - continue; - } - Map lbDeviceUsageAnswerMap = new HashMap(); - List accountsProcessed = new ArrayList(); - - for (DomainRouterVO domainRouter : domainRoutersInZone) { - long accountId = domainRouter.getAccountId(); - - if (accountsProcessed.contains(new Long(accountId))) { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Networks for Account " + accountId + " are already processed for external network usage, so skipping usage check."); - } - continue; - } - - long zoneId = zone.getId(); - - List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestType.Isolated); - if (networksForAccount == null) { - continue; - } - - for (NetworkVO network : networksForAccount) { - if (!_networkMgr.networkIsConfiguredForExternalNetworking(zoneId, network.getId())) { - s_logger.debug("Network " + network.getId() + " is not configured for external networking, so skipping usage check."); - continue; - } - - ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); - if (lbDeviceVO == null) { - continue; - } - - // Get network stats from the external load balancer - ExternalNetworkResourceUsageAnswer lbAnswer = null; - HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); - if (externalLoadBalancer != null) { - Long lbDeviceId = new Long(externalLoadBalancer.getId()); - if (!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)) { - ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); - lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); - if (lbAnswer == null || !lbAnswer.getResult()) { - String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; - String msg = "Unable to get external load balancer stats for " + zone.getName() + " due to: " + details + "."; - s_logger.error(msg); - continue; - } - lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer); - } else { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Reusing usage Answer for device id " + lbDeviceId + "for Network " + network.getId()); - } - lbAnswer = lbDeviceUsageAnswerMap.get(lbDeviceId); - } - } - - AccountVO account = _accountDao.findById(accountId); - if (account == null) { - s_logger.debug("Skipping stats update for account with ID " + accountId); - continue; - } - - if (!manageStatsEntries(true, accountId, zoneId, network, externalLoadBalancer, lbAnswer)) { - continue; - } - - manageStatsEntries(false, accountId, zoneId, network, externalLoadBalancer, lbAnswer); - } - - accountsProcessed.add(new Long(accountId)); - } - } - } - - private boolean updateBytes(UserStatisticsVO userStats, long newCurrentBytesSent, long newCurrentBytesReceived) { - long oldNetBytesSent = userStats.getNetBytesSent(); - long oldNetBytesReceived = userStats.getNetBytesReceived(); - long oldCurrentBytesSent = userStats.getCurrentBytesSent(); - long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); - String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; - - userStats.setCurrentBytesSent(newCurrentBytesSent); - if (oldCurrentBytesSent > newCurrentBytesSent) { - s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); - userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); - } - - userStats.setCurrentBytesReceived(newCurrentBytesReceived); - if (oldCurrentBytesReceived > newCurrentBytesReceived) { - s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); - userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); - } - - return _userStatsDao.update(userStats.getId(), userStats); - } - - // Creates a new stats entry for the specified parameters, if one doesn't already exist. - private boolean createStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId) { - HostVO host = _hostDao.findById(hostId); - UserStatisticsVO userStats = _userStatsDao.findBy(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); - if (userStats == null) { - return (_userStatsDao.persist(new UserStatisticsVO(accountId, zoneId, publicIp, hostId, host.getType().toString(), networkId)) != null); - } else { - return true; - } - } - - // Updates an existing stats entry with new data from the specified usage answer. - private boolean updateStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { - AccountVO account = _accountDao.findById(accountId); - DataCenterVO zone = _dcDao.findById(zoneId); - NetworkVO network = _networkDao.findById(networkId); - HostVO host = _hostDao.findById(hostId); - String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + host.getName(); - - long newCurrentBytesSent = 0; - long newCurrentBytesReceived = 0; - - if (publicIp != null) { - long[] bytesSentAndReceived = null; - statsEntryIdentifier += ", public IP: " + publicIp; - - if (host.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(host)) { - // Look up stats for the guest IP address that's mapped to the public IP address - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); - - if (mapping != null) { - NicVO nic = _nicDao.findById(mapping.getNicId()); - String loadBalancingIpAddress = nic.getIp4Address(); - bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress); - - if (bytesSentAndReceived != null) { - bytesSentAndReceived[0] = 0; - } - } - } else { - bytesSentAndReceived = answer.ipBytes.get(publicIp); - } - - if (bytesSentAndReceived == null) { - s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); - } else { - newCurrentBytesSent += bytesSentAndReceived[0]; - newCurrentBytesReceived += bytesSentAndReceived[1]; - } - } else { - URI broadcastURI = network.getBroadcastUri(); - if (broadcastURI == null) { - s_logger.debug("Not updating stats for guest network with ID " + network.getId() + " because the network is not implemented."); - return true; - } else { - long vlanTag = Integer.parseInt(broadcastURI.getHost()); - long[] bytesSentAndReceived = answer.guestVlanBytes.get(String.valueOf(vlanTag)); - - if (bytesSentAndReceived == null) { - s_logger.warn("Didn't get an external network usage answer for guest VLAN " + vlanTag); - } else { - newCurrentBytesSent += bytesSentAndReceived[0]; - newCurrentBytesReceived += bytesSentAndReceived[1]; - } - } - } - - UserStatisticsVO userStats; - try { - userStats = _userStatsDao.lock(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); - } catch (Exception e) { - s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); - return false; - } - - if (updateBytes(userStats, newCurrentBytesSent, newCurrentBytesReceived)) { - s_logger.debug("Successfully updated stats for " + statsEntryIdentifier); - return true; - } else { - s_logger.debug("Failed to update stats for " + statsEntryIdentifier); - return false; - } - } - - private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { - if (create) { - return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId); - } else { - return updateStatsEntry(accountId, zoneId, networkId, publicIp, hostId, answer); - } - } - - /* - * Creates/updates all necessary stats entries for an account and zone. - * Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load - * balancing rules - */ - private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network, - HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { - String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId; - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - txn.start(); - String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); - - // If an external load balancer is added, manage one entry for each load balancing rule in this network - if (externalLoadBalancer != null && lbAnswer != null) { - List loadBalancers = _loadBalancerDao.listByNetworkId(network.getId()); - for (LoadBalancerVO loadBalancer : loadBalancers) { - String publicIp = _networkMgr.getIp(loadBalancer.getSourceIpAddressId()).getAddress().addr(); - if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalLoadBalancer.getId(), lbAnswer)) { - throw new ExecutionException(networkErrorMsg + ", load balancing rule public IP = " + publicIp); - } - } - } - return txn.commit(); - } catch (Exception e) { - s_logger.warn("Exception: ", e); - txn.rollback(); - return false; - } finally { - txn.close(); - } - } - } -} +package com.cloud.network; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +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.ExternalNetworkResourceUsageAnswer; +import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.dc.dao.HostPodDao; +import com.cloud.dc.dao.VlanDao; +import com.cloud.host.DetailVO; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.host.dao.HostDetailsDao; +import com.cloud.network.dao.ExternalFirewallDeviceDao; +import com.cloud.network.dao.ExternalLoadBalancerDeviceDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.InlineLoadBalancerNicMapDao; +import com.cloud.network.dao.LoadBalancerDao; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkExternalFirewallDao; +import com.cloud.network.dao.NetworkExternalLoadBalancerDao; +import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.rules.dao.PortForwardingRulesDao; +import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.resource.ResourceManager; +import com.cloud.user.AccountManager; +import com.cloud.user.AccountVO; +import com.cloud.user.UserStatisticsVO; +import com.cloud.user.dao.AccountDao; +import com.cloud.user.dao.UserStatisticsDao; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.component.Inject; +import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.exception.ExecutionException; +import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.NicVO; +import com.cloud.vm.dao.DomainRouterDao; +import com.cloud.vm.dao.NicDao; + +@Local(value = { ExternalLoadBalancerUsageManager.class }) +public class ExternalLoadBalancerUsageManagerImpl implements ExternalLoadBalancerUsageManager { + + String _name; + @Inject + NetworkExternalLoadBalancerDao _networkExternalLBDao; + @Inject + ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; + @Inject + HostDao _hostDao; + @Inject + DataCenterDao _dcDao; + @Inject + NetworkManager _networkMgr; + @Inject + InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; + @Inject + NicDao _nicDao; + @Inject + AgentManager _agentMgr; + @Inject + ResourceManager _resourceMgr; + @Inject + IPAddressDao _ipAddressDao; + @Inject + VlanDao _vlanDao; + @Inject + NetworkOfferingDao _networkOfferingDao; + @Inject + AccountDao _accountDao; + @Inject + PhysicalNetworkDao _physicalNetworkDao; + @Inject + PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; + @Inject + AccountManager _accountMgr; + @Inject + UserStatisticsDao _userStatsDao; + @Inject + NetworkDao _networkDao; + @Inject + DomainRouterDao _routerDao; + @Inject + LoadBalancerDao _loadBalancerDao; + @Inject + PortForwardingRulesDao _portForwardingRulesDao; + @Inject + ConfigurationDao _configDao; + @Inject + HostDetailsDao _hostDetailDao; + @Inject + NetworkExternalLoadBalancerDao _networkLBDao; + @Inject + NetworkServiceMapDao _ntwkSrvcProviderDao; + @Inject + NetworkExternalFirewallDao _networkExternalFirewallDao; + @Inject + ExternalFirewallDeviceDao _externalFirewallDeviceDao; + @Inject + protected HostPodDao _podDao = null; + + ScheduledExecutorService _executor; + private int _externalNetworkStatsInterval; + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerUsageManagerImpl.class); + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ExternalNetworkStatsInterval.key()), 300); + if (_externalNetworkStatsInterval > 0) { + _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor")); + } + return true; + + } + + @Override + public boolean start() { + if (_externalNetworkStatsInterval > 0) { + _executor.scheduleAtFixedRate(new ExternalLoadBalancerDeviceNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS); + } + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + private ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { + NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); + if (lbDeviceForNetwork != null) { + long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); + ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); + assert (lbDeviceVo != null); + return lbDeviceVo; + } + return null; + } + + private boolean externalLoadBalancerIsInline(HostVO externalLoadBalancer) { + DetailVO detail = _hostDetailDao.findDetail(externalLoadBalancer.getId(), "inline"); + return (detail != null && detail.getValue().equals("true")); + } + + @Override + public void updateExternalLoadBalancerNetworkUsageStats(long loadBalancerRuleId){ + + LoadBalancerVO lb = _loadBalancerDao.findById(loadBalancerRuleId); + if(lb == null){ + if(s_logger.isDebugEnabled()){ + s_logger.debug("Cannot update usage stats, LB rule is not found"); + } + return; + } + long networkId = lb.getNetworkId(); + Network network = _networkDao.findById(networkId); + if(network == null){ + if(s_logger.isDebugEnabled()){ + s_logger.debug("Cannot update usage stats, Network is not found"); + } + return; + } + ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); + if (lbDeviceVO == null) { + if(s_logger.isDebugEnabled()){ + s_logger.debug("Cannot update usage stats, No external LB device found"); + } + return; + } + + // Get network stats from the external load balancer + ExternalNetworkResourceUsageAnswer lbAnswer = null; + HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); + if (externalLoadBalancer != null) { + ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); + lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); + if (lbAnswer == null || !lbAnswer.getResult()) { + String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; + String msg = "Unable to get external load balancer stats for network" + networkId + " due to: " + details + "."; + s_logger.error(msg); + return; + } + } + + long accountId = lb.getAccountId(); + AccountVO account = _accountDao.findById(accountId); + if (account == null) { + s_logger.debug("Skipping stats update for external LB for account with ID " + accountId); + return; + } + + String publicIp = _networkMgr.getIp(lb.getSourceIpAddressId()).getAddress().addr(); + DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); + String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + externalLoadBalancer.getName(); + + long newCurrentBytesSent = 0; + long newCurrentBytesReceived = 0; + + if (publicIp != null) { + long[] bytesSentAndReceived = null; + statsEntryIdentifier += ", public IP: " + publicIp; + + if (externalLoadBalancer.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(externalLoadBalancer)) { + // Look up stats for the guest IP address that's mapped to the public IP address + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); + + if (mapping != null) { + NicVO nic = _nicDao.findById(mapping.getNicId()); + String loadBalancingIpAddress = nic.getIp4Address(); + bytesSentAndReceived = lbAnswer.ipBytes.get(loadBalancingIpAddress); + + if (bytesSentAndReceived != null) { + bytesSentAndReceived[0] = 0; + } + } + } else { + bytesSentAndReceived = lbAnswer.ipBytes.get(publicIp); + } + + if (bytesSentAndReceived == null) { + s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); + } else { + newCurrentBytesSent += bytesSentAndReceived[0]; + newCurrentBytesReceived += bytesSentAndReceived[1]; + } + + UserStatisticsVO userStats; + final Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + userStats = _userStatsDao.lock(accountId, zone.getId(), networkId, publicIp, externalLoadBalancer.getId(), externalLoadBalancer.getType().toString()); + + if(userStats != null){ + long oldNetBytesSent = userStats.getNetBytesSent(); + long oldNetBytesReceived = userStats.getNetBytesReceived(); + long oldCurrentBytesSent = userStats.getCurrentBytesSent(); + long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); + String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; + + userStats.setCurrentBytesSent(newCurrentBytesSent); + if (oldCurrentBytesSent > newCurrentBytesSent) { + s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); + userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); + } + + userStats.setCurrentBytesReceived(newCurrentBytesReceived); + if (oldCurrentBytesReceived > newCurrentBytesReceived) { + s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); + userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); + } + + if (_userStatsDao.update(userStats.getId(), userStats)) { + s_logger.debug("Successfully updated stats for " + statsEntryIdentifier); + } else { + s_logger.debug("Failed to update stats for " + statsEntryIdentifier); + } + }else { + s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); + } + + txn.commit(); + }catch (final Exception e) { + txn.rollback(); + throw new CloudRuntimeException("Problem getting stats after reboot/stop ", e); + } + } + } + + protected class ExternalLoadBalancerDeviceNetworkUsageTask implements Runnable { + + public ExternalLoadBalancerDeviceNetworkUsageTask() { + + } + + @Override + public void run() { + GlobalLock scanLock = GlobalLock.getInternLock("ExternalLoadBalancerUsageManagerImpl"); + try { + if (scanLock.lock(20)) { + try { + runExternalLoadBalancerNetworkUsageTask(); + } finally { + scanLock.unlock(); + } + } + } catch (Exception e) { + s_logger.warn("Problems while getting external load balancer device usage", e); + } finally { + scanLock.releaseRef(); + } + } + + private void runExternalLoadBalancerNetworkUsageTask() { + s_logger.debug("External load balancer devices stats collector is running..."); + + for (DataCenterVO zone : _dcDao.listAll()) { + List domainRoutersInZone = _routerDao.listByDataCenter(zone.getId()); + if (domainRoutersInZone == null) { + continue; + } + Map lbDeviceUsageAnswerMap = new HashMap(); + List accountsProcessed = new ArrayList(); + + for (DomainRouterVO domainRouter : domainRoutersInZone) { + long accountId = domainRouter.getAccountId(); + + if (accountsProcessed.contains(new Long(accountId))) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Networks for Account " + accountId + " are already processed for external network usage, so skipping usage check."); + } + continue; + } + + long zoneId = zone.getId(); + + List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestType.Isolated); + if (networksForAccount == null) { + continue; + } + + for (NetworkVO network : networksForAccount) { + if (!_networkMgr.networkIsConfiguredForExternalNetworking(zoneId, network.getId())) { + s_logger.debug("Network " + network.getId() + " is not configured for external networking, so skipping usage check."); + continue; + } + + ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); + if (lbDeviceVO == null) { + continue; + } + + // Get network stats from the external load balancer + ExternalNetworkResourceUsageAnswer lbAnswer = null; + HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); + if (externalLoadBalancer != null) { + Long lbDeviceId = new Long(externalLoadBalancer.getId()); + if (!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)) { + ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); + lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); + if (lbAnswer == null || !lbAnswer.getResult()) { + String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; + String msg = "Unable to get external load balancer stats for " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + continue; + } + lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer); + } else { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Reusing usage Answer for device id " + lbDeviceId + "for Network " + network.getId()); + } + lbAnswer = lbDeviceUsageAnswerMap.get(lbDeviceId); + } + } + + AccountVO account = _accountDao.findById(accountId); + if (account == null) { + s_logger.debug("Skipping stats update for account with ID " + accountId); + continue; + } + + if (!manageStatsEntries(true, accountId, zoneId, network, externalLoadBalancer, lbAnswer)) { + continue; + } + + manageStatsEntries(false, accountId, zoneId, network, externalLoadBalancer, lbAnswer); + } + + accountsProcessed.add(new Long(accountId)); + } + } + } + + private boolean updateBytes(UserStatisticsVO userStats, long newCurrentBytesSent, long newCurrentBytesReceived) { + long oldNetBytesSent = userStats.getNetBytesSent(); + long oldNetBytesReceived = userStats.getNetBytesReceived(); + long oldCurrentBytesSent = userStats.getCurrentBytesSent(); + long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); + String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; + + userStats.setCurrentBytesSent(newCurrentBytesSent); + if (oldCurrentBytesSent > newCurrentBytesSent) { + s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); + userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); + } + + userStats.setCurrentBytesReceived(newCurrentBytesReceived); + if (oldCurrentBytesReceived > newCurrentBytesReceived) { + s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); + userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); + } + + return _userStatsDao.update(userStats.getId(), userStats); + } + + // Creates a new stats entry for the specified parameters, if one doesn't already exist. + private boolean createStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId) { + HostVO host = _hostDao.findById(hostId); + UserStatisticsVO userStats = _userStatsDao.findBy(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); + if (userStats == null) { + return (_userStatsDao.persist(new UserStatisticsVO(accountId, zoneId, publicIp, hostId, host.getType().toString(), networkId)) != null); + } else { + return true; + } + } + + // Updates an existing stats entry with new data from the specified usage answer. + private boolean updateStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { + AccountVO account = _accountDao.findById(accountId); + DataCenterVO zone = _dcDao.findById(zoneId); + NetworkVO network = _networkDao.findById(networkId); + HostVO host = _hostDao.findById(hostId); + String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + host.getName(); + + long newCurrentBytesSent = 0; + long newCurrentBytesReceived = 0; + + if (publicIp != null) { + long[] bytesSentAndReceived = null; + statsEntryIdentifier += ", public IP: " + publicIp; + + if (host.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(host)) { + // Look up stats for the guest IP address that's mapped to the public IP address + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); + + if (mapping != null) { + NicVO nic = _nicDao.findById(mapping.getNicId()); + String loadBalancingIpAddress = nic.getIp4Address(); + bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress); + + if (bytesSentAndReceived != null) { + bytesSentAndReceived[0] = 0; + } + } + } else { + bytesSentAndReceived = answer.ipBytes.get(publicIp); + } + + if (bytesSentAndReceived == null) { + s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); + } else { + newCurrentBytesSent += bytesSentAndReceived[0]; + newCurrentBytesReceived += bytesSentAndReceived[1]; + } + } else { + URI broadcastURI = network.getBroadcastUri(); + if (broadcastURI == null) { + s_logger.debug("Not updating stats for guest network with ID " + network.getId() + " because the network is not implemented."); + return true; + } else { + long vlanTag = Integer.parseInt(broadcastURI.getHost()); + long[] bytesSentAndReceived = answer.guestVlanBytes.get(String.valueOf(vlanTag)); + + if (bytesSentAndReceived == null) { + s_logger.warn("Didn't get an external network usage answer for guest VLAN " + vlanTag); + } else { + newCurrentBytesSent += bytesSentAndReceived[0]; + newCurrentBytesReceived += bytesSentAndReceived[1]; + } + } + } + + UserStatisticsVO userStats; + try { + userStats = _userStatsDao.lock(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); + } catch (Exception e) { + s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); + return false; + } + + if (updateBytes(userStats, newCurrentBytesSent, newCurrentBytesReceived)) { + s_logger.debug("Successfully updated stats for " + statsEntryIdentifier); + return true; + } else { + s_logger.debug("Failed to update stats for " + statsEntryIdentifier); + return false; + } + } + + private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { + if (create) { + return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId); + } else { + return updateStatsEntry(accountId, zoneId, networkId, publicIp, hostId, answer); + } + } + + /* + * Creates/updates all necessary stats entries for an account and zone. + * Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load + * balancing rules + */ + private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network, + HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { + String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId; + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + txn.start(); + String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); + + // If an external load balancer is added, manage one entry for each load balancing rule in this network + if (externalLoadBalancer != null && lbAnswer != null) { + List loadBalancers = _loadBalancerDao.listByNetworkId(network.getId()); + for (LoadBalancerVO loadBalancer : loadBalancers) { + String publicIp = _networkMgr.getIp(loadBalancer.getSourceIpAddressId()).getAddress().addr(); + if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalLoadBalancer.getId(), lbAnswer)) { + throw new ExecutionException(networkErrorMsg + ", load balancing rule public IP = " + publicIp); + } + } + } + return txn.commit(); + } catch (Exception e) { + s_logger.warn("Exception: ", e); + txn.rollback(); + return false; + } finally { + txn.close(); + } + } + } +} diff --git a/server/src/com/cloud/network/IPAddressVO.java b/server/src/com/cloud/network/IPAddressVO.java index 9ed071f774d..4f9114254d2 100644 --- a/server/src/com/cloud/network/IPAddressVO.java +++ b/server/src/com/cloud/network/IPAddressVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - +package com.cloud.network; + import java.util.Date; import java.util.UUID; @@ -29,42 +29,42 @@ import javax.persistence.Transient; import com.cloud.api.Identity; import com.cloud.utils.net.Ip; - -/** - * A bean representing a public IP Address - * - */ -@Entity -@Table(name=("user_ip_address")) + +/** + * A bean representing a public IP Address + * + */ +@Entity +@Table(name=("user_ip_address")) public class IPAddressVO implements IpAddress, Identity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - - @Column(name="account_id") - private Long allocatedToAccountId = null; - - @Column(name="domain_id") - private Long allocatedInDomainId = null; - - @Id + + @Column(name="account_id") + private Long allocatedToAccountId = null; + + @Column(name="domain_id") + private Long allocatedInDomainId = null; + + @Id @Column(name="public_ip_address") - @Enumerated(value=EnumType.STRING) - private Ip address = null; - - @Column(name="data_center_id", updatable=false) - private long dataCenterId; - - @Column(name="source_nat") - private boolean sourceNat; - - @Column(name="allocated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date allocatedTime; - - @Column(name="vlan_db_id") - private long vlanId; + @Enumerated(value=EnumType.STRING) + private Ip address = null; + + @Column(name="data_center_id", updatable=false) + private long dataCenterId; + + @Column(name="source_nat") + private boolean sourceNat; + + @Column(name="allocated") + @Temporal(value=TemporalType.TIMESTAMP) + private Date allocatedTime; + + @Column(name="vlan_db_id") + private long vlanId; @Column(name="one_to_one_nat") private boolean oneToOneNat; @@ -100,20 +100,20 @@ public class IPAddressVO implements IpAddress, Identity { @Transient @Column(name="domain_id") private Long domainId = null; - + protected IPAddressVO() { - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } @Override public boolean readyToUse() { return state == State.Allocated; - } - - public IPAddressVO(Ip address, long dataCenterId, long macAddress, long vlanDbId, boolean sourceNat) { - this.address = address; - this.dataCenterId = dataCenterId; - this.vlanId = vlanDbId; + } + + public IPAddressVO(Ip address, long dataCenterId, long macAddress, long vlanDbId, boolean sourceNat) { + this.address = address; + this.dataCenterId = dataCenterId; + this.vlanId = vlanDbId; this.sourceNat = sourceNat; this.allocatedInDomainId = null; this.allocatedToAccountId = null; @@ -125,21 +125,21 @@ public class IPAddressVO implements IpAddress, Identity { public long getMacAddress() { return macAddress; - } - - @Override - public long getDataCenterId() { - return dataCenterId; - } - - @Override - public Ip getAddress() { - return address; } - + @Override - public Long getAllocatedToAccountId() { - return allocatedToAccountId; + public long getDataCenterId() { + return dataCenterId; + } + + @Override + public Ip getAddress() { + return address; + } + + @Override + public Long getAllocatedToAccountId() { + return allocatedToAccountId; } @Override @@ -156,7 +156,7 @@ public class IPAddressVO implements IpAddress, Identity { this.associatedWithNetworkId = networkId; } - @Override + @Override public Long getAssociatedWithVmId() { return associatedWithVmId; } @@ -164,40 +164,40 @@ public class IPAddressVO implements IpAddress, Identity { public void setAssociatedWithVmId(Long associatedWithVmId) { this.associatedWithVmId = associatedWithVmId; } - + @Override - public Date getAllocatedTime() { - return allocatedTime; - } - - public void setAllocatedToAccountId(Long accountId) { - this.allocatedToAccountId = accountId; - } - - public void setAllocatedInDomainId(Long domainId) { - this.allocatedInDomainId = domainId; - } - - public void setSourceNat(boolean sourceNat) { - this.sourceNat = sourceNat; + public Date getAllocatedTime() { + return allocatedTime; + } + + public void setAllocatedToAccountId(Long accountId) { + this.allocatedToAccountId = accountId; + } + + public void setAllocatedInDomainId(Long domainId) { + this.allocatedInDomainId = domainId; + } + + public void setSourceNat(boolean sourceNat) { + this.sourceNat = sourceNat; } @Override public boolean isSourceNat() { return sourceNat; - } - - public void setAllocatedTime(Date allocated) { - this.allocatedTime = allocated; - } - + } + + public void setAllocatedTime(Date allocated) { + this.allocatedTime = allocated; + } + @Override - public long getVlanId() { - return this.vlanId; - } - - public void setVlanId(long vlanDbId) { - this.vlanId = vlanDbId; + public long getVlanId() { + return this.vlanId; + } + + public void setVlanId(long vlanDbId) { + this.vlanId = vlanDbId; } @Override @@ -254,7 +254,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setUuid(String uuid) { this.uuid = uuid; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } @@ -271,4 +271,4 @@ public class IPAddressVO implements IpAddress, Identity { public void setSystem(boolean isSystem) { this.system = isSystem; } -} +} diff --git a/server/src/com/cloud/network/LBStickinessPolicyVO.java b/server/src/com/cloud/network/LBStickinessPolicyVO.java index b96be7920f7..6160efa81df 100644 --- a/server/src/com/cloud/network/LBStickinessPolicyVO.java +++ b/server/src/com/cloud/network/LBStickinessPolicyVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - +package com.cloud.network; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -27,7 +27,7 @@ import javax.persistence.Id; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.cloud.network.rules.StickinessPolicy; -import com.cloud.utils.Pair; +import com.cloud.utils.Pair; @Entity @Table(name = ("load_balancer_stickiness_policies")) @@ -137,4 +137,4 @@ public class LBStickinessPolicyVO implements StickinessPolicy { public void setUuid(String uuid) { this.uuid = uuid; } -} +} diff --git a/server/src/com/cloud/network/LoadBalancerVMMapVO.java b/server/src/com/cloud/network/LoadBalancerVMMapVO.java index 0b8fd987f97..b0197bae376 100644 --- a/server/src/com/cloud/network/LoadBalancerVMMapVO.java +++ b/server/src/com/cloud/network/LoadBalancerVMMapVO.java @@ -10,56 +10,56 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - +package com.cloud.network; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; - -@Entity -@Table(name=("load_balancer_vm_map")) -public class LoadBalancerVMMapVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="load_balancer_id") - private long loadBalancerId; - - @Column(name="instance_id") - private long instanceId; - + +@Entity +@Table(name=("load_balancer_vm_map")) +public class LoadBalancerVMMapVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="load_balancer_id") + private long loadBalancerId; + + @Column(name="instance_id") + private long instanceId; + @Column(name="revoke") private boolean revoke = false; - public LoadBalancerVMMapVO() { } - - public LoadBalancerVMMapVO(long loadBalancerId, long instanceId) { - this.loadBalancerId = loadBalancerId; - this.instanceId = instanceId; - } - + public LoadBalancerVMMapVO() { } + + public LoadBalancerVMMapVO(long loadBalancerId, long instanceId) { + this.loadBalancerId = loadBalancerId; + this.instanceId = instanceId; + } + public LoadBalancerVMMapVO(long loadBalancerId, long instanceId, boolean revoke) { this.loadBalancerId = loadBalancerId; this.instanceId = instanceId; this.revoke = revoke; } - public long getId() { - return id; - } - - public long getLoadBalancerId() { - return loadBalancerId; - } - - public long getInstanceId() { - return instanceId; - } + public long getId() { + return id; + } + + public long getLoadBalancerId() { + return loadBalancerId; + } + + public long getInstanceId() { + return instanceId; + } public boolean isRevoke() { return revoke; @@ -68,4 +68,4 @@ public class LoadBalancerVMMapVO { public void setRevoke(boolean revoke) { this.revoke = revoke; } -} +} diff --git a/server/src/com/cloud/network/LoadBalancerVO.java b/server/src/com/cloud/network/LoadBalancerVO.java index 6a572f43aac..6746896f632 100644 --- a/server/src/com/cloud/network/LoadBalancerVO.java +++ b/server/src/com/cloud/network/LoadBalancerVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - +package com.cloud.network; + import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -21,20 +21,20 @@ import javax.persistence.Table; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.LoadBalancer; import com.cloud.utils.net.NetUtils; - -@Entity -@Table(name=("load_balancing_rules")) + +@Entity +@Table(name=("load_balancing_rules")) @DiscriminatorValue(value="LoadBalancing") @PrimaryKeyJoinColumn(name="id") public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer { - - @Column(name="name") - private String name; - - @Column(name="description", length=4096) - private String description; - - @Column(name="algorithm") + + @Column(name="name") + private String name; + + @Column(name="description", length=4096) + private String description; + + @Column(name="algorithm") private String algorithm; @Column(name="default_port_start") @@ -44,7 +44,7 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer { private int defaultPortEnd; public LoadBalancerVO() { - } + } public LoadBalancerVO(String xId, String name, String description, long srcIpId, int srcPort, int dstPort, String algorithm, long networkId, long accountId, long domainId) { super(xId, srcIpId, srcPort, NetUtils.TCP_PROTO, networkId, accountId, domainId, Purpose.LoadBalancing, null, null, null, null); @@ -54,22 +54,22 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer { this.defaultPortStart = dstPort; this.defaultPortEnd = dstPort; } - + @Override - public String getName() { - return name; + public String getName() { + return name; } - + @Override - public String getDescription() { - return description; - } - + public String getDescription() { + return description; + } + @Override - public String getAlgorithm() { - return algorithm; - } - + public String getAlgorithm() { + return algorithm; + } + @Override public int getDefaultPortStart() { return defaultPortStart; @@ -90,5 +90,5 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer { public void setDescription(String description) { this.description = description; - } -} + } +} diff --git a/server/src/com/cloud/network/NetworkRuleConfigVO.java b/server/src/com/cloud/network/NetworkRuleConfigVO.java index a4e27ff8acc..81d6ca70020 100644 --- a/server/src/com/cloud/network/NetworkRuleConfigVO.java +++ b/server/src/com/cloud/network/NetworkRuleConfigVO.java @@ -10,79 +10,79 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - -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; - +package com.cloud.network; + +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 com.cloud.async.AsyncInstanceCreateStatus; -import com.google.gson.annotations.Expose; - -@Entity -@Table(name=("network_rule_config")) -public class NetworkRuleConfigVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id; - - @Column(name="security_group_id") - private long securityGroupId; - - @Column(name="public_port") - private String publicPort; - - @Column(name="private_port") - private String privatePort; - - @Column(name="protocol") - private String protocol; - - @Expose - @Column(name="create_status", updatable = true, nullable=false) - @Enumerated(value=EnumType.STRING) - private AsyncInstanceCreateStatus createStatus; - - public NetworkRuleConfigVO() {} - - public NetworkRuleConfigVO(long securityGroupId, String publicPort, String privatePort, String protocol) { - this.securityGroupId = securityGroupId; - this.publicPort = publicPort; - this.privatePort = privatePort; - this.protocol = protocol; - } - - public Long getId() { - return id; - } - - public long getSecurityGroupId() { - return securityGroupId; - } - - public String getPublicPort() { - return publicPort; - } - - public String getPrivatePort() { - return privatePort; - } - - public String getProtocol() { - return protocol; - } - - public AsyncInstanceCreateStatus getCreateStatus() { - return createStatus; - } - - public void setCreateStatus(AsyncInstanceCreateStatus createStatus) { - this.createStatus = createStatus; - } -} +import com.google.gson.annotations.Expose; + +@Entity +@Table(name=("network_rule_config")) +public class NetworkRuleConfigVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id; + + @Column(name="security_group_id") + private long securityGroupId; + + @Column(name="public_port") + private String publicPort; + + @Column(name="private_port") + private String privatePort; + + @Column(name="protocol") + private String protocol; + + @Expose + @Column(name="create_status", updatable = true, nullable=false) + @Enumerated(value=EnumType.STRING) + private AsyncInstanceCreateStatus createStatus; + + public NetworkRuleConfigVO() {} + + public NetworkRuleConfigVO(long securityGroupId, String publicPort, String privatePort, String protocol) { + this.securityGroupId = securityGroupId; + this.publicPort = publicPort; + this.privatePort = privatePort; + this.protocol = protocol; + } + + public Long getId() { + return id; + } + + public long getSecurityGroupId() { + return securityGroupId; + } + + public String getPublicPort() { + return publicPort; + } + + public String getPrivatePort() { + return privatePort; + } + + public String getProtocol() { + return protocol; + } + + public AsyncInstanceCreateStatus getCreateStatus() { + return createStatus; + } + + public void setCreateStatus(AsyncInstanceCreateStatus createStatus) { + this.createStatus = createStatus; + } +} diff --git a/server/src/com/cloud/network/RemoteAccessVpnVO.java b/server/src/com/cloud/network/RemoteAccessVpnVO.java index 43fcff0dc06..094df34c786 100644 --- a/server/src/com/cloud/network/RemoteAccessVpnVO.java +++ b/server/src/com/cloud/network/RemoteAccessVpnVO.java @@ -10,44 +10,44 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - +package com.cloud.network; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; - -@Entity -@Table(name=("remote_access_vpn")) -public class RemoteAccessVpnVO implements RemoteAccessVpn { - @Column(name="account_id") + +@Entity +@Table(name=("remote_access_vpn")) +public class RemoteAccessVpnVO implements RemoteAccessVpn { + @Column(name="account_id") private long accountId; @Column(name="network_id") private long networkId; @Column(name="domain_id") - private long domainId; + private long domainId; - @Id + @Id @Column(name="vpn_server_addr_id") private long serverAddressId; @Column(name="local_ip") - private String localIp; - - @Column(name="ip_range") - private String ipRange; - - @Column(name="ipsec_psk") + private String localIp; + + @Column(name="ip_range") + private String ipRange; + + @Column(name="ipsec_psk") private String ipsecPresharedKey; @Column(name="state") - private State state; - - public RemoteAccessVpnVO() { } - - public RemoteAccessVpnVO(long accountId, long domainId, long networkId, long publicIpId, String localIp, String ipRange, String presharedKey) { + private State state; + + public RemoteAccessVpnVO() { } + + public RemoteAccessVpnVO(long accountId, long domainId, long networkId, long publicIpId, String localIp, String ipRange, String presharedKey) { this.accountId = accountId; this.serverAddressId = publicIpId; this.ipRange = ipRange; @@ -55,7 +55,7 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn { this.localIp = localIp; this.domainId = domainId; this.networkId = networkId; - this.state = State.Added; + this.state = State.Added; } @Override @@ -65,12 +65,12 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn { public void setState(State state) { this.state = state; - } - + } + @Override - public long getAccountId() { - return accountId; - } + public long getAccountId() { + return accountId; + } @Override public long getServerAddressId() { @@ -109,4 +109,4 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn { public long getNetworkId() { return networkId; } -} +} diff --git a/server/src/com/cloud/network/StorageNetworkManager.java b/server/src/com/cloud/network/StorageNetworkManager.java index 2c8a7d23e2d..3caf73f66d9 100755 --- a/server/src/com/cloud/network/StorageNetworkManager.java +++ b/server/src/com/cloud/network/StorageNetworkManager.java @@ -10,22 +10,22 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - -import java.util.List; - -import com.cloud.dc.StorageNetworkIpAddressVO; -import com.cloud.utils.component.Manager; -import com.cloud.vm.SecondaryStorageVmVO; - -public interface StorageNetworkManager extends Manager { - StorageNetworkIpAddressVO acquireIpAddress(long podId); - - void releaseIpAddress(String ip); - - boolean isStorageIpRangeAvailable(long zoneId); - - List getSSVMWithNoStorageNetwork(long zoneId); - - boolean isAnyStorageIpInUseInZone(long zoneId); -} +package com.cloud.network; + +import java.util.List; + +import com.cloud.dc.StorageNetworkIpAddressVO; +import com.cloud.utils.component.Manager; +import com.cloud.vm.SecondaryStorageVmVO; + +public interface StorageNetworkManager extends Manager { + StorageNetworkIpAddressVO acquireIpAddress(long podId); + + void releaseIpAddress(String ip); + + boolean isStorageIpRangeAvailable(long zoneId); + + List getSSVMWithNoStorageNetwork(long zoneId); + + boolean isAnyStorageIpInUseInZone(long zoneId); +} diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index 816c5ed9e58..b454585e8b2 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -10,372 +10,372 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -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.CreateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; -import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.listStorageNetworkIpRangeCmd; -import com.cloud.dc.HostPodVO; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.dc.StorageNetworkIpAddressVO; -import com.cloud.dc.StorageNetworkIpRangeVO; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.StorageNetworkIpAddressDao; -import com.cloud.dc.dao.StorageNetworkIpRangeDao; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.HostVO; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkDao; -import com.cloud.utils.Pair; -import com.cloud.utils.component.Inject; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.SecondaryStorageVmVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.dao.SecondaryStorageVmDao; -import com.cloud.vm.dao.VMInstanceDao; - -@Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) -public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService { - private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); - - String _name; - @Inject - StorageNetworkIpAddressDao _sNwIpDao; - @Inject - StorageNetworkIpRangeDao _sNwIpRangeDao; - @Inject - NetworkDao _networkDao; - @Inject - HostPodDao _podDao; - @Inject - SecondaryStorageVmDao _ssvmDao; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } - - @Override - public boolean start() { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean stop() { - // TODO Auto-generated method stub - return true; - } - - @Override - public String getName() { - // TODO Auto-generated method stub - return null; - } - - private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new CloudRuntimeException("Cannot find pod " + podId); - } - String[] IpRange = pod.getDescription().split("-"); - if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { - return; - } - if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { - throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]); - } - } - - private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) { - List curRanges = _sNwIpRangeDao.listByPodId(podId); - for (StorageNetworkIpRangeVO range : curRanges) { - if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { - throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp()); - } - } - } - - private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException { - long startIPLong = NetUtils.ip2Long(startIp); - long endIPLong = NetUtils.ip2Long(endIp); - String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; - String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; - PreparedStatement stmt = null; - Connection conn = txn.getConnection(); - - while (startIPLong <= endIPLong) { - stmt = conn.prepareStatement(insertSql); - stmt.setLong(1, rangeId); - stmt.setString(2, NetUtils.long2Ip(startIPLong++)); - stmt.setLong(3, zoneId); - stmt.setNull(4, java.sql.Types.DATE); - stmt.executeUpdate(); - stmt.close(); - - stmt = txn.prepareStatement(updateSql); - stmt.setLong(1, zoneId); - stmt.executeUpdate(); - stmt.close(); - } - } - - @Override - @DB - public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) { - Integer vlan = cmd.getVlan(); - Long rangeId = cmd.getId(); - String startIp = cmd.getStartIp(); - String endIp = cmd.getEndIp(); - String netmask = cmd.getNetmask(); - - if (netmask != null && !NetUtils.isValidNetmask(netmask)) { - throw new CloudRuntimeException("Invalid netmask:" + netmask); - } - - if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { - throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); - } - - StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); - if (range == null) { - throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); - } - - if (startIp != null || endIp != null) { - long podId = range.getPodId(); - startIp = startIp == null ? range.getStartIp() : startIp; - endIp = endIp == null ? range.getEndIp() : endIp; - checkOverlapPrivateIpRange(podId, startIp, endIp); - checkOverlapStorageIpRange(podId, startIp, endIp); - } - - Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - range = _sNwIpRangeDao.acquireInLockTable(range.getId()); - if (range == null) { - throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); - } - StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); - if (vlan != null) { - vo.setVlan(vlan); - } - if (startIp != null) { - vo.setStartIp(startIp); - } - if (endIp != null) { - vo.setEndIp(endIp); - } - if (netmask != null) { - vo.setNetmask(netmask); - } - _sNwIpRangeDao.update(rangeId, vo); - } finally { - if (range != null) { - _sNwIpRangeDao.releaseFromLockTable(range.getId()); - } - } - txn.commit(); - - return _sNwIpRangeDao.findById(rangeId); - } - - @Override - @DB - public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { - Long podId = cmd.getPodId(); - String startIp = cmd.getStartIp(); - String endIp = cmd.getEndIp(); - Integer vlan = cmd.getVlan(); - String netmask = cmd.getNetmask(); - - if (endIp == null) { - endIp = startIp; - } - - if (!NetUtils.isValidNetmask(netmask)) { - throw new CloudRuntimeException("Invalid netmask:" + netmask); - } - - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new CloudRuntimeException("Cannot find pod " + podId); - } - Long zoneId = pod.getDataCenterId(); - - List nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); - if (nws.size() == 0) { - throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); - } - if (nws.size() > 1) { - throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); - } - NetworkVO nw = nws.get(0); - - checkOverlapPrivateIpRange(podId, startIp, endIp); - checkOverlapStorageIpRange(podId, startIp, endIp); - - Transaction txn = Transaction.currentTxn(); - StorageNetworkIpRangeVO range = null; - - txn.start(); - range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); - _sNwIpRangeDao.persist(range); - try { - createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); - } catch (SQLException e) { - txn.rollback(); - StringBuilder err = new StringBuilder(); - err.append("Create storage network range failed."); - err.append("startIp=" + startIp); - err.append("endIp=" + endIp); - err.append("netmask=" + netmask); - err.append("zoneId=" + zoneId); - s_logger.debug(err.toString(), e); - throw e; - } - - txn.commit(); - - return range; - } - - private String getInUseIpAddress(long rangeId) { - List ips = _sNwIpDao.listInUseIpByRangeId(rangeId); - StringBuilder res = new StringBuilder(); - res.append("Below IP of range " + rangeId + " is still in use:"); - for (String ip : ips) { - res.append(ip).append(","); - } - return res.toString(); - } - - @Override - @DB - public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) { - long rangeId = cmd.getId(); - StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); - if (range == null) { - throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); - } - - if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { - throw new CloudRuntimeException(getInUseIpAddress(rangeId)); - } - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - range = _sNwIpRangeDao.acquireInLockTable(rangeId); - if (range == null) { - String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; - s_logger.warn(msg); - throw new CloudRuntimeException(msg); - } - /* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */ - _sNwIpRangeDao.remove(rangeId); - } finally { - if (range != null) { - _sNwIpRangeDao.releaseFromLockTable(rangeId); - } - } - txn.commit(); - } - - @Override - public List listIpRange(listStorageNetworkIpRangeCmd cmd) { - Long rangeId = cmd.getRangeId(); - Long podId = cmd.getPodId(); - Long zoneId = cmd.getZoneId(); - - List result = null; - if (rangeId != null) { - result = _sNwIpRangeDao.listByRangeId(rangeId); - } else if (podId != null) { - result = _sNwIpRangeDao.listByPodId(podId); - } else if (zoneId != null) { - result = _sNwIpRangeDao.listByDataCenterId(zoneId); - } else { - result = _sNwIpRangeDao.listAll(); - } - - return (List)result; - } - - @Override - public void releaseIpAddress(String ip) { - _sNwIpDao.releaseIpAddress(ip); - } - - @Override - public StorageNetworkIpAddressVO acquireIpAddress(long podId) { - List ranges = _sNwIpRangeDao.listByPodId(podId); - for (StorageNetworkIpRangeVO r : ranges) { - try { - r = _sNwIpRangeDao.acquireInLockTable(r.getId()); - if (r == null) { - String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; - s_logger.warn(msg); - throw new CloudRuntimeException(msg); - } - - StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); - if (ip != null) { - return ip; - } - } finally { - if (r != null) { - _sNwIpRangeDao.releaseFromLockTable(r.getId()); - } - } - } - - return null; - } - - @Override - public boolean isStorageIpRangeAvailable(long zoneId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); - List entries = sc.list(); - return entries.size() > 0; - } - - @Override - public List getSSVMWithNoStorageNetwork(long zoneId) { - List ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); - return ssvms; - } - - @Override - public boolean isAnyStorageIpInUseInZone(long zoneId) { - List ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); - for (StorageNetworkIpRangeVO r : ranges) { - if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { - return true; - } - } - return false; - } -} +package com.cloud.network; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +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.CreateStorageNetworkIpRangeCmd; +import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; +import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; +import com.cloud.api.commands.listStorageNetworkIpRangeCmd; +import com.cloud.dc.HostPodVO; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.dc.StorageNetworkIpAddressVO; +import com.cloud.dc.StorageNetworkIpRangeVO; +import com.cloud.dc.dao.HostPodDao; +import com.cloud.dc.dao.StorageNetworkIpAddressDao; +import com.cloud.dc.dao.StorageNetworkIpRangeDao; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.host.HostVO; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkDao; +import com.cloud.utils.Pair; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.SecondaryStorageVmVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.SecondaryStorageVmDao; +import com.cloud.vm.dao.VMInstanceDao; + +@Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) +public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService { + private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); + + String _name; + @Inject + StorageNetworkIpAddressDao _sNwIpDao; + @Inject + StorageNetworkIpRangeDao _sNwIpRangeDao; + @Inject + NetworkDao _networkDao; + @Inject + HostPodDao _podDao; + @Inject + SecondaryStorageVmDao _ssvmDao; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public boolean start() { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean stop() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new CloudRuntimeException("Cannot find pod " + podId); + } + String[] IpRange = pod.getDescription().split("-"); + if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { + return; + } + if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { + throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]); + } + } + + private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) { + List curRanges = _sNwIpRangeDao.listByPodId(podId); + for (StorageNetworkIpRangeVO range : curRanges) { + if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { + throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp()); + } + } + } + + private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException { + long startIPLong = NetUtils.ip2Long(startIp); + long endIPLong = NetUtils.ip2Long(endIp); + String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; + String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; + PreparedStatement stmt = null; + Connection conn = txn.getConnection(); + + while (startIPLong <= endIPLong) { + stmt = conn.prepareStatement(insertSql); + stmt.setLong(1, rangeId); + stmt.setString(2, NetUtils.long2Ip(startIPLong++)); + stmt.setLong(3, zoneId); + stmt.setNull(4, java.sql.Types.DATE); + stmt.executeUpdate(); + stmt.close(); + + stmt = txn.prepareStatement(updateSql); + stmt.setLong(1, zoneId); + stmt.executeUpdate(); + stmt.close(); + } + } + + @Override + @DB + public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) { + Integer vlan = cmd.getVlan(); + Long rangeId = cmd.getId(); + String startIp = cmd.getStartIp(); + String endIp = cmd.getEndIp(); + String netmask = cmd.getNetmask(); + + if (netmask != null && !NetUtils.isValidNetmask(netmask)) { + throw new CloudRuntimeException("Invalid netmask:" + netmask); + } + + if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { + throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); + } + + StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); + if (range == null) { + throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); + } + + if (startIp != null || endIp != null) { + long podId = range.getPodId(); + startIp = startIp == null ? range.getStartIp() : startIp; + endIp = endIp == null ? range.getEndIp() : endIp; + checkOverlapPrivateIpRange(podId, startIp, endIp); + checkOverlapStorageIpRange(podId, startIp, endIp); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + range = _sNwIpRangeDao.acquireInLockTable(range.getId()); + if (range == null) { + throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); + } + StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); + if (vlan != null) { + vo.setVlan(vlan); + } + if (startIp != null) { + vo.setStartIp(startIp); + } + if (endIp != null) { + vo.setEndIp(endIp); + } + if (netmask != null) { + vo.setNetmask(netmask); + } + _sNwIpRangeDao.update(rangeId, vo); + } finally { + if (range != null) { + _sNwIpRangeDao.releaseFromLockTable(range.getId()); + } + } + txn.commit(); + + return _sNwIpRangeDao.findById(rangeId); + } + + @Override + @DB + public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { + Long podId = cmd.getPodId(); + String startIp = cmd.getStartIp(); + String endIp = cmd.getEndIp(); + Integer vlan = cmd.getVlan(); + String netmask = cmd.getNetmask(); + + if (endIp == null) { + endIp = startIp; + } + + if (!NetUtils.isValidNetmask(netmask)) { + throw new CloudRuntimeException("Invalid netmask:" + netmask); + } + + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new CloudRuntimeException("Cannot find pod " + podId); + } + Long zoneId = pod.getDataCenterId(); + + List nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); + if (nws.size() == 0) { + throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); + } + if (nws.size() > 1) { + throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); + } + NetworkVO nw = nws.get(0); + + checkOverlapPrivateIpRange(podId, startIp, endIp); + checkOverlapStorageIpRange(podId, startIp, endIp); + + Transaction txn = Transaction.currentTxn(); + StorageNetworkIpRangeVO range = null; + + txn.start(); + range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); + _sNwIpRangeDao.persist(range); + try { + createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); + } catch (SQLException e) { + txn.rollback(); + StringBuilder err = new StringBuilder(); + err.append("Create storage network range failed."); + err.append("startIp=" + startIp); + err.append("endIp=" + endIp); + err.append("netmask=" + netmask); + err.append("zoneId=" + zoneId); + s_logger.debug(err.toString(), e); + throw e; + } + + txn.commit(); + + return range; + } + + private String getInUseIpAddress(long rangeId) { + List ips = _sNwIpDao.listInUseIpByRangeId(rangeId); + StringBuilder res = new StringBuilder(); + res.append("Below IP of range " + rangeId + " is still in use:"); + for (String ip : ips) { + res.append(ip).append(","); + } + return res.toString(); + } + + @Override + @DB + public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) { + long rangeId = cmd.getId(); + StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); + if (range == null) { + throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); + } + + if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { + throw new CloudRuntimeException(getInUseIpAddress(rangeId)); + } + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + range = _sNwIpRangeDao.acquireInLockTable(rangeId); + if (range == null) { + String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; + s_logger.warn(msg); + throw new CloudRuntimeException(msg); + } + /* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */ + _sNwIpRangeDao.remove(rangeId); + } finally { + if (range != null) { + _sNwIpRangeDao.releaseFromLockTable(rangeId); + } + } + txn.commit(); + } + + @Override + public List listIpRange(listStorageNetworkIpRangeCmd cmd) { + Long rangeId = cmd.getRangeId(); + Long podId = cmd.getPodId(); + Long zoneId = cmd.getZoneId(); + + List result = null; + if (rangeId != null) { + result = _sNwIpRangeDao.listByRangeId(rangeId); + } else if (podId != null) { + result = _sNwIpRangeDao.listByPodId(podId); + } else if (zoneId != null) { + result = _sNwIpRangeDao.listByDataCenterId(zoneId); + } else { + result = _sNwIpRangeDao.listAll(); + } + + return (List)result; + } + + @Override + public void releaseIpAddress(String ip) { + _sNwIpDao.releaseIpAddress(ip); + } + + @Override + public StorageNetworkIpAddressVO acquireIpAddress(long podId) { + List ranges = _sNwIpRangeDao.listByPodId(podId); + for (StorageNetworkIpRangeVO r : ranges) { + try { + r = _sNwIpRangeDao.acquireInLockTable(r.getId()); + if (r == null) { + String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; + s_logger.warn(msg); + throw new CloudRuntimeException(msg); + } + + StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); + if (ip != null) { + return ip; + } + } finally { + if (r != null) { + _sNwIpRangeDao.releaseFromLockTable(r.getId()); + } + } + } + + return null; + } + + @Override + public boolean isStorageIpRangeAvailable(long zoneId) { + SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); + List entries = sc.list(); + return entries.size() > 0; + } + + @Override + public List getSSVMWithNoStorageNetwork(long zoneId) { + List ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); + return ssvms; + } + + @Override + public boolean isAnyStorageIpInUseInZone(long zoneId) { + List ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); + for (StorageNetworkIpRangeVO r : ranges) { + if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { + return true; + } + } + return false; + } +} diff --git a/server/src/com/cloud/network/dao/IPAddressDao.java b/server/src/com/cloud/network/dao/IPAddressDao.java index 1b44b16ba9e..711a7fe8e1c 100755 --- a/server/src/com/cloud/network/dao/IPAddressDao.java +++ b/server/src/com/cloud/network/dao/IPAddressDao.java @@ -10,25 +10,25 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import com.cloud.dc.Vlan.VlanType; import com.cloud.network.IPAddressVO; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.Ip; - -public interface IPAddressDao extends GenericDao { + +public interface IPAddressDao extends GenericDao { IPAddressVO markAsUnavailable(long ipAddressId); - - void unassignIpAddress(long ipAddressId); - + + void unassignIpAddress(long ipAddressId); + List listByAccount(long accountId); - List listByVlanId(long vlanId); - + List listByVlanId(long vlanId); + List listByDcIdIpAddress(long dcId, String ipAddress); List listByDcId(long dcId); @@ -36,13 +36,13 @@ public interface IPAddressDao extends GenericDao { List listByAssociatedNetwork(long networkId, Boolean isSourceNat); List listStaticNatPublicIps(long networkId); - + int countIPs(long dcId, long vlanDbId, boolean onlyCountAllocated); int countIPs(long dcId, Long accountId, String vlanId, String vlanGateway, String vlanNetmask); - long countAllocatedIPsForAccount(long accountId); - + long countAllocatedIPsForAccount(long accountId); + boolean mark(long dcId, Ip ip); int countIPsForNetwork(long dcId, boolean onlyCountAllocated, VlanType vlanType); @@ -56,4 +56,4 @@ public interface IPAddressDao extends GenericDao { List listByPhysicalNetworkId(long physicalNetworkId); long countFreeIPs(); -} +} diff --git a/server/src/com/cloud/network/dao/LBStickinessPolicyDao.java b/server/src/com/cloud/network/dao/LBStickinessPolicyDao.java index 4c2c6f49f8a..f96fcccf4e5 100644 --- a/server/src/com/cloud/network/dao/LBStickinessPolicyDao.java +++ b/server/src/com/cloud/network/dao/LBStickinessPolicyDao.java @@ -10,13 +10,13 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import com.cloud.network.LBStickinessPolicyVO; import com.cloud.utils.db.GenericDao; - + public interface LBStickinessPolicyDao extends GenericDao { @@ -28,4 +28,4 @@ public interface LBStickinessPolicyDao extends List listByLoadBalancerId(long loadBalancerId, boolean revoke); -} +} diff --git a/server/src/com/cloud/network/dao/LBStickinessPolicyDaoImpl.java b/server/src/com/cloud/network/dao/LBStickinessPolicyDaoImpl.java index 4efde7b96b6..ab0fbf87d01 100644 --- a/server/src/com/cloud/network/dao/LBStickinessPolicyDaoImpl.java +++ b/server/src/com/cloud/network/dao/LBStickinessPolicyDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import javax.ejb.Local; @@ -19,7 +19,7 @@ import javax.ejb.Local; import com.cloud.network.LBStickinessPolicyVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria; - + @Local(value = { LBStickinessPolicyDao.class }) diff --git a/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java b/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java index b330f394678..aa1cf42e00e 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java +++ b/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java @@ -10,19 +10,19 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import com.cloud.network.LoadBalancerVMMapVO; import com.cloud.utils.db.GenericDao; - -public interface LoadBalancerVMMapDao extends GenericDao { - void remove(long loadBalancerId); - void remove(long loadBalancerId, List instanceIds, Boolean pending); - List listByInstanceId(long instanceId); - List listByLoadBalancerId(long loadBalancerId); + +public interface LoadBalancerVMMapDao extends GenericDao { + void remove(long loadBalancerId); + void remove(long loadBalancerId, List instanceIds, Boolean pending); + List listByInstanceId(long instanceId); + List listByLoadBalancerId(long loadBalancerId); List listByLoadBalancerId(long loadBalancerId, boolean revoke); LoadBalancerVMMapVO findByLoadBalancerIdAndVmId(long loadBalancerId, long instanceId); -} +} diff --git a/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java b/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java index 70921fcf5a6..d0c8cfc749b 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java +++ b/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import javax.ejb.Local; @@ -19,45 +19,45 @@ import javax.ejb.Local; import com.cloud.network.LoadBalancerVMMapVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria; - -@Local(value={LoadBalancerVMMapDao.class}) -public class LoadBalancerVMMapDaoImpl extends GenericDaoBase implements LoadBalancerVMMapDao { - - @Override - public void remove(long loadBalancerId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); - - expunge(sc); - } - - @Override - public void remove(long loadBalancerId, List instanceIds, Boolean revoke) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); + +@Local(value={LoadBalancerVMMapDao.class}) +public class LoadBalancerVMMapDaoImpl extends GenericDaoBase implements LoadBalancerVMMapDao { + + @Override + public void remove(long loadBalancerId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); + + expunge(sc); + } + + @Override + public void remove(long loadBalancerId, List instanceIds, Boolean revoke) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); sc.addAnd("instanceId", SearchCriteria.Op.IN, instanceIds.toArray()); if (revoke != null) { sc.addAnd("revoke", SearchCriteria.Op.EQ, revoke); - } - - expunge(sc); - } - - @Override - public List listByInstanceId(long instanceId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("instanceId", SearchCriteria.Op.EQ, instanceId); - - return listBy(sc); - } - - @Override - public List listByLoadBalancerId(long loadBalancerId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); - - return listBy(sc); - } + } + + expunge(sc); + } + + @Override + public List listByInstanceId(long instanceId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("instanceId", SearchCriteria.Op.EQ, instanceId); + + return listBy(sc); + } + + @Override + public List listByLoadBalancerId(long loadBalancerId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); + + return listBy(sc); + } @Override public List listByLoadBalancerId(long loadBalancerId, boolean pending) { @@ -77,4 +77,4 @@ public class LoadBalancerVMMapDaoImpl extends GenericDaoBase { - List listBySecurityGroupId(long securityGroupId); - void deleteBySecurityGroup(long securityGroupId); -} + +public interface NetworkRuleConfigDao extends GenericDao { + List listBySecurityGroupId(long securityGroupId); + void deleteBySecurityGroup(long securityGroupId); +} diff --git a/server/src/com/cloud/network/dao/NetworkRuleConfigDaoImpl.java b/server/src/com/cloud/network/dao/NetworkRuleConfigDaoImpl.java index 34b9dcd47b3..ce757043615 100644 --- a/server/src/com/cloud/network/dao/NetworkRuleConfigDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkRuleConfigDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import javax.ejb.Local; @@ -20,26 +20,26 @@ import com.cloud.network.NetworkRuleConfigVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={NetworkRuleConfigDao.class}) -public class NetworkRuleConfigDaoImpl extends GenericDaoBase implements NetworkRuleConfigDao { - protected SearchBuilder SecurityGroupIdSearch; - - protected NetworkRuleConfigDaoImpl() { - SecurityGroupIdSearch = createSearchBuilder(); - SecurityGroupIdSearch.and("securityGroupId", SecurityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); - SecurityGroupIdSearch.done(); - } - - public List listBySecurityGroupId(long securityGroupId) { - SearchCriteria sc = SecurityGroupIdSearch.create(); - sc.setParameters("securityGroupId", securityGroupId); - return listBy(sc); - } - - public void deleteBySecurityGroup(long securityGroupId) { - SearchCriteria sc = SecurityGroupIdSearch.create(); - sc.setParameters("securityGroupId", securityGroupId); - expunge(sc); - } -} + +@Local(value={NetworkRuleConfigDao.class}) +public class NetworkRuleConfigDaoImpl extends GenericDaoBase implements NetworkRuleConfigDao { + protected SearchBuilder SecurityGroupIdSearch; + + protected NetworkRuleConfigDaoImpl() { + SecurityGroupIdSearch = createSearchBuilder(); + SecurityGroupIdSearch.and("securityGroupId", SecurityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); + SecurityGroupIdSearch.done(); + } + + public List listBySecurityGroupId(long securityGroupId) { + SearchCriteria sc = SecurityGroupIdSearch.create(); + sc.setParameters("securityGroupId", securityGroupId); + return listBy(sc); + } + + public void deleteBySecurityGroup(long securityGroupId) { + SearchCriteria sc = SecurityGroupIdSearch.create(); + sc.setParameters("securityGroupId", securityGroupId); + expunge(sc); + } +} diff --git a/server/src/com/cloud/network/dao/RemoteAccessVpnDao.java b/server/src/com/cloud/network/dao/RemoteAccessVpnDao.java index 4224436f860..aa94c4ac3d4 100644 --- a/server/src/com/cloud/network/dao/RemoteAccessVpnDao.java +++ b/server/src/com/cloud/network/dao/RemoteAccessVpnDao.java @@ -10,18 +10,18 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.RemoteAccessVpnVO; import com.cloud.utils.db.GenericDao; - -public interface RemoteAccessVpnDao extends GenericDao { + +public interface RemoteAccessVpnDao extends GenericDao { RemoteAccessVpnVO findByPublicIpAddress(long ipAddressId); RemoteAccessVpnVO findByPublicIpAddressAndState(long ipAddressId, RemoteAccessVpn.State state); RemoteAccessVpnVO findByAccountAndNetwork(Long accountId, Long zoneId); List findByAccount(Long accountId); - List listByNetworkId(Long networkId); -} + List listByNetworkId(Long networkId); +} diff --git a/server/src/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java b/server/src/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java index c7dbef78bec..dc9bfce3ec1 100644 --- a/server/src/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java +++ b/server/src/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import javax.ejb.Local; @@ -23,29 +23,29 @@ import com.cloud.network.RemoteAccessVpnVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={RemoteAccessVpnDao.class}) -public class RemoteAccessVpnDaoImpl extends GenericDaoBase implements RemoteAccessVpnDao { + +@Local(value={RemoteAccessVpnDao.class}) +public class RemoteAccessVpnDaoImpl extends GenericDaoBase implements RemoteAccessVpnDao { private static final Logger s_logger = Logger.getLogger(RemoteAccessVpnDaoImpl.class); - + private final SearchBuilder AllFieldsSearch; - - protected RemoteAccessVpnDaoImpl() { + + protected RemoteAccessVpnDaoImpl() { AllFieldsSearch = createSearchBuilder(); AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("networkId", AllFieldsSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("ipAddress", AllFieldsSearch.entity().getServerAddressId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), SearchCriteria.Op.EQ); AllFieldsSearch.done(); - } - - @Override - public RemoteAccessVpnVO findByPublicIpAddress(long ipAddressId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("ipAddress", ipAddressId); - return findOneBy(sc); - } + } + + @Override + public RemoteAccessVpnVO findByPublicIpAddress(long ipAddressId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("ipAddress", ipAddressId); + return findOneBy(sc); + } @Override public RemoteAccessVpnVO findByAccountAndNetwork(Long accountId, Long networkId) { @@ -75,5 +75,5 @@ public class RemoteAccessVpnDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("networkId", networkId); return listBy(sc); - } -} + } +} diff --git a/server/src/com/cloud/network/dao/VpnUserDao.java b/server/src/com/cloud/network/dao/VpnUserDao.java index 931721ffd37..9d277b93d1d 100644 --- a/server/src/com/cloud/network/dao/VpnUserDao.java +++ b/server/src/com/cloud/network/dao/VpnUserDao.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import com.cloud.network.VpnUserVO; import com.cloud.utils.db.GenericDao; - -public interface VpnUserDao extends GenericDao { + +public interface VpnUserDao extends GenericDao { List listByAccount(Long accountId); VpnUserVO findByAccountAndUsername(Long acccountId, String userName); - long getVpnUserCount(Long accountId); -} + long getVpnUserCount(Long accountId); +} diff --git a/server/src/com/cloud/network/dao/VpnUserDaoImpl.java b/server/src/com/cloud/network/dao/VpnUserDaoImpl.java index cca26624473..2465e2925e3 100644 --- a/server/src/com/cloud/network/dao/VpnUserDaoImpl.java +++ b/server/src/com/cloud/network/dao/VpnUserDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.util.List; import javax.ejb.Local; @@ -23,15 +23,15 @@ import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; - -@Local(value={VpnUserDao.class}) -public class VpnUserDaoImpl extends GenericDaoBase implements VpnUserDao { + +@Local(value={VpnUserDao.class}) +public class VpnUserDaoImpl extends GenericDaoBase implements VpnUserDao { private final SearchBuilder AccountSearch; private final SearchBuilder AccountNameSearch; private final GenericSearchBuilder VpnUserCount; - - protected VpnUserDaoImpl() { + + protected VpnUserDaoImpl() { AccountSearch = createSearchBuilder(); AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); @@ -47,7 +47,7 @@ public class VpnUserDaoImpl extends GenericDaoBase implements V VpnUserCount.and("state", VpnUserCount.entity().getState(), SearchCriteria.Op.NEQ); VpnUserCount.select(null, Func.COUNT, null); VpnUserCount.done(); - } + } @Override public List listByAccount(Long accountId) { @@ -76,5 +76,5 @@ public class VpnUserDaoImpl extends GenericDaoBase implements V } return rs.get(0); - } -} + } +} diff --git a/server/src/com/cloud/network/element/VirtualRouterProviderVO.java b/server/src/com/cloud/network/element/VirtualRouterProviderVO.java index 240c35b8389..183604151c2 100644 --- a/server/src/com/cloud/network/element/VirtualRouterProviderVO.java +++ b/server/src/com/cloud/network/element/VirtualRouterProviderVO.java @@ -27,8 +27,8 @@ import javax.persistence.Table; import com.cloud.network.VirtualRouterProvider; import com.cloud.utils.db.GenericDao; -@Entity -@Table(name=("virtual_router_providers")) +@Entity +@Table(name=("virtual_router_providers")) public class VirtualRouterProviderVO implements VirtualRouterProvider { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/guru/StorageNetworkGuru.java b/server/src/com/cloud/network/guru/StorageNetworkGuru.java index 1872f2e6f02..52323a7709a 100755 --- a/server/src/com/cloud/network/guru/StorageNetworkGuru.java +++ b/server/src/com/cloud/network/guru/StorageNetworkGuru.java @@ -10,181 +10,181 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.guru; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.dc.Pod; -import com.cloud.dc.StorageNetworkIpAddressVO; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.network.Network; -import com.cloud.network.NetworkProfile; -import com.cloud.network.NetworkVO; -import com.cloud.network.Networks.AddressFormat; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.Mode; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.StorageNetworkManager; -import com.cloud.network.dao.NetworkDao; -import com.cloud.offering.NetworkOffering; -import com.cloud.user.Account; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.component.Inject; -import com.cloud.utils.net.Ip4Address; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.Nic.ReservationStrategy; - -@Local(value = NetworkGuru.class) -public class StorageNetworkGuru extends PodBasedNetworkGuru implements NetworkGuru { - private static final Logger s_logger = Logger.getLogger(StorageNetworkGuru.class); - @Inject StorageNetworkManager _sNwMgr; - @Inject NetworkDao _nwDao; - - protected StorageNetworkGuru() { - super(); - } - - private static final TrafficType[] _trafficTypes = {TrafficType.Storage}; - - @Override - public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { - if (t == type) { - return true; - } - } - return false; - } - - @Override - public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; - } - - protected boolean canHandle(NetworkOffering offering) { - if (isMyTrafficType(offering.getTrafficType()) && offering.isSystemOnly()) { - return true; - } else { - s_logger.trace("It's not storage network offering, skip it."); - return false; - } - } - - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { - if (!canHandle(offering)) { - return null; - } - - NetworkVO config = new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.Native, offering.getId(), Network.State.Setup, - plan.getDataCenterId(), plan.getPhysicalNetworkId()); - return config; - } - - @Override - public Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context) - throws InsufficientVirtualNetworkCapcityException { - assert network.getTrafficType() == TrafficType.Storage : "Why are you sending this configuration to me " + network; - if (!_sNwMgr.isStorageIpRangeAvailable(destination.getDataCenter().getId())) { - return super.implement(network, offering, destination, context); - } - return network; - } - - @Override - public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile vm) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { - assert network.getTrafficType() == TrafficType.Storage : "Well, I can't take care of this config now can I? " + network; - if (!_sNwMgr.isStorageIpRangeAvailable(network.getDataCenterId())) { - return super.allocate(network, nic, vm); - } - - return new NicProfile(ReservationStrategy.Start, null, null, null, null); - } - - @Override - public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { - if (!_sNwMgr.isStorageIpRangeAvailable(dest.getDataCenter().getId())) { - super.reserve(nic, network, vm, dest, context); - return; - } - - Pod pod = dest.getPod(); - Integer vlan = null; - - StorageNetworkIpAddressVO ip = _sNwMgr.acquireIpAddress(pod.getId()); - if (ip == null) { - throw new InsufficientAddressCapacityException("Unable to get a storage network ip address", Pod.class, pod.getId()); - } - - vlan = ip.getVlan(); - nic.setIp4Address(ip.getIpAddress()); - nic.setMacAddress(NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(ip.getMac()))); - nic.setFormat(AddressFormat.Ip4); - nic.setNetmask(ip.getNetmask()); +package com.cloud.network.guru; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.dc.Pod; +import com.cloud.dc.StorageNetworkIpAddressVO; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapcityException; +import com.cloud.network.Network; +import com.cloud.network.NetworkProfile; +import com.cloud.network.NetworkVO; +import com.cloud.network.Networks.AddressFormat; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.Mode; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.StorageNetworkManager; +import com.cloud.network.dao.NetworkDao; +import com.cloud.offering.NetworkOffering; +import com.cloud.user.Account; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.component.Inject; +import com.cloud.utils.net.Ip4Address; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; +import com.cloud.vm.Nic.ReservationStrategy; + +@Local(value = NetworkGuru.class) +public class StorageNetworkGuru extends PodBasedNetworkGuru implements NetworkGuru { + private static final Logger s_logger = Logger.getLogger(StorageNetworkGuru.class); + @Inject StorageNetworkManager _sNwMgr; + @Inject NetworkDao _nwDao; + + protected StorageNetworkGuru() { + super(); + } + + private static final TrafficType[] _trafficTypes = {TrafficType.Storage}; + + @Override + public boolean isMyTrafficType(TrafficType type) { + for (TrafficType t : _trafficTypes) { + if (t == type) { + return true; + } + } + return false; + } + + @Override + public TrafficType[] getSupportedTrafficType() { + return _trafficTypes; + } + + protected boolean canHandle(NetworkOffering offering) { + if (isMyTrafficType(offering.getTrafficType()) && offering.isSystemOnly()) { + return true; + } else { + s_logger.trace("It's not storage network offering, skip it."); + return false; + } + } + + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { + if (!canHandle(offering)) { + return null; + } + + NetworkVO config = new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.Native, offering.getId(), Network.State.Setup, + plan.getDataCenterId(), plan.getPhysicalNetworkId()); + return config; + } + + @Override + public Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException { + assert network.getTrafficType() == TrafficType.Storage : "Why are you sending this configuration to me " + network; + if (!_sNwMgr.isStorageIpRangeAvailable(destination.getDataCenter().getId())) { + return super.implement(network, offering, destination, context); + } + return network; + } + + @Override + public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile vm) + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { + assert network.getTrafficType() == TrafficType.Storage : "Well, I can't take care of this config now can I? " + network; + if (!_sNwMgr.isStorageIpRangeAvailable(network.getDataCenterId())) { + return super.allocate(network, nic, vm); + } + + return new NicProfile(ReservationStrategy.Start, null, null, null, null); + } + + @Override + public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { + if (!_sNwMgr.isStorageIpRangeAvailable(dest.getDataCenter().getId())) { + super.reserve(nic, network, vm, dest, context); + return; + } + + Pod pod = dest.getPod(); + Integer vlan = null; + + StorageNetworkIpAddressVO ip = _sNwMgr.acquireIpAddress(pod.getId()); + if (ip == null) { + throw new InsufficientAddressCapacityException("Unable to get a storage network ip address", Pod.class, pod.getId()); + } + + vlan = ip.getVlan(); + nic.setIp4Address(ip.getIpAddress()); + nic.setMacAddress(NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(ip.getMac()))); + nic.setFormat(AddressFormat.Ip4); + nic.setNetmask(ip.getNetmask()); nic.setBroadcastType(BroadcastDomainType.Storage); - nic.setGateway(ip.getGateway()); - if (vlan != null) { - nic.setBroadcastUri(BroadcastDomainType.Storage.toUri(vlan)); - } else { - nic.setBroadcastUri(null); - } - nic.setIsolationUri(null); - s_logger.debug("Allocated a storage nic " + nic + " for " + vm); - } - - @Override - public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { - Network nw = _nwDao.findById(nic.getNetworkId()); - if (!_sNwMgr.isStorageIpRangeAvailable(nw.getDataCenterId())) { - return super.release(nic, vm, reservationId); - } - - _sNwMgr.releaseIpAddress(nic.getIp4Address()); - s_logger.debug("Release an storage ip " + nic.getIp4Address()); - nic.deallocate(); - return true; - } - - @Override - public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) { - // TODO Auto-generated method stub - - } - - @Override - public void updateNicProfile(NicProfile profile, Network network) { - // TODO Auto-generated method stub - - } - - @Override - public void shutdown(NetworkProfile network, NetworkOffering offering) { - // TODO Auto-generated method stub - - } - - @Override - public boolean trash(Network network, NetworkOffering offering, Account owner) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void updateNetworkProfile(NetworkProfile networkProfile) { - // TODO Auto-generated method stub - - } - -} + nic.setGateway(ip.getGateway()); + if (vlan != null) { + nic.setBroadcastUri(BroadcastDomainType.Storage.toUri(vlan)); + } else { + nic.setBroadcastUri(null); + } + nic.setIsolationUri(null); + s_logger.debug("Allocated a storage nic " + nic + " for " + vm); + } + + @Override + public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { + Network nw = _nwDao.findById(nic.getNetworkId()); + if (!_sNwMgr.isStorageIpRangeAvailable(nw.getDataCenterId())) { + return super.release(nic, vm, reservationId); + } + + _sNwMgr.releaseIpAddress(nic.getIp4Address()); + s_logger.debug("Release an storage ip " + nic.getIp4Address()); + nic.deallocate(); + return true; + } + + @Override + public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) { + // TODO Auto-generated method stub + + } + + @Override + public void updateNicProfile(NicProfile profile, Network network) { + // TODO Auto-generated method stub + + } + + @Override + public void shutdown(NetworkProfile network, NetworkOffering offering) { + // TODO Auto-generated method stub + + } + + @Override + public boolean trash(Network network, NetworkOffering offering, Account owner) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void updateNetworkProfile(NetworkProfile networkProfile) { + // TODO Auto-generated method stub + + } + +} diff --git a/server/src/com/cloud/network/lb/dao/ElasticLbVmMapDao.java b/server/src/com/cloud/network/lb/dao/ElasticLbVmMapDao.java index 7874d704ba4..7ab53306774 100644 --- a/server/src/com/cloud/network/lb/dao/ElasticLbVmMapDao.java +++ b/server/src/com/cloud/network/lb/dao/ElasticLbVmMapDao.java @@ -10,24 +10,24 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.lb.dao; - +package com.cloud.network.lb.dao; + import java.util.List; import com.cloud.network.ElasticLbVmMapVO; import com.cloud.network.LoadBalancerVO; import com.cloud.utils.db.GenericDao; import com.cloud.vm.DomainRouterVO; - -public interface ElasticLbVmMapDao extends GenericDao { + +public interface ElasticLbVmMapDao extends GenericDao { ElasticLbVmMapVO findOneByLbIdAndElbVmId(long lbId, long elbVmId); ElasticLbVmMapVO findOneByIpIdAndElbVmId(long ipId, long elbVmId); ElasticLbVmMapVO findOneByIp(long ipId); - - List listByElbVmId(long elbVmId); - List listByLbId(long lbId); + + List listByElbVmId(long elbVmId); + List listByLbId(long lbId); int deleteLB(long lbId); List listUnusedElbVms(); List listLbsForElbVm(long elbVmId); - -} + +} diff --git a/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDao.java b/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDao.java index 598cece1181..f5d3da7d7b4 100644 --- a/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDao.java +++ b/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.ovs.dao; - -import java.util.List; - -import com.cloud.utils.db.GenericDao; - -public interface OvsTunnelAccountDao extends - GenericDao { - OvsTunnelAccountVO getByFromToAccount(long from, long to, long account); - void removeByFromAccount(long from, long account); - void removeByFromToAccount(long from, long to, long account); - List listByToAccount(long to, long account); -} +package com.cloud.network.ovs.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; + +public interface OvsTunnelAccountDao extends + GenericDao { + OvsTunnelAccountVO getByFromToAccount(long from, long to, long account); + void removeByFromAccount(long from, long account); + void removeByFromToAccount(long from, long to, long account); + List listByToAccount(long to, long account); +} diff --git a/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDaoImpl.java b/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDaoImpl.java index ab31a597fa3..b2c7a4b7965 100644 --- a/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDaoImpl.java +++ b/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountDaoImpl.java @@ -10,76 +10,76 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.ovs.dao; - -import java.util.List; - -import javax.ejb.Local; - -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Local(value = { OvsTunnelAccountDao.class }) -public class OvsTunnelAccountDaoImpl extends - GenericDaoBase implements OvsTunnelAccountDao { - - protected final SearchBuilder fromToAccountSearch; - protected final SearchBuilder fromAccountSearch; - protected final SearchBuilder toAccountSearch; - - public OvsTunnelAccountDaoImpl() { - fromToAccountSearch = createSearchBuilder(); - fromToAccountSearch.and("from", fromToAccountSearch.entity().getFrom(), Op.EQ); - fromToAccountSearch.and("to", fromToAccountSearch.entity().getTo(), Op.EQ); - fromToAccountSearch.and("account", fromToAccountSearch.entity().getAccount(), Op.EQ); - fromToAccountSearch.done(); - - fromAccountSearch = createSearchBuilder(); - fromAccountSearch.and("from", fromAccountSearch.entity().getFrom(), Op.EQ); - fromAccountSearch.and("account", fromAccountSearch.entity().getAccount(), Op.EQ); - fromAccountSearch.done(); - - toAccountSearch = createSearchBuilder(); - toAccountSearch.and("to", toAccountSearch.entity().getTo(), Op.EQ); - toAccountSearch.and("account", toAccountSearch.entity().getAccount(), Op.EQ); - toAccountSearch.done(); - } - - @Override - public OvsTunnelAccountVO getByFromToAccount(long from, long to, - long account) { - SearchCriteria sc = fromToAccountSearch.create(); - sc.setParameters("from", from); - sc.setParameters("to", to); - sc.setParameters("account", account); - return findOneBy(sc); - } - - @Override - public void removeByFromAccount(long from, long account) { - SearchCriteria sc = fromAccountSearch.create(); - sc.setParameters("from", from); - sc.setParameters("account", account); - remove(sc); - } - - @Override - public List listByToAccount(long to, long account) { - SearchCriteria sc = toAccountSearch.create(); - sc.setParameters("to", to); - sc.setParameters("account", account); - return listBy(sc); - } - - @Override - public void removeByFromToAccount(long from, long to, long account) { - SearchCriteria sc = fromToAccountSearch.create(); - sc.setParameters("from", from); - sc.setParameters("to", to); - sc.setParameters("account", account); - remove(sc); - } - -} +package com.cloud.network.ovs.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value = { OvsTunnelAccountDao.class }) +public class OvsTunnelAccountDaoImpl extends + GenericDaoBase implements OvsTunnelAccountDao { + + protected final SearchBuilder fromToAccountSearch; + protected final SearchBuilder fromAccountSearch; + protected final SearchBuilder toAccountSearch; + + public OvsTunnelAccountDaoImpl() { + fromToAccountSearch = createSearchBuilder(); + fromToAccountSearch.and("from", fromToAccountSearch.entity().getFrom(), Op.EQ); + fromToAccountSearch.and("to", fromToAccountSearch.entity().getTo(), Op.EQ); + fromToAccountSearch.and("account", fromToAccountSearch.entity().getAccount(), Op.EQ); + fromToAccountSearch.done(); + + fromAccountSearch = createSearchBuilder(); + fromAccountSearch.and("from", fromAccountSearch.entity().getFrom(), Op.EQ); + fromAccountSearch.and("account", fromAccountSearch.entity().getAccount(), Op.EQ); + fromAccountSearch.done(); + + toAccountSearch = createSearchBuilder(); + toAccountSearch.and("to", toAccountSearch.entity().getTo(), Op.EQ); + toAccountSearch.and("account", toAccountSearch.entity().getAccount(), Op.EQ); + toAccountSearch.done(); + } + + @Override + public OvsTunnelAccountVO getByFromToAccount(long from, long to, + long account) { + SearchCriteria sc = fromToAccountSearch.create(); + sc.setParameters("from", from); + sc.setParameters("to", to); + sc.setParameters("account", account); + return findOneBy(sc); + } + + @Override + public void removeByFromAccount(long from, long account) { + SearchCriteria sc = fromAccountSearch.create(); + sc.setParameters("from", from); + sc.setParameters("account", account); + remove(sc); + } + + @Override + public List listByToAccount(long to, long account) { + SearchCriteria sc = toAccountSearch.create(); + sc.setParameters("to", to); + sc.setParameters("account", account); + return listBy(sc); + } + + @Override + public void removeByFromToAccount(long from, long to, long account) { + SearchCriteria sc = fromToAccountSearch.create(); + sc.setParameters("from", from); + sc.setParameters("to", to); + sc.setParameters("account", account); + remove(sc); + } + +} diff --git a/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountVO.java b/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountVO.java index bbfd654b6c3..6bb70d9d8ff 100644 --- a/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountVO.java +++ b/server/src/com/cloud/network/ovs/dao/OvsTunnelAccountVO.java @@ -10,91 +10,91 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.ovs.dao; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name=("ovs_tunnel_account")) -public class OvsTunnelAccountVO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "from") - private long from; - - @Column(name = "to") - private long to; - - @Column(name = "key") - private int key; - - @Column(name = "account") - private long account; - - @Column(name = "port_name") - private String portName; - - @Column(name = "state") - private String state; - - public OvsTunnelAccountVO() { - - } - - public OvsTunnelAccountVO(long from, long to, int key, long account) { - this.from = from; - this.to = to; - this.key = key; - this.account = account; - this.portName = "[]"; - this.state = "FAILED"; - } - - public void setKey(int key) { - this.key = key; - } - - public long getFrom() { - return from; - } - - public long getTo() { - return to; - } - - public int getKey() { - return key; - } - - public long getId() { - return id; - } - - public long getAccount() { - return account; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public void setPortName(String name) { - this.portName = name; - } - - public String getPortName() { - return portName; - } -} +package com.cloud.network.ovs.dao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name=("ovs_tunnel_account")) +public class OvsTunnelAccountVO { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "from") + private long from; + + @Column(name = "to") + private long to; + + @Column(name = "key") + private int key; + + @Column(name = "account") + private long account; + + @Column(name = "port_name") + private String portName; + + @Column(name = "state") + private String state; + + public OvsTunnelAccountVO() { + + } + + public OvsTunnelAccountVO(long from, long to, int key, long account) { + this.from = from; + this.to = to; + this.key = key; + this.account = account; + this.portName = "[]"; + this.state = "FAILED"; + } + + public void setKey(int key) { + this.key = key; + } + + public long getFrom() { + return from; + } + + public long getTo() { + return to; + } + + public int getKey() { + return key; + } + + public long getId() { + return id; + } + + public long getAccount() { + return account; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public void setPortName(String name) { + this.portName = name; + } + + public String getPortName() { + return portName; + } +} diff --git a/server/src/com/cloud/network/rules/PortForwardingRuleVO.java b/server/src/com/cloud/network/rules/PortForwardingRuleVO.java index a3ea0e83626..848177e3eba 100644 --- a/server/src/com/cloud/network/rules/PortForwardingRuleVO.java +++ b/server/src/com/cloud/network/rules/PortForwardingRuleVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.rules; - +package com.cloud.network.rules; + import java.util.List; import javax.persistence.Column; @@ -23,18 +23,18 @@ import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.cloud.utils.net.Ip; - -@Entity -@Table(name=("port_forwarding_rules")) + +@Entity +@Table(name=("port_forwarding_rules")) @DiscriminatorValue(value="PortForwarding") @PrimaryKeyJoinColumn(name="id") -public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardingRule { +public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardingRule { - @Enumerated(value=EnumType.STRING) - @Column(name="dest_ip_address") - private Ip destinationIpAddress = null; - - @Column(name="dest_port_start") + @Enumerated(value=EnumType.STRING) + @Column(name="dest_ip_address") + private Ip destinationIpAddress = null; + + @Column(name="dest_port_start") private int destinationPortStart; @Column(name="dest_port_end") @@ -42,35 +42,35 @@ public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardi @Column(name="instance_id") private long virtualMachineId; - - public PortForwardingRuleVO() { - } + + public PortForwardingRuleVO() { + } public PortForwardingRuleVO(String xId, long srcIpId, int srcPortStart, int srcPortEnd, Ip dstIp, int dstPortStart, int dstPortEnd, String protocol, long networkId, long accountId, long domainId, long instanceId) { super(xId, srcIpId, srcPortStart, srcPortEnd, protocol, networkId, accountId, domainId, Purpose.PortForwarding, null, null, null, null); this.destinationIpAddress = dstIp; this.virtualMachineId = instanceId; this.destinationPortStart = dstPortStart; - this.destinationPortEnd = dstPortEnd; + this.destinationPortEnd = dstPortEnd; } public PortForwardingRuleVO(String xId, long srcIpId, int srcPort, Ip dstIp, int dstPort, String protocol, List sourceCidrs, long networkId, long accountId, long domainId, long instanceId) { this(xId, srcIpId, srcPort, srcPort, dstIp, dstPort, dstPort, protocol.toLowerCase(), networkId, accountId, domainId, instanceId); } - + @Override - public Ip getDestinationIpAddress() { - return destinationIpAddress; + public Ip getDestinationIpAddress() { + return destinationIpAddress; } @Override public void setDestinationIpAddress(Ip destinationIpAddress) { this.destinationIpAddress = destinationIpAddress; - } - + } + @Override - public int getDestinationPortStart() { - return destinationPortStart; + public int getDestinationPortStart() { + return destinationPortStart; } @Override @@ -86,7 +86,7 @@ public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardi @Override public Long getRelated() { return null; - } + } + +} -} - diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupDao.java b/server/src/com/cloud/network/security/dao/SecurityGroupDao.java index 1097239e5b9..f123175e184 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupDao.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupDao.java @@ -10,17 +10,17 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - -import java.util.List; - +package com.cloud.network.security.dao; + +import java.util.List; + import com.cloud.network.security.SecurityGroupVO; import com.cloud.utils.db.GenericDao; - -public interface SecurityGroupDao extends GenericDao { - List listByAccountId(long accountId); + +public interface SecurityGroupDao extends GenericDao { + List listByAccountId(long accountId); boolean isNameInUse(Long accountId, Long domainId, String name); SecurityGroupVO findByAccountAndName(Long accountId, String name); List findByAccountAndNames(Long accountId, String... names); - int removeByAccountId(long accountId); -} + int removeByAccountId(long accountId); +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupDaoImpl.java index 4d37d4bc4c6..e59dcdee521 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.util.List; import javax.ejb.Local; @@ -20,16 +20,16 @@ import com.cloud.network.security.SecurityGroupVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={SecurityGroupDao.class}) -public class SecurityGroupDaoImpl extends GenericDaoBase implements SecurityGroupDao { + +@Local(value={SecurityGroupDao.class}) +public class SecurityGroupDaoImpl extends GenericDaoBase implements SecurityGroupDao { private SearchBuilder AccountIdSearch; private SearchBuilder AccountIdNameSearch; - private SearchBuilder AccountIdNamesSearch; - - protected SecurityGroupDaoImpl() { - AccountIdSearch = createSearchBuilder(); - AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + private SearchBuilder AccountIdNamesSearch; + + protected SecurityGroupDaoImpl() { + AccountIdSearch = createSearchBuilder(); + AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountIdSearch.done(); AccountIdNameSearch = createSearchBuilder(); @@ -39,29 +39,29 @@ public class SecurityGroupDaoImpl extends GenericDaoBase AccountIdNamesSearch = createSearchBuilder(); AccountIdNamesSearch.and("accountId", AccountIdNamesSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountIdNamesSearch.and("groupNames", AccountIdNamesSearch.entity().getName(), SearchCriteria.Op.IN); - AccountIdNameSearch.done(); - } - - @Override - public List listByAccountId(long accountId) { - SearchCriteria sc = AccountIdSearch.create(); - sc.setParameters("accountId", accountId); - return listBy(sc); - } - - @Override - public boolean isNameInUse(Long accountId, Long domainId, String name) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("name", SearchCriteria.Op.EQ, name); - if (accountId != null) { - sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); - } else { - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); - sc.addAnd("accountId", SearchCriteria.Op.NULL); - } - - List securityGroups = listBy(sc); - return ((securityGroups != null) && !securityGroups.isEmpty()); + AccountIdNameSearch.done(); + } + + @Override + public List listByAccountId(long accountId) { + SearchCriteria sc = AccountIdSearch.create(); + sc.setParameters("accountId", accountId); + return listBy(sc); + } + + @Override + public boolean isNameInUse(Long accountId, Long domainId, String name) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("name", SearchCriteria.Op.EQ, name); + if (accountId != null) { + sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + } else { + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); + sc.addAnd("accountId", SearchCriteria.Op.NULL); + } + + List securityGroups = listBy(sc); + return ((securityGroups != null) && !securityGroups.isEmpty()); } @Override @@ -87,5 +87,5 @@ public class SecurityGroupDaoImpl extends GenericDaoBase SearchCriteria sc = AccountIdSearch.create(); sc.setParameters("accountId", accountId); return expunge(sc); - } -} + } +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupRuleDao.java b/server/src/com/cloud/network/security/dao/SecurityGroupRuleDao.java index 06174eaa0d0..48d2f8e8346 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupRuleDao.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupRuleDao.java @@ -10,22 +10,22 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - -import java.util.List; - +package com.cloud.network.security.dao; + +import java.util.List; + import com.cloud.network.security.SecurityGroupRuleVO; import com.cloud.network.security.SecurityRule.SecurityRuleType; import com.cloud.utils.db.GenericDao; - -public interface SecurityGroupRuleDao extends GenericDao { + +public interface SecurityGroupRuleDao extends GenericDao { List listBySecurityGroupId(long securityGroupId, SecurityRuleType type); List listByAllowedSecurityGroupId(long networkGroupId); SecurityGroupRuleVO findByProtoPortsAndCidr(long networkGroupId, String proto, int startPort, int endPort, String cidr); SecurityGroupRuleVO findByProtoPortsAndGroup(String proto, int startPort, int endPort, String networkGroup); - SecurityGroupRuleVO findByProtoPortsAndAllowedGroupId(long networkGroupId, String proto, int startPort, int endPort, Long allowedGroupId); + SecurityGroupRuleVO findByProtoPortsAndAllowedGroupId(long networkGroupId, String proto, int startPort, int endPort, Long allowedGroupId); int deleteBySecurityGroup(long securityGroupId); int deleteByPortProtoAndGroup(long securityGroupId, String protocol, int startPort,int endPort, Long id); int deleteByPortProtoAndCidr(long securityGroupId, String protocol, int startPort,int endPort, String cidr); - -} + +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupRuleDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupRuleDaoImpl.java index 2b5d5a72869..83b51bd2f59 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupRuleDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupRuleDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.util.List; import java.util.Map; @@ -26,12 +26,12 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={SecurityGroupRuleDao.class}) + +@Local(value={SecurityGroupRuleDao.class}) public class SecurityGroupRuleDaoImpl extends GenericDaoBase implements SecurityGroupRuleDao { @Inject SecurityGroupDao _securityGroupDao; - + protected SearchBuilder securityGroupIdSearch; protected SearchBuilder securityGroupIdAndTypeSearch; protected SearchBuilder allowedSecurityGroupIdSearch; @@ -39,11 +39,11 @@ public class SecurityGroupRuleDaoImpl extends GenericDaoBase protoPortsAndSecurityGroupNameSearch; protected SearchBuilder protoPortsAndSecurityGroupIdSearch; - - - protected SecurityGroupRuleDaoImpl() { - securityGroupIdSearch = createSearchBuilder(); - securityGroupIdSearch.and("securityGroupId", securityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); + + + protected SecurityGroupRuleDaoImpl() { + securityGroupIdSearch = createSearchBuilder(); + securityGroupIdSearch.and("securityGroupId", securityGroupIdSearch.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); securityGroupIdSearch.done(); securityGroupIdAndTypeSearch = createSearchBuilder(); @@ -69,11 +69,11 @@ public class SecurityGroupRuleDaoImpl extends GenericDaoBase listBySecurityGroupId(long securityGroupId, SecurityRuleType type) { - SearchCriteria sc = securityGroupIdAndTypeSearch.create(); + + } + + public List listBySecurityGroupId(long securityGroupId, SecurityRuleType type) { + SearchCriteria sc = securityGroupIdAndTypeSearch.create(); sc.setParameters("securityGroupId", securityGroupId); String dbType; if (type == SecurityRuleType.EgressRule) { @@ -82,14 +82,14 @@ public class SecurityGroupRuleDaoImpl extends GenericDaoBase sc = securityGroupIdSearch.create(); - sc.setParameters("securityGroupId", securityGroupId); - return expunge(sc); + sc.setParameters("type", dbType); + return listBy(sc); + } + + public int deleteBySecurityGroup(long securityGroupId) { + SearchCriteria sc = securityGroupIdSearch.create(); + sc.setParameters("securityGroupId", securityGroupId); + return expunge(sc); } @Override @@ -165,5 +165,5 @@ public class SecurityGroupRuleDaoImpl extends GenericDaoBase { - /** - * List a security group and associated ingress rules - * @return the list of ingress rules associated with the security group (and security group info) - */ - List listSecurityGroupRules(long accountId, String groupName); - - /** - * List security groups and associated ingress rules - * @return the list of security groups with associated ingress rules - */ - List listSecurityGroupRules(long accountId); - - /** - * List all security groups and associated ingress rules - * @return the list of security groups with associated ingress rules - */ - List listSecurityGroupRules(); - - /** - * List all security rules belonging to the specific group - * @return the security group with associated ingress rules - */ - List listSecurityRulesByGroupId(long groupId); -} +package com.cloud.network.security.dao; + +import java.util.List; + +import com.cloud.network.security.SecurityGroupRulesVO; +import com.cloud.utils.db.GenericDao; + +public interface SecurityGroupRulesDao extends GenericDao { + /** + * List a security group and associated ingress rules + * @return the list of ingress rules associated with the security group (and security group info) + */ + List listSecurityGroupRules(long accountId, String groupName); + + /** + * List security groups and associated ingress rules + * @return the list of security groups with associated ingress rules + */ + List listSecurityGroupRules(long accountId); + + /** + * List all security groups and associated ingress rules + * @return the list of security groups with associated ingress rules + */ + List listSecurityGroupRules(); + + /** + * List all security rules belonging to the specific group + * @return the security group with associated ingress rules + */ + List listSecurityRulesByGroupId(long groupId); +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupRulesDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupRulesDaoImpl.java index 719b4e52f6e..cd2e9b79ca4 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupRulesDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupRulesDaoImpl.java @@ -10,71 +10,71 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - -import java.util.List; - -import javax.ejb.Local; - -import com.cloud.network.security.SecurityGroupRulesVO; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; - -@Local(value={SecurityGroupRulesDao.class}) -public class SecurityGroupRulesDaoImpl extends GenericDaoBase implements SecurityGroupRulesDao { - private SearchBuilder AccountGroupNameSearch; - private SearchBuilder AccountSearch; - private SearchBuilder GroupSearch; - - - protected SecurityGroupRulesDaoImpl() { - AccountGroupNameSearch = createSearchBuilder(); - AccountGroupNameSearch.and("accountId", AccountGroupNameSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountGroupNameSearch.and("name", AccountGroupNameSearch.entity().getName(), SearchCriteria.Op.EQ); - AccountGroupNameSearch.done(); - - AccountSearch = createSearchBuilder(); - AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountSearch.done(); - - GroupSearch = createSearchBuilder(); - GroupSearch.and("groupId", GroupSearch.entity().getId(), SearchCriteria.Op.EQ); - GroupSearch.done(); - - } - - @Override - public List listSecurityGroupRules() { - Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); - return listAll(searchFilter); - } - - @Override - public List listSecurityGroupRules(long accountId, String groupName) { - Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); - - SearchCriteria sc = AccountGroupNameSearch.create(); - sc.setParameters("accountId", accountId); - sc.setParameters("name", groupName); - - return listBy(sc, searchFilter); - } - - @Override - public List listSecurityGroupRules(long accountId) { - Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); - SearchCriteria sc = AccountSearch.create(); - sc.setParameters("accountId", accountId); - return listBy(sc, searchFilter); - } - - @Override - public List listSecurityRulesByGroupId(long groupId) { - Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); - SearchCriteria sc = GroupSearch.create(); - sc.setParameters("groupId", groupId); - return listBy(sc, searchFilter); - } -} +package com.cloud.network.security.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.security.SecurityGroupRulesVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={SecurityGroupRulesDao.class}) +public class SecurityGroupRulesDaoImpl extends GenericDaoBase implements SecurityGroupRulesDao { + private SearchBuilder AccountGroupNameSearch; + private SearchBuilder AccountSearch; + private SearchBuilder GroupSearch; + + + protected SecurityGroupRulesDaoImpl() { + AccountGroupNameSearch = createSearchBuilder(); + AccountGroupNameSearch.and("accountId", AccountGroupNameSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountGroupNameSearch.and("name", AccountGroupNameSearch.entity().getName(), SearchCriteria.Op.EQ); + AccountGroupNameSearch.done(); + + AccountSearch = createSearchBuilder(); + AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountSearch.done(); + + GroupSearch = createSearchBuilder(); + GroupSearch.and("groupId", GroupSearch.entity().getId(), SearchCriteria.Op.EQ); + GroupSearch.done(); + + } + + @Override + public List listSecurityGroupRules() { + Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); + return listAll(searchFilter); + } + + @Override + public List listSecurityGroupRules(long accountId, String groupName) { + Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); + + SearchCriteria sc = AccountGroupNameSearch.create(); + sc.setParameters("accountId", accountId); + sc.setParameters("name", groupName); + + return listBy(sc, searchFilter); + } + + @Override + public List listSecurityGroupRules(long accountId) { + Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); + SearchCriteria sc = AccountSearch.create(); + sc.setParameters("accountId", accountId); + return listBy(sc, searchFilter); + } + + @Override + public List listSecurityRulesByGroupId(long groupId) { + Filter searchFilter = new Filter(SecurityGroupRulesVO.class, "id", true, null, null); + SearchCriteria sc = GroupSearch.create(); + sc.setParameters("groupId", groupId); + return listBy(sc, searchFilter); + } +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java index 5664f188994..b7ffc9d730d 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java @@ -10,22 +10,22 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.util.List; import com.cloud.network.security.SecurityGroupVMMapVO; import com.cloud.utils.db.GenericDao; import com.cloud.vm.VirtualMachine.State; - -public interface SecurityGroupVMMapDao extends GenericDao { - List listByIpAndInstanceId(String ipAddress, long instanceId); - List listByInstanceId(long instanceId); - List listByIp(String ipAddress); + +public interface SecurityGroupVMMapDao extends GenericDao { + List listByIpAndInstanceId(String ipAddress, long instanceId); + List listByInstanceId(long instanceId); + List listByIp(String ipAddress); List listBySecurityGroup(long securityGroupId); - List listBySecurityGroup(long securityGroupId, State ... vmStates); + List listBySecurityGroup(long securityGroupId, State ... vmStates); int deleteVM(long instanceid); List listVmIdsBySecurityGroup(long securityGroupId); SecurityGroupVMMapVO findByVmIdGroupId(long instanceId, long securityGroupId); - long countSGForVm(long instanceId); -} + long countSGForVm(long instanceId); +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java index 269c0678b5c..b22744e26ad 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.util.List; import javax.ejb.Local; @@ -28,41 +28,41 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.vm.VirtualMachine.State; - -@Local(value={SecurityGroupVMMapDao.class}) + +@Local(value={SecurityGroupVMMapDao.class}) public class SecurityGroupVMMapDaoImpl extends GenericDaoBase implements SecurityGroupVMMapDao { - private SearchBuilder ListByIpAndVmId; + private SearchBuilder ListByIpAndVmId; private SearchBuilder ListByVmId; private SearchBuilder ListByVmIdGroupId; protected GenericSearchBuilder CountSGForVm; private GenericSearchBuilder ListVmIdBySecurityGroup; - - private SearchBuilder ListByIp; + + private SearchBuilder ListByIp; private SearchBuilder ListBySecurityGroup; - private SearchBuilder ListBySecurityGroupAndStates; - - protected SecurityGroupVMMapDaoImpl() { - ListByIpAndVmId = createSearchBuilder(); - ListByIpAndVmId.and("ipAddress", ListByIpAndVmId.entity().getGuestIpAddress(), SearchCriteria.Op.EQ); - ListByIpAndVmId.and("instanceId", ListByIpAndVmId.entity().getInstanceId(), SearchCriteria.Op.EQ); - ListByIpAndVmId.done(); - - ListVmIdBySecurityGroup = createSearchBuilder(Long.class); + private SearchBuilder ListBySecurityGroupAndStates; + + protected SecurityGroupVMMapDaoImpl() { + ListByIpAndVmId = createSearchBuilder(); + ListByIpAndVmId.and("ipAddress", ListByIpAndVmId.entity().getGuestIpAddress(), SearchCriteria.Op.EQ); + ListByIpAndVmId.and("instanceId", ListByIpAndVmId.entity().getInstanceId(), SearchCriteria.Op.EQ); + ListByIpAndVmId.done(); + + ListVmIdBySecurityGroup = createSearchBuilder(Long.class); ListVmIdBySecurityGroup.and("securityGroupId", ListVmIdBySecurityGroup.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); - ListVmIdBySecurityGroup.selectField(ListVmIdBySecurityGroup.entity().getInstanceId()); + ListVmIdBySecurityGroup.selectField(ListVmIdBySecurityGroup.entity().getInstanceId()); ListVmIdBySecurityGroup.done(); ListBySecurityGroup = createSearchBuilder(); ListBySecurityGroup.and("securityGroupId", ListBySecurityGroup.entity().getSecurityGroupId(), SearchCriteria.Op.EQ); - ListBySecurityGroup.done(); - - ListByIp = createSearchBuilder(); - ListByIp.and("ipAddress", ListByIp.entity().getGuestIpAddress(), SearchCriteria.Op.EQ); - ListByIp.done(); - - ListByVmId = createSearchBuilder(); - ListByVmId.and("instanceId", ListByVmId.entity().getInstanceId(), SearchCriteria.Op.EQ); + ListBySecurityGroup.done(); + + ListByIp = createSearchBuilder(); + ListByIp.and("ipAddress", ListByIp.entity().getGuestIpAddress(), SearchCriteria.Op.EQ); + ListByIp.done(); + + ListByVmId = createSearchBuilder(); + ListByVmId.and("instanceId", ListByVmId.entity().getInstanceId(), SearchCriteria.Op.EQ); ListByVmId.done(); ListBySecurityGroupAndStates = createSearchBuilder(); @@ -78,43 +78,43 @@ public class SecurityGroupVMMapDaoImpl extends GenericDaoBase listByIpAndInstanceId(String ipAddress, long vmId) { + SearchCriteria sc = ListByIpAndVmId.create(); + sc.setParameters("ipAddress", ipAddress); + sc.setParameters("instanceId", vmId); + return listBy(sc); + } + + @Override + public List listBySecurityGroup(long securityGroupId) { + SearchCriteria sc = ListBySecurityGroup.create(); + sc.setParameters("securityGroupId", securityGroupId); + return listBy(sc); + } + + @Override + public List listByIp(String ipAddress) { + SearchCriteria sc = ListByIp.create(); + sc.setParameters("ipAddress", ipAddress); + return listBy(sc); + } + + @Override + public List listByInstanceId(long vmId) { + SearchCriteria sc = ListByVmId.create(); + sc.setParameters("instanceId", vmId); + return listBy(sc); + } + @Override - public List listByIpAndInstanceId(String ipAddress, long vmId) { - SearchCriteria sc = ListByIpAndVmId.create(); - sc.setParameters("ipAddress", ipAddress); - sc.setParameters("instanceId", vmId); - return listBy(sc); - } - - @Override - public List listBySecurityGroup(long securityGroupId) { - SearchCriteria sc = ListBySecurityGroup.create(); - sc.setParameters("securityGroupId", securityGroupId); - return listBy(sc); - } - - @Override - public List listByIp(String ipAddress) { - SearchCriteria sc = ListByIp.create(); - sc.setParameters("ipAddress", ipAddress); - return listBy(sc); - } - - @Override - public List listByInstanceId(long vmId) { - SearchCriteria sc = ListByVmId.create(); - sc.setParameters("instanceId", vmId); - return listBy(sc); - } - - @Override public int deleteVM(long instanceId) { SearchCriteria sc = ListByVmId.create(); - sc.setParameters("instanceId", instanceId); - return super.expunge(sc); + sc.setParameters("instanceId", instanceId); + return super.expunge(sc); } @Override @@ -146,5 +146,5 @@ public class SecurityGroupVMMapDaoImpl extends GenericDaoBase { + +public interface SecurityGroupWorkDao extends GenericDao { SecurityGroupWork findByVmId(long vmId, boolean taken); SecurityGroupWorkVO findByVmIdStep(long vmId, Step step); @@ -41,5 +41,5 @@ public interface SecurityGroupWorkDao extends GenericDao findScheduledWork(); - -} + +} diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java index 05fc5c2397e..734662491e9 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.util.Date; import java.util.List; @@ -31,24 +31,24 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={SecurityGroupWorkDao.class}) + +@Local(value={SecurityGroupWorkDao.class}) public class SecurityGroupWorkDaoImpl extends GenericDaoBase implements SecurityGroupWorkDao { private static final Logger s_logger = Logger.getLogger(SecurityGroupWorkDaoImpl.class); - + private SearchBuilder VmIdTakenSearch; private SearchBuilder VmIdSeqNumSearch; private SearchBuilder VmIdUnTakenSearch; private SearchBuilder UntakenWorkSearch; private SearchBuilder VmIdStepSearch; private SearchBuilder CleanupSearch; - - - protected SecurityGroupWorkDaoImpl() { - VmIdTakenSearch = createSearchBuilder(); + + + protected SecurityGroupWorkDaoImpl() { + VmIdTakenSearch = createSearchBuilder(); VmIdTakenSearch.and("vmId", VmIdTakenSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); VmIdTakenSearch.and("taken", VmIdTakenSearch.entity().getDateTaken(), SearchCriteria.Op.NNULL); - + VmIdTakenSearch.done(); VmIdUnTakenSearch = createSearchBuilder(); @@ -82,14 +82,14 @@ public class SecurityGroupWorkDaoImpl extends GenericDaoBase sc = taken?VmIdTakenSearch.create():VmIdUnTakenSearch.create(); - sc.setParameters("vmId", vmId); - return findOneIncludingRemovedBy(sc); + + } + + @Override + public SecurityGroupWork findByVmId(long vmId, boolean taken) { + SearchCriteria sc = taken?VmIdTakenSearch.create():VmIdUnTakenSearch.create(); + sc.setParameters("vmId", vmId); + return findOneIncludingRemovedBy(sc); } @Override @@ -228,7 +228,7 @@ public class SecurityGroupWorkDaoImpl extends GenericDaoBase sc = UntakenWorkSearch.create(); sc.setParameters("step", Step.Scheduled); return listIncludingRemovedBy(sc); - } - - -} + } + + +} diff --git a/server/src/com/cloud/network/security/dao/VmRulesetLogDao.java b/server/src/com/cloud/network/security/dao/VmRulesetLogDao.java index f11b3cbe377..526e09f4616 100644 --- a/server/src/com/cloud/network/security/dao/VmRulesetLogDao.java +++ b/server/src/com/cloud/network/security/dao/VmRulesetLogDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.util.Set; import com.cloud.network.security.VmRulesetLogVO; import com.cloud.utils.db.GenericDao; - -public interface VmRulesetLogDao extends GenericDao { + +public interface VmRulesetLogDao extends GenericDao { VmRulesetLogVO findByVmId(long vmId); int createOrUpdate(Set workItems); - -} + +} diff --git a/server/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java b/server/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java index d74dfbc1cb6..7efde98c82b 100644 --- a/server/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network.security.dao; - +package com.cloud.network.security.dao; + import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLTransactionRollbackException; @@ -30,10 +30,10 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value={VmRulesetLogDao.class}) + +@Local(value={VmRulesetLogDao.class}) public class VmRulesetLogDaoImpl extends GenericDaoBase implements VmRulesetLogDao { - protected static Logger s_logger = Logger.getLogger(VmRulesetLogDaoImpl.class); + protected static Logger s_logger = Logger.getLogger(VmRulesetLogDaoImpl.class); private SearchBuilder VmIdSearch; private String INSERT_OR_UPDATE = "INSERT INTO op_vm_ruleset_log (instance_id, created, logsequence) " + " VALUES(?, now(), 1) ON DUPLICATE KEY UPDATE logsequence=logsequence+1"; @@ -56,21 +56,21 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im builder.append("(?, now(), 1) "); builder.append(" ON DUPLICATE KEY UPDATE logsequence=logsequence+1"); return builder.toString(); - } - - protected VmRulesetLogDaoImpl() { - VmIdSearch = createSearchBuilder(); + } + + protected VmRulesetLogDaoImpl() { + VmIdSearch = createSearchBuilder(); VmIdSearch.and("vmId", VmIdSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); - + VmIdSearch.done(); - - } - - @Override - public VmRulesetLogVO findByVmId(long vmId) { - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - return findOneIncludingRemovedBy(sc); + + } + + @Override + public VmRulesetLogVO findByVmId(long vmId) { + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + return findOneIncludingRemovedBy(sc); } @Override @@ -188,7 +188,7 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im } } return count; - } - - -} + } + + +} diff --git a/server/src/com/cloud/resource/DummyHostDiscoverer.java b/server/src/com/cloud/resource/DummyHostDiscoverer.java index bef66135298..824a33e4338 100755 --- a/server/src/com/cloud/resource/DummyHostDiscoverer.java +++ b/server/src/com/cloud/resource/DummyHostDiscoverer.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.resource; - +package com.cloud.resource; + import java.net.URI; import java.util.HashMap; import java.util.List; @@ -25,63 +25,63 @@ import org.apache.log4j.Logger; import com.cloud.host.HostVO; import com.cloud.hypervisor.Hypervisor; - -@Local(value=Discoverer.class) -public class DummyHostDiscoverer implements Discoverer { - private static final Logger s_logger = Logger.getLogger(DummyHostDiscoverer.class); - - private String _name; - - @Override - public Map> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) { - if (!url.getScheme().equals("dummy")) { - return null; - } - - Map> resources = new HashMap>(); - Map params = new HashMap(); - Map details = new HashMap(); - - details.put("url", url.toString()); - details.put("username", username); - details.put("password", password); - - params.put("url", url.toString()); - params.put("username", username); - params.put("password", password); - params.put("zone", Long.toString(dcId)); - params.put("guid", UUID.randomUUID().toString()); - params.put("pod", Long.toString(podId)); - - DummyHostServerResource resource = new DummyHostServerResource(); - try { - resource.configure("Dummy Host Server", params); - } catch (ConfigurationException e) { - s_logger.warn("Unable to instantiate dummy host server resource"); - } - resource.start(); - resources.put(resource, details); - return resources; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; + +@Local(value=Discoverer.class) +public class DummyHostDiscoverer implements Discoverer { + private static final Logger s_logger = Logger.getLogger(DummyHostDiscoverer.class); + + private String _name; + + @Override + public Map> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) { + if (!url.getScheme().equals("dummy")) { + return null; + } + + Map> resources = new HashMap>(); + Map params = new HashMap(); + Map details = new HashMap(); + + details.put("url", url.toString()); + details.put("username", username); + details.put("password", password); + + params.put("url", url.toString()); + params.put("username", username); + params.put("password", password); + params.put("zone", Long.toString(dcId)); + params.put("guid", UUID.randomUUID().toString()); + params.put("pod", Long.toString(podId)); + + DummyHostServerResource resource = new DummyHostServerResource(); + try { + resource.configure("Dummy Host Server", params); + } catch (ConfigurationException e) { + s_logger.warn("Unable to instantiate dummy host server resource"); + } + resource.start(); + resources.put(resource, details); + return resources; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; } @Override @@ -109,5 +109,5 @@ public class DummyHostDiscoverer implements Discoverer { public ServerResource reloadResource(HostVO host) { // TODO Auto-generated method stub return null; - } -} + } +} diff --git a/server/src/com/cloud/resource/DummyHostServerResource.java b/server/src/com/cloud/resource/DummyHostServerResource.java index 5641fa08784..0998c592a61 100644 --- a/server/src/com/cloud/resource/DummyHostServerResource.java +++ b/server/src/com/cloud/resource/DummyHostServerResource.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.resource; - +package com.cloud.resource; + import java.util.HashMap; import java.util.Map; @@ -27,137 +27,137 @@ import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.net.MacAddress; import com.cloud.vm.VirtualMachine; - -public class DummyHostServerResource extends ServerResourceBase { - - private String _name; - private String _zone; - private String _pod; - private String _guid; - private String _url; - private int _instanceId; - private final int _prefix = 0x55; - - private static volatile int s_nextSequence = 1; - - @Override - protected String getDefaultScriptsDir() { - return "/dummy"; - } - - @Override - public Answer executeRequest(Command cmd) { - return new Answer(cmd, false, "Unsupported in dummy host server resource"); - } - - @Override - public PingCommand getCurrentStatus(long id) { - HashMap newStates = new HashMap(); - return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, newStates); - } - - @Override - public Type getType() { - return com.cloud.host.Host.Type.Routing; - } - - @Override - public StartupCommand[] initialize() { - + +public class DummyHostServerResource extends ServerResourceBase { + + private String _name; + private String _zone; + private String _pod; + private String _guid; + private String _url; + private int _instanceId; + private final int _prefix = 0x55; + + private static volatile int s_nextSequence = 1; + + @Override + protected String getDefaultScriptsDir() { + return "/dummy"; + } + + @Override + public Answer executeRequest(Command cmd) { + return new Answer(cmd, false, "Unsupported in dummy host server resource"); + } + + @Override + public PingCommand getCurrentStatus(long id) { + HashMap newStates = new HashMap(); + return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, newStates); + } + + @Override + public Type getType() { + return com.cloud.host.Host.Type.Routing; + } + + @Override + public StartupCommand[] initialize() { + StartupRoutingCommand cmd = new StartupRoutingCommand(); cmd.setCpus(1); cmd.setSpeed(1000L); cmd.setMemory(1000000L); cmd.setDom0MinMemory(256L); - cmd.setCaps("hvm"); - cmd.setGuid(_guid); - cmd.setDataCenter(_zone); - cmd.setPod(_pod); - cmd.setHypervisorType(HypervisorType.None); - cmd.setAgentTag("vmops-simulator"); - cmd.setName(_url); - cmd.setPrivateIpAddress(this.getHostPrivateIp()); - cmd.setPrivateMacAddress(this.getHostMacAddress().toString()); - cmd.setPrivateNetmask("255.255.0.0"); - cmd.setIqn("iqn:"+_url); - cmd.setStorageIpAddress(getHostStoragePrivateIp()); - cmd.setStorageMacAddress(getHostStorageMacAddress().toString()); - cmd.setStorageIpAddressDeux(getHostStoragePrivateIp2()); - cmd.setStorageMacAddressDeux(getHostStorageMacAddress2().toString()); - cmd.setPublicIpAddress(getHostStoragePrivateIp()); - cmd.setPublicMacAddress(getHostStorageMacAddress().toString()); - cmd.setPublicNetmask("255.255.0.0"); - cmd.setVersion("1.0"); - - return new StartupCommand[] {cmd}; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - _guid = (String)params.get("guid"); - _zone = (String)params.get("zone"); - _pod = (String)params.get("pod"); - _url = (String)params.get("url"); - - _instanceId = getNextSequenceId(); - return true; - } - - public static int getNextSequenceId() { - return s_nextSequence++; - } - - public MacAddress getHostMacAddress() { - long address = 0; - - address = (_prefix & 0xff); - address <<= 40; - address |= _instanceId; - return new MacAddress(address); - } - - public String getHostPrivateIp() { - int id = _instanceId; - - return "172.16." + - String.valueOf((id >> 8) & 0xff) + "." + - String.valueOf(id & 0xff); - } - - public MacAddress getHostStorageMacAddress() { - long address = 0; - - address = (_prefix & 0xff); - address <<= 40; - address |= (_instanceId | (1L << 31)) & 0xffffffff; - return new MacAddress(address); - } - - public MacAddress getHostStorageMacAddress2() { - long address = 0; - - address = (_prefix & 0xff); - address <<= 40; - address |= (_instanceId | (3L << 30)) & 0xffffffff; - return new MacAddress(address); - } - - public String getHostStoragePrivateIp() { - int id = _instanceId; - id |= 1 << 15; - - return "172.16." + - String.valueOf((id >> 8) & 0xff) + "." + - String.valueOf(id & 0xff); - } - - public String getHostStoragePrivateIp2() { - int id = _instanceId; - id |= 3 << 14; - - return "172.16." + - String.valueOf((id >> 8) & 0xff) + "." + - String.valueOf((id) & 0xff); - } -} + cmd.setCaps("hvm"); + cmd.setGuid(_guid); + cmd.setDataCenter(_zone); + cmd.setPod(_pod); + cmd.setHypervisorType(HypervisorType.None); + cmd.setAgentTag("vmops-simulator"); + cmd.setName(_url); + cmd.setPrivateIpAddress(this.getHostPrivateIp()); + cmd.setPrivateMacAddress(this.getHostMacAddress().toString()); + cmd.setPrivateNetmask("255.255.0.0"); + cmd.setIqn("iqn:"+_url); + cmd.setStorageIpAddress(getHostStoragePrivateIp()); + cmd.setStorageMacAddress(getHostStorageMacAddress().toString()); + cmd.setStorageIpAddressDeux(getHostStoragePrivateIp2()); + cmd.setStorageMacAddressDeux(getHostStorageMacAddress2().toString()); + cmd.setPublicIpAddress(getHostStoragePrivateIp()); + cmd.setPublicMacAddress(getHostStorageMacAddress().toString()); + cmd.setPublicNetmask("255.255.0.0"); + cmd.setVersion("1.0"); + + return new StartupCommand[] {cmd}; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + _guid = (String)params.get("guid"); + _zone = (String)params.get("zone"); + _pod = (String)params.get("pod"); + _url = (String)params.get("url"); + + _instanceId = getNextSequenceId(); + return true; + } + + public static int getNextSequenceId() { + return s_nextSequence++; + } + + public MacAddress getHostMacAddress() { + long address = 0; + + address = (_prefix & 0xff); + address <<= 40; + address |= _instanceId; + return new MacAddress(address); + } + + public String getHostPrivateIp() { + int id = _instanceId; + + return "172.16." + + String.valueOf((id >> 8) & 0xff) + "." + + String.valueOf(id & 0xff); + } + + public MacAddress getHostStorageMacAddress() { + long address = 0; + + address = (_prefix & 0xff); + address <<= 40; + address |= (_instanceId | (1L << 31)) & 0xffffffff; + return new MacAddress(address); + } + + public MacAddress getHostStorageMacAddress2() { + long address = 0; + + address = (_prefix & 0xff); + address <<= 40; + address |= (_instanceId | (3L << 30)) & 0xffffffff; + return new MacAddress(address); + } + + public String getHostStoragePrivateIp() { + int id = _instanceId; + id |= 1 << 15; + + return "172.16." + + String.valueOf((id >> 8) & 0xff) + "." + + String.valueOf(id & 0xff); + } + + public String getHostStoragePrivateIp2() { + int id = _instanceId; + id |= 3 << 14; + + return "172.16." + + String.valueOf((id >> 8) & 0xff) + "." + + String.valueOf((id) & 0xff); + } +} diff --git a/server/src/com/cloud/resource/ResourceStateAdapter.java b/server/src/com/cloud/resource/ResourceStateAdapter.java index 7bf3aa4227a..a09694c1474 100755 --- a/server/src/com/cloud/resource/ResourceStateAdapter.java +++ b/server/src/com/cloud/resource/ResourceStateAdapter.java @@ -10,50 +10,50 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.resource; - -import java.util.List; -import java.util.Map; - -import com.cloud.agent.api.StartupAnswer; -import com.cloud.agent.api.StartupCommand; -import com.cloud.exception.ConnectionException; -import com.cloud.host.HostVO; -import com.cloud.utils.component.Adapter; - -public interface ResourceStateAdapter extends Adapter { - static public enum Event { - CREATE_HOST_VO_FOR_CONNECTED, - CREATE_HOST_VO_FOR_DIRECT_CONNECT, - DELETE_HOST, - } - - static public class DeleteHostAnswer { - private boolean isContinue; - private boolean isException; - - public DeleteHostAnswer(boolean isContinue) { - this.isContinue = isContinue; - this.isException = false; - } - - public DeleteHostAnswer(boolean isContinue, boolean isException) { - this.isContinue = isContinue; - this.isException = isException; - } - - public boolean getIsContinue() { - return this.isContinue; - } - - public boolean getIsException() { - return this.isException; - } - } - - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd); - - public HostVO createHostVOForDirectConnectAgent(HostVO host, final StartupCommand[] startup, ServerResource resource, Map details, List hostTags); - - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException; -} +package com.cloud.resource; + +import java.util.List; +import java.util.Map; + +import com.cloud.agent.api.StartupAnswer; +import com.cloud.agent.api.StartupCommand; +import com.cloud.exception.ConnectionException; +import com.cloud.host.HostVO; +import com.cloud.utils.component.Adapter; + +public interface ResourceStateAdapter extends Adapter { + static public enum Event { + CREATE_HOST_VO_FOR_CONNECTED, + CREATE_HOST_VO_FOR_DIRECT_CONNECT, + DELETE_HOST, + } + + static public class DeleteHostAnswer { + private boolean isContinue; + private boolean isException; + + public DeleteHostAnswer(boolean isContinue) { + this.isContinue = isContinue; + this.isException = false; + } + + public DeleteHostAnswer(boolean isContinue, boolean isException) { + this.isContinue = isContinue; + this.isException = isException; + } + + public boolean getIsContinue() { + return this.isContinue; + } + + public boolean getIsException() { + return this.isException; + } + } + + public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd); + + public HostVO createHostVOForDirectConnectAgent(HostVO host, final StartupCommand[] startup, ServerResource resource, Map details, List hostTags); + + public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException; +} diff --git a/server/src/com/cloud/server/ManagementServerExt.java b/server/src/com/cloud/server/ManagementServerExt.java index ee762b08420..5f32c196e3e 100644 --- a/server/src/com/cloud/server/ManagementServerExt.java +++ b/server/src/com/cloud/server/ManagementServerExt.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server; - +package com.cloud.server; + import java.util.List; import java.util.TimeZone; @@ -19,41 +19,41 @@ import com.cloud.api.commands.GenerateUsageRecordsCmd; import com.cloud.api.commands.GetUsageRecordsCmd; import com.cloud.server.api.response.UsageTypeResponse; import com.cloud.usage.UsageVO; -public interface ManagementServerExt extends ManagementServer { - /** - * Generate Billing Records from the last time it was generated to the - * time specified. - * - * @param cmd the command wrapping the generate parameters - * - userId unique id of the user, pass in -1 to generate billing records - * for all users - * - startDate - * - endDate inclusive. If date specified is greater than the current time, the - * system will use the current time. - */ - boolean generateUsageRecords(GenerateUsageRecordsCmd cmd); - - /** - * Retrieves all Usage Records generated between the start and end date specified - * - * @param userId unique id of the user, pass in -1 to retrieve billing records - * for all users - * @param startDate inclusive. - * @param endDate inclusive. If date specified is greater than the current time, the - * system will use the current time. - * @param page The page of usage records to see (500 results are returned at a time, if - * more than 500 records exist then additional results can be retrieved by - * the appropriate page number) - * @return a list of usage records +public interface ManagementServerExt extends ManagementServer { + /** + * Generate Billing Records from the last time it was generated to the + * time specified. + * + * @param cmd the command wrapping the generate parameters + * - userId unique id of the user, pass in -1 to generate billing records + * for all users + * - startDate + * - endDate inclusive. If date specified is greater than the current time, the + * system will use the current time. + */ + boolean generateUsageRecords(GenerateUsageRecordsCmd cmd); + + /** + * Retrieves all Usage Records generated between the start and end date specified + * + * @param userId unique id of the user, pass in -1 to retrieve billing records + * for all users + * @param startDate inclusive. + * @param endDate inclusive. If date specified is greater than the current time, the + * system will use the current time. + * @param page The page of usage records to see (500 results are returned at a time, if + * more than 500 records exist then additional results can be retrieved by + * the appropriate page number) + * @return a list of usage records */ List getUsageRecords(GetUsageRecordsCmd cmd); - - /** - * Retrieves the timezone used for usage aggregation. One day is represented as midnight to 11:59:59pm - * in the given time zone - * @return the timezone specified by the config value usage.aggregation.timezone, or GMT if null - */ - TimeZone getUsageTimezone(); - List listUsageTypes(); -} + /** + * Retrieves the timezone used for usage aggregation. One day is represented as midnight to 11:59:59pm + * in the given time zone + * @return the timezone specified by the config value usage.aggregation.timezone, or GMT if null + */ + TimeZone getUsageTimezone(); + + List listUsageTypes(); +} diff --git a/server/src/com/cloud/server/ManagementServerExtImpl.java b/server/src/com/cloud/server/ManagementServerExtImpl.java index dbfd78559fd..41c03f8811b 100644 --- a/server/src/com/cloud/server/ManagementServerExtImpl.java +++ b/server/src/com/cloud/server/ManagementServerExtImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server; - +package com.cloud.server; + import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -39,64 +39,64 @@ import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.Filter; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -public class ManagementServerExtImpl extends ManagementServerImpl implements ManagementServerExt { - private final AccountDao _accountDao; - private final DomainDao _domainDao; - private final UsageDao _usageDao; - private final UsageJobDao _usageJobDao; - private final TimeZone _usageTimezone; - - protected ManagementServerExtImpl() { - super(); - - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - _accountDao = locator.getDao(AccountDao.class); - _domainDao = locator.getDao(DomainDao.class); - _usageDao = locator.getDao(UsageDao.class); - _usageJobDao = locator.getDao(UsageJobDao.class); - - Map configs = getConfigs(); - String timeZoneStr = configs.get("usage.aggregation.timezone"); - if (timeZoneStr == null) { - timeZoneStr = "GMT"; - } - _usageTimezone = TimeZone.getTimeZone(timeZoneStr); - } - - @Override - public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - try { - UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); - if (immediateJob == null) { - UsageJobVO job = _usageJobDao.getLastJob(); - - String host = null; - int pid = 0; - if (job != null) { - host = job.getHost(); - pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); - } - _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); - } - } finally { - txn.close(); - - // switch back to VMOPS_DB - Transaction swap = Transaction.open(Transaction.CLOUD_DB); - swap.close(); - } - return true; - } - + +public class ManagementServerExtImpl extends ManagementServerImpl implements ManagementServerExt { + private final AccountDao _accountDao; + private final DomainDao _domainDao; + private final UsageDao _usageDao; + private final UsageJobDao _usageJobDao; + private final TimeZone _usageTimezone; + + protected ManagementServerExtImpl() { + super(); + + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + _accountDao = locator.getDao(AccountDao.class); + _domainDao = locator.getDao(DomainDao.class); + _usageDao = locator.getDao(UsageDao.class); + _usageJobDao = locator.getDao(UsageJobDao.class); + + Map configs = getConfigs(); + String timeZoneStr = configs.get("usage.aggregation.timezone"); + if (timeZoneStr == null) { + timeZoneStr = "GMT"; + } + _usageTimezone = TimeZone.getTimeZone(timeZoneStr); + } + @Override - public List getUsageRecords(GetUsageRecordsCmd cmd) { - Long accountId = cmd.getAccountId(); - Long domainId = cmd.getDomainId(); - String accountName = cmd.getAccountName(); - Account userAccount = null; - Account caller = (Account)UserContext.current().getCaller(); + public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + try { + UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); + if (immediateJob == null) { + UsageJobVO job = _usageJobDao.getLastJob(); + + String host = null; + int pid = 0; + if (job != null) { + host = job.getHost(); + pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); + } + _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); + } + } finally { + txn.close(); + + // switch back to VMOPS_DB + Transaction swap = Transaction.open(Transaction.CLOUD_DB); + swap.close(); + } + return true; + } + + @Override + public List getUsageRecords(GetUsageRecordsCmd cmd) { + Long accountId = cmd.getAccountId(); + Long domainId = cmd.getDomainId(); + String accountName = cmd.getAccountName(); + Account userAccount = null; + Account caller = (Account)UserContext.current().getCaller(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); @@ -110,139 +110,139 @@ public class ManagementServerExtImpl extends ManagementServerImpl implements Man } accountId = project.getProjectAccountId(); } - - //if accountId is not specified, use accountName and domainId - if ((accountId == null) && (accountName != null) && (domainId != null)) { - if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { - Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); - List accounts = _accountDao.listAccounts(accountName, domainId, filter); - if(accounts.size() > 0){ - userAccount = accounts.get(0); - } - if (userAccount != null) { - accountId = userAccount.getId(); - } else { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - } else { - throw new PermissionDeniedException("Invalid Domain Id or Account"); - } - } + + //if accountId is not specified, use accountName and domainId + if ((accountId == null) && (accountName != null) && (domainId != null)) { + if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { + Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); + List accounts = _accountDao.listAccounts(accountName, domainId, filter); + if(accounts.size() > 0){ + userAccount = accounts.get(0); + } + if (userAccount != null) { + accountId = userAccount.getId(); + } else { + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + } + } else { + throw new PermissionDeniedException("Invalid Domain Id or Account"); + } + } boolean isAdmin = false; - - //If accountId couldn't be found using accountName and domainId, get it from userContext - if(accountId == null){ + + //If accountId couldn't be found using accountName and domainId, get it from userContext + if(accountId == null){ accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if(caller.getType() == Account.ACCOUNT_TYPE_ADMIN){ isAdmin = true; - } - s_logger.debug("Account details not available. Using userContext accountId: " + accountId); - } - - Date startDate = cmd.getStartDate(); + } + s_logger.debug("Account details not available. Using userContext accountId: " + accountId); + } + + Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if(startDate.after(endDate)){ throw new InvalidParameterValueException("Incorrect Date Range. Start date: "+startDate+" is after end date:"+endDate); - } - TimeZone usageTZ = getUsageTimezone(); - Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ, true); - Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ, false); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + startDate + " and " + endDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); - } - + } + TimeZone usageTZ = getUsageTimezone(); + Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ, true); + Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ, false); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + startDate + " and " + endDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); + } + Filter usageFilter = new Filter(UsageVO.class, "startDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); - if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin) { - sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); - } - - if (domainId != null) { - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); + if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin) { + sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + } + + if (domainId != null) { + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); - } - - if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { - sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); - sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); - } else { - return new ArrayList(); // return an empty list if we fail to validate the dates - } - - List usageRecords = null; - Transaction txn = Transaction.open(Transaction.USAGE_DB); - try { - usageRecords = _usageDao.searchAllRecords(sc, usageFilter); - } finally { - txn.close(); - - // switch back to VMOPS_DB - Transaction swap = Transaction.open(Transaction.CLOUD_DB); - swap.close(); - } - - // now that we are done with the records, update the command with the correct timezone so it can write the proper response - cmd.setUsageTimezone(getUsageTimezone()); - - return usageRecords; - } - - @Override - public TimeZone getUsageTimezone() { - return _usageTimezone; - } - - @Override - public String[] getApiConfig() { - return new String[] { "commands.properties", "commands-ext.properties" }; - } - - private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ, boolean adjustToDayStart) { - Calendar cal = Calendar.getInstance(); - cal.setTime(initialDate); - TimeZone localTZ = cal.getTimeZone(); - int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); - if (localTZ.inDaylightTime(initialDate)) { - timezoneOffset += (60 * 60 * 1000); - } - cal.add(Calendar.MILLISECOND, timezoneOffset); - - Date newTime = cal.getTime(); - - Calendar calTS = Calendar.getInstance(targetTZ); - calTS.setTime(newTime); - timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); - if (targetTZ.inDaylightTime(initialDate)) { - timezoneOffset += (60 * 60 * 1000); - } - - calTS.add(Calendar.MILLISECOND, -1*timezoneOffset); - if (adjustToDayStart) { - calTS.set(Calendar.HOUR_OF_DAY, 0); - calTS.set(Calendar.MINUTE, 0); - calTS.set(Calendar.SECOND, 0); - calTS.set(Calendar.MILLISECOND, 0); - } else { - calTS.set(Calendar.HOUR_OF_DAY, 23); - calTS.set(Calendar.MINUTE, 59); - calTS.set(Calendar.SECOND, 59); - calTS.set(Calendar.MILLISECOND, 999); - } - - return calTS.getTime(); + } + + if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { + sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); + sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); + } else { + return new ArrayList(); // return an empty list if we fail to validate the dates + } + + List usageRecords = null; + Transaction txn = Transaction.open(Transaction.USAGE_DB); + try { + usageRecords = _usageDao.searchAllRecords(sc, usageFilter); + } finally { + txn.close(); + + // switch back to VMOPS_DB + Transaction swap = Transaction.open(Transaction.CLOUD_DB); + swap.close(); + } + + // now that we are done with the records, update the command with the correct timezone so it can write the proper response + cmd.setUsageTimezone(getUsageTimezone()); + + return usageRecords; + } + + @Override + public TimeZone getUsageTimezone() { + return _usageTimezone; + } + + @Override + public String[] getApiConfig() { + return new String[] { "commands.properties", "commands-ext.properties" }; + } + + private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ, boolean adjustToDayStart) { + Calendar cal = Calendar.getInstance(); + cal.setTime(initialDate); + TimeZone localTZ = cal.getTimeZone(); + int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); + if (localTZ.inDaylightTime(initialDate)) { + timezoneOffset += (60 * 60 * 1000); + } + cal.add(Calendar.MILLISECOND, timezoneOffset); + + Date newTime = cal.getTime(); + + Calendar calTS = Calendar.getInstance(targetTZ); + calTS.setTime(newTime); + timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); + if (targetTZ.inDaylightTime(initialDate)) { + timezoneOffset += (60 * 60 * 1000); + } + + calTS.add(Calendar.MILLISECOND, -1*timezoneOffset); + if (adjustToDayStart) { + calTS.set(Calendar.HOUR_OF_DAY, 0); + calTS.set(Calendar.MINUTE, 0); + calTS.set(Calendar.SECOND, 0); + calTS.set(Calendar.MILLISECOND, 0); + } else { + calTS.set(Calendar.HOUR_OF_DAY, 23); + calTS.set(Calendar.MINUTE, 59); + calTS.set(Calendar.SECOND, 59); + calTS.set(Calendar.MILLISECOND, 999); + } + + return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); - } -} + } +} diff --git a/server/src/com/cloud/server/StatsCollector.java b/server/src/com/cloud/server/StatsCollector.java index b07dc2ea965..d7587556013 100755 --- a/server/src/com/cloud/server/StatsCollector.java +++ b/server/src/com/cloud/server/StatsCollector.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server; - +package com.cloud.server; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -60,74 +60,74 @@ import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VmStats; import com.cloud.vm.dao.UserVmDao; - -/** - * Provides real time stats for various agent resources up to x seconds - * - * @author Will Chan - * - */ -public class StatsCollector { - public static final Logger s_logger = Logger.getLogger(StatsCollector.class.getName()); - - private static StatsCollector s_instance = null; - - private ScheduledExecutorService _executor = null; + +/** + * Provides real time stats for various agent resources up to x seconds + * + * @author Will Chan + * + */ +public class StatsCollector { + public static final Logger s_logger = Logger.getLogger(StatsCollector.class.getName()); + + private static StatsCollector s_instance = null; + + private ScheduledExecutorService _executor = null; private final AgentManager _agentMgr; - private final UserVmManager _userVmMgr; + private final UserVmManager _userVmMgr; private final HostDao _hostDao; - private final UserVmDao _userVmDao; - private final VolumeDao _volsDao; - private final StoragePoolDao _storagePoolDao; + private final UserVmDao _userVmDao; + private final VolumeDao _volsDao; + private final StoragePoolDao _storagePoolDao; private final StorageManager _storageManager; private final StoragePoolHostDao _storagePoolHostDao; private final SecondaryStorageVmManager _ssvmMgr; - private final ResourceManager _resourceMgr; - + private final ResourceManager _resourceMgr; + private ConcurrentHashMap _hostStats = new ConcurrentHashMap(); private final ConcurrentHashMap _VmStats = new ConcurrentHashMap(); - private ConcurrentHashMap _volumeStats = new ConcurrentHashMap(); - private ConcurrentHashMap _storageStats = new ConcurrentHashMap(); - private ConcurrentHashMap _storagePoolStats = new ConcurrentHashMap(); - + private ConcurrentHashMap _volumeStats = new ConcurrentHashMap(); + private ConcurrentHashMap _storageStats = new ConcurrentHashMap(); + private ConcurrentHashMap _storagePoolStats = new ConcurrentHashMap(); + long hostStatsInterval = -1L; - long hostAndVmStatsInterval = -1L; - long storageStatsInterval = -1L; - long volumeStatsInterval = -1L; - - //private final GlobalLock m_capacityCheckLock = GlobalLock.getInternLock("capacity.check"); - - public static StatsCollector getInstance() { - return s_instance; - } - public static StatsCollector getInstance(Map configs) { - if (s_instance == null) { - s_instance = new StatsCollector(configs); - } - return s_instance; - } - - private StatsCollector(Map configs) { - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + long hostAndVmStatsInterval = -1L; + long storageStatsInterval = -1L; + long volumeStatsInterval = -1L; + + //private final GlobalLock m_capacityCheckLock = GlobalLock.getInternLock("capacity.check"); + + public static StatsCollector getInstance() { + return s_instance; + } + public static StatsCollector getInstance(Map configs) { + if (s_instance == null) { + s_instance = new StatsCollector(configs); + } + return s_instance; + } + + private StatsCollector(Map configs) { + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); _agentMgr = locator.getManager(AgentManager.class); _userVmMgr = locator.getManager(UserVmManager.class); - _ssvmMgr = locator.getManager(SecondaryStorageVmManager.class); + _ssvmMgr = locator.getManager(SecondaryStorageVmManager.class); _hostDao = locator.getDao(HostDao.class); - _userVmDao = locator.getDao(UserVmDao.class); - _volsDao = locator.getDao(VolumeDao.class); - _storagePoolDao = locator.getDao(StoragePoolDao.class); + _userVmDao = locator.getDao(UserVmDao.class); + _volsDao = locator.getDao(VolumeDao.class); + _storagePoolDao = locator.getDao(StoragePoolDao.class); _storageManager = locator.getManager(StorageManager.class); _storagePoolHostDao = locator.getDao(StoragePoolHostDao.class); - _resourceMgr = locator.getManager(ResourceManager.class); - - _executor = Executors.newScheduledThreadPool(3, new NamedThreadFactory("StatsCollector")); - - hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), 60000L); - hostAndVmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), 60000L); - storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), 60000L); - volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), -1L); + _resourceMgr = locator.getManager(ResourceManager.class); - if (hostStatsInterval > 0) { + _executor = Executors.newScheduledThreadPool(3, new NamedThreadFactory("StatsCollector")); + + hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), 60000L); + hostAndVmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), 60000L); + storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), 60000L); + volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), -1L); + + if (hostStatsInterval > 0) { _executor.scheduleWithFixedDelay(new HostCollector(), 15000L, hostStatsInterval, TimeUnit.MILLISECONDS); } @@ -135,56 +135,56 @@ public class StatsCollector { _executor.scheduleWithFixedDelay(new VmStatsCollector(), 15000L, hostAndVmStatsInterval, TimeUnit.MILLISECONDS); } - if (storageStatsInterval > 0) { + if (storageStatsInterval > 0) { _executor.scheduleWithFixedDelay(new StorageCollector(), 15000L, storageStatsInterval, TimeUnit.MILLISECONDS); - } - - // -1 means we don't even start this thread to pick up any data. - if (volumeStatsInterval > 0) { - _executor.scheduleWithFixedDelay(new VolumeCollector(), 15000L, volumeStatsInterval, TimeUnit.MILLISECONDS); - } else { - s_logger.info("Disabling volume stats collector"); - } - } - - class HostCollector implements Runnable { + } + + // -1 means we don't even start this thread to pick up any data. + if (volumeStatsInterval > 0) { + _executor.scheduleWithFixedDelay(new VolumeCollector(), 15000L, volumeStatsInterval, TimeUnit.MILLISECONDS); + } else { + s_logger.info("Disabling volume stats collector"); + } + } + + class HostCollector implements Runnable { @Override - public void run() { + public void run() { try { s_logger.debug("HostStatsCollector is running..."); - - SearchCriteria sc = _hostDao.createSearchCriteria(); + + SearchCriteria sc = _hostDao.createSearchCriteria(); sc.addAnd("status", SearchCriteria.Op.EQ, Status.Up.toString()); - sc.addAnd("resourceState", SearchCriteria.Op.NIN, ResourceState.Maintenance, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); - sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.Storage.toString()); - sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ConsoleProxy.toString()); + sc.addAnd("resourceState", SearchCriteria.Op.NIN, ResourceState.Maintenance, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); + sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.Storage.toString()); + sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ConsoleProxy.toString()); sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.SecondaryStorage.toString()); sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.LocalSecondaryStorage.toString()); - sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.TrafficMonitor.toString()); + sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.TrafficMonitor.toString()); sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.SecondaryStorageVM.toString()); sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ExternalFirewall.toString()); - sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ExternalLoadBalancer.toString()); - ConcurrentHashMap hostStats = new ConcurrentHashMap(); - List hosts = _hostDao.search(sc, null); + sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ExternalLoadBalancer.toString()); + ConcurrentHashMap hostStats = new ConcurrentHashMap(); + List hosts = _hostDao.search(sc, null); for (HostVO host : hosts) - { - HostStatsEntry stats = (HostStatsEntry) _resourceMgr.getHostStatistics(host.getId()); + { + HostStatsEntry stats = (HostStatsEntry) _resourceMgr.getHostStatistics(host.getId()); if (stats != null) - { - hostStats.put(host.getId(), stats); + { + hostStats.put(host.getId(), stats); } else - { - s_logger.warn("Received invalid host stats for host: " + host.getId()); - } - } - _hostStats = hostStats; + { + s_logger.warn("Received invalid host stats for host: " + host.getId()); + } + } + _hostStats = hostStats; } catch (Throwable t) - { - s_logger.error("Error trying to retrieve host stats", t); - } - } + { + s_logger.error("Error trying to retrieve host stats", t); + } + } } class VmStatsCollector implements Runnable { @@ -254,35 +254,35 @@ public class StatsCollector { s_logger.error("Error trying to retrieve VM stats", t); } } - } + } public VmStats getVmStats(long id) { return _VmStats.get(id); - } - - class StorageCollector implements Runnable { + } + + class StorageCollector implements Runnable { @Override - public void run() { + public void run() { try { if (s_logger.isDebugEnabled()) { s_logger.debug("StorageCollector is running..."); } - + List hosts = _ssvmMgr.listSecondaryStorageHostsInAllZones(); - ConcurrentHashMap storageStats = new ConcurrentHashMap(); + ConcurrentHashMap storageStats = new ConcurrentHashMap(); for (HostVO host : hosts) { if ( host.getStorageUrl() == null ) { continue; - } + } GetStorageStatsCommand command = new GetStorageStatsCommand(host.getStorageUrl()); HostVO ssAhost = _ssvmMgr.pickSsvmHost(host); if (ssAhost == null) { s_logger.debug("There is no secondary storage VM for secondary storage host " + host.getName()); continue; } - long hostId = host.getId(); - Answer answer = _agentMgr.easySend(ssAhost.getId(), command); - if (answer != null && answer.getResult()) { + long hostId = host.getId(); + Answer answer = _agentMgr.easySend(ssAhost.getId(), command); + if (answer != null && answer.getResult()) { storageStats.put(hostId, (StorageStats)answer); s_logger.trace("HostId: "+hostId+ " Used: " + ((StorageStats)answer).getByteUsed() + " Total Available: " + ((StorageStats)answer).getCapacityBytes()); //Seems like we have dynamically updated the sec. storage as prev. size and the current do not match @@ -290,13 +290,13 @@ public class StatsCollector { _storageStats.get(hostId).getCapacityBytes() != ((StorageStats)answer).getCapacityBytes()){ host.setTotalSize(((StorageStats)answer).getCapacityBytes()); _hostDao.update(hostId, host); - } - } - } - _storageStats = storageStats; - ConcurrentHashMap storagePoolStats = new ConcurrentHashMap(); - - List storagePools = _storagePoolDao.listAll(); + } + } + } + _storageStats = storageStats; + ConcurrentHashMap storagePoolStats = new ConcurrentHashMap(); + + List storagePools = _storagePoolDao.listAll(); for (StoragePoolVO pool: storagePools) { // check if the pool has enabled hosts List hostIds = _storageManager.getUpHostsInPool(pool.getId()); @@ -305,7 +305,7 @@ public class StatsCollector { long poolId = pool.getId(); try { Answer answer = _storageManager.sendToPool(pool, command); - if (answer != null && answer.getResult()) { + if (answer != null && answer.getResult()) { storagePoolStats.put(pool.getId(), (StorageStats)answer); // Seems like we have dynamically updated the pool size since the prev. size and the current do not match @@ -313,8 +313,8 @@ public class StatsCollector { _storagePoolStats.get(poolId).getCapacityBytes() != ((StorageStats)answer).getCapacityBytes()){ pool.setCapacityBytes(((StorageStats)answer).getCapacityBytes()); _storagePoolDao.update(pool.getId(), pool); - } - } + } + } } catch (StorageUnavailableException e) { s_logger.info("Unable to reach " + pool, e); } catch (Exception e) { @@ -322,96 +322,96 @@ public class StatsCollector { } } _storagePoolStats = storagePoolStats; - } catch (Throwable t) { - s_logger.error("Error trying to retrieve storage stats", t); - } - } - } - - public StorageStats getStorageStats(long id) { - return _storageStats.get(id); + } catch (Throwable t) { + s_logger.error("Error trying to retrieve storage stats", t); + } + } + } + + public StorageStats getStorageStats(long id) { + return _storageStats.get(id); } public HostStats getHostStats(long hostId){ return _hostStats.get(hostId); - } - - public StorageStats getStoragePoolStats(long id) { - return _storagePoolStats.get(id); - } - - class VolumeCollector implements Runnable { + } + + public StorageStats getStoragePoolStats(long id) { + return _storagePoolStats.get(id); + } + + class VolumeCollector implements Runnable { @Override - public void run() { - try { - List volumes = _volsDao.listAll(); - Map> commandsByPool = new HashMap>(); - - for (VolumeVO volume : volumes) { - List commands = commandsByPool.get(volume.getPoolId()); - if (commands == null) { - commands = new ArrayList(); - commandsByPool.put(volume.getPoolId(), commands); - } - VolumeCommand vCommand = new VolumeCommand(); - vCommand.volumeId = volume.getId(); - vCommand.command = new GetFileStatsCommand(volume); - commands.add(vCommand); - } - ConcurrentHashMap volumeStats = new ConcurrentHashMap(); - for (Iterator iter = commandsByPool.keySet().iterator(); iter.hasNext();) { + public void run() { + try { + List volumes = _volsDao.listAll(); + Map> commandsByPool = new HashMap>(); + + for (VolumeVO volume : volumes) { + List commands = commandsByPool.get(volume.getPoolId()); + if (commands == null) { + commands = new ArrayList(); + commandsByPool.put(volume.getPoolId(), commands); + } + VolumeCommand vCommand = new VolumeCommand(); + vCommand.volumeId = volume.getId(); + vCommand.command = new GetFileStatsCommand(volume); + commands.add(vCommand); + } + ConcurrentHashMap volumeStats = new ConcurrentHashMap(); + for (Iterator iter = commandsByPool.keySet().iterator(); iter.hasNext();) { Long poolId = iter.next(); - if(poolId != null) { - List commandsList = commandsByPool.get(poolId); - - long[] volumeIdArray = new long[commandsList.size()]; - Commands commands = new Commands(OnError.Continue); - for (int i = 0; i < commandsList.size(); i++) { - VolumeCommand vCommand = commandsList.get(i); - volumeIdArray[i] = vCommand.volumeId; - commands.addCommand(vCommand.command); + if(poolId != null) { + List commandsList = commandsByPool.get(poolId); + + long[] volumeIdArray = new long[commandsList.size()]; + Commands commands = new Commands(OnError.Continue); + for (int i = 0; i < commandsList.size(); i++) { + VolumeCommand vCommand = commandsList.get(i); + volumeIdArray[i] = vCommand.volumeId; + commands.addCommand(vCommand.command); } List poolhosts = _storagePoolHostDao.listByPoolId(poolId); for(StoragePoolHostVO poolhost : poolhosts) { - Answer[] answers = _agentMgr.send(poolhost.getHostId(), commands); - if (answers != null) { - long totalBytes = 0L; - for (int i = 0; i < answers.length; i++) { - if (answers[i].getResult()) { - VolumeStats vStats = (VolumeStats)answers[i]; - volumeStats.put(volumeIdArray[i], vStats); - totalBytes += vStats.getBytesUsed(); - } + Answer[] answers = _agentMgr.send(poolhost.getHostId(), commands); + if (answers != null) { + long totalBytes = 0L; + for (int i = 0; i < answers.length; i++) { + if (answers[i].getResult()) { + VolumeStats vStats = (VolumeStats)answers[i]; + volumeStats.put(volumeIdArray[i], vStats); + totalBytes += vStats.getBytesUsed(); + } } break; } } - } - } - - // We replace the existing volumeStats so that it does not grow with no bounds - _volumeStats = volumeStats; - } catch (AgentUnavailableException e) { - s_logger.debug(e.getMessage()); - } catch (Throwable t) { - s_logger.error("Error trying to retrieve volume stats", t); - } - } - } - - private class VolumeCommand { - public long volumeId; - public GetFileStatsCommand command; - } - - public VolumeStats[] getVolumeStats(long[] ids) { - VolumeStats[] stats = new VolumeStats[ids.length]; - if (volumeStatsInterval > 0) { - for (int i = 0; i < ids.length; i++) { - stats[i] = _volumeStats.get(ids[i]); - } - } - return stats; - } -} + } + } + + // We replace the existing volumeStats so that it does not grow with no bounds + _volumeStats = volumeStats; + } catch (AgentUnavailableException e) { + s_logger.debug(e.getMessage()); + } catch (Throwable t) { + s_logger.error("Error trying to retrieve volume stats", t); + } + } + } + + private class VolumeCommand { + public long volumeId; + public GetFileStatsCommand command; + } + + public VolumeStats[] getVolumeStats(long[] ids) { + VolumeStats[] stats = new VolumeStats[ids.length]; + if (volumeStatsInterval > 0) { + for (int i = 0; i < ids.length; i++) { + stats[i] = _volumeStats.get(ids[i]); + } + } + return stats; + } +} diff --git a/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java b/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java index 400267d6511..cecd5d18f7c 100644 --- a/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java +++ b/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java @@ -10,43 +10,43 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server.auth; - +package com.cloud.server.auth; + import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; - -/** - * Use this UserAuthenticator if users are already authenticated outside - * - * @author Will Chan - * - */ -@Local(value={UserAuthenticator.class}) -public abstract class DefaultUserAuthenticator implements UserAuthenticator { - private String _name = null; - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - _name = name; - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - -} + +/** + * Use this UserAuthenticator if users are already authenticated outside + * + * @author Will Chan + * + */ +@Local(value={UserAuthenticator.class}) +public abstract class DefaultUserAuthenticator implements UserAuthenticator { + private String _name = null; + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + _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/server/src/com/cloud/server/auth/LDAPUserAuthenticator.java b/server/src/com/cloud/server/auth/LDAPUserAuthenticator.java index d5fd3183b2c..a1bfc728641 100644 --- a/server/src/com/cloud/server/auth/LDAPUserAuthenticator.java +++ b/server/src/com/cloud/server/auth/LDAPUserAuthenticator.java @@ -10,150 +10,150 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server.auth; - -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.AuthenticationException; -import javax.naming.ConfigurationException; -import javax.naming.Context; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants.LDAPParams; -import com.cloud.configuration.Config; -import com.cloud.configuration.dao.ConfigurationDao; -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.crypt.DBEncryptionUtil; - - -@Local(value={UserAuthenticator.class}) -public class LDAPUserAuthenticator extends DefaultUserAuthenticator { - public static final Logger s_logger = Logger.getLogger(LDAPUserAuthenticator.class); - - private ConfigurationDao _configDao; - 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 = _userAccountDao.getUserAccount(username, domainId); - if (user == null) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId); - return false; - } - - String url = _configDao.getValue(LDAPParams.hostname.toString()); - if (url==null){ - s_logger.debug("LDAP authenticator is not configured."); - return false; - } - String port = _configDao.getValue(LDAPParams.port.toString()); - String queryFilter = _configDao.getValue(LDAPParams.queryfilter.toString()); - String searchBase = _configDao.getValue(LDAPParams.searchbase.toString()); - String useSSL = _configDao.getValue(LDAPParams.usessl.toString()); - String bindDN = _configDao.getValue(LDAPParams.dn.toString()); - String bindPasswd = DBEncryptionUtil.decrypt(_configDao.getValue(LDAPParams.passwd.toString())); - String trustStore = _configDao.getValue(LDAPParams.truststore.toString()); - String trustStorePassword = DBEncryptionUtil.decrypt(_configDao.getValue(LDAPParams.truststorepass.toString())); - - try { - // get all params - Hashtable env = new Hashtable(11); - env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); - String protocol = "ldap://" ; - if (new Boolean(useSSL)){ - env.put(Context.SECURITY_PROTOCOL, "ssl"); - protocol="ldaps://" ; - System.setProperty("javax.net.ssl.trustStore", trustStore); - System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); - } - env.put(Context.PROVIDER_URL, protocol + url + ":" + port); - - if (bindDN != null && bindPasswd != null){ - env.put(Context.SECURITY_PRINCIPAL, bindDN); - env.put(Context.SECURITY_CREDENTIALS, bindPasswd); - } - else { - // Use anonymous authentication - env.put(Context.SECURITY_AUTHENTICATION, "none"); - } - // Create the initial context - DirContext ctx = new InitialDirContext(env); - // use this context to search - - // substitute the queryFilter with this user info - queryFilter = queryFilter.replaceAll("\\%u", username); - queryFilter = queryFilter.replaceAll("\\%n", user.getFirstname() + " " + user.getLastname()); - queryFilter = queryFilter.replaceAll("\\%e", user.getEmail()); - - - SearchControls sc = new SearchControls(); - String[] searchFilter = { "dn" }; - sc.setReturningAttributes(new String[0]); //return no attributes - sc.setReturningAttributes(searchFilter); - sc.setSearchScope(SearchControls.SUBTREE_SCOPE); - sc.setCountLimit(1); - - // Search for objects with those matching attributes - NamingEnumeration answer = ctx.search(searchBase, queryFilter, sc); - SearchResult sr = (SearchResult)answer.next(); - String cn = sr.getName(); - answer.close(); - ctx.close(); - - s_logger.info("DN from LDAP =" + cn); - - // check the password - env = new Hashtable(11); - env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); - protocol = "ldap://" ; - if (new Boolean(useSSL)){ - env.put(Context.SECURITY_PROTOCOL, "ssl"); - protocol="ldaps://" ; - } - env.put(Context.PROVIDER_URL, protocol + url + ":" + port); - env.put(Context.SECURITY_PRINCIPAL, cn + "," + searchBase); - env.put(Context.SECURITY_CREDENTIALS, password); - // Create the initial context - ctx = new InitialDirContext(env); - ctx.close(); - - } catch (NamingException ne) { - ne.printStackTrace(); - s_logger.warn("Authentication failed due to " + ne.getMessage()); - return false; - } - catch (Exception e){ - e.printStackTrace(); - s_logger.warn("Unknown error encountered " + e.getMessage()); - return false; - } - - // authenticate - return true; - } - - public boolean configure(String name, Map params) - throws ConfigurationException { - super.configure(name, params); - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - _configDao = locator.getDao(ConfigurationDao.class); - _userAccountDao = locator.getDao(UserAccountDao.class); - return true; - } -} +package com.cloud.server.auth; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.AuthenticationException; +import javax.naming.ConfigurationException; +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.directory.InitialDirContext; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants.LDAPParams; +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; +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.crypt.DBEncryptionUtil; + + +@Local(value={UserAuthenticator.class}) +public class LDAPUserAuthenticator extends DefaultUserAuthenticator { + public static final Logger s_logger = Logger.getLogger(LDAPUserAuthenticator.class); + + private ConfigurationDao _configDao; + 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 = _userAccountDao.getUserAccount(username, domainId); + if (user == null) { + s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + return false; + } + + String url = _configDao.getValue(LDAPParams.hostname.toString()); + if (url==null){ + s_logger.debug("LDAP authenticator is not configured."); + return false; + } + String port = _configDao.getValue(LDAPParams.port.toString()); + String queryFilter = _configDao.getValue(LDAPParams.queryfilter.toString()); + String searchBase = _configDao.getValue(LDAPParams.searchbase.toString()); + String useSSL = _configDao.getValue(LDAPParams.usessl.toString()); + String bindDN = _configDao.getValue(LDAPParams.dn.toString()); + String bindPasswd = DBEncryptionUtil.decrypt(_configDao.getValue(LDAPParams.passwd.toString())); + String trustStore = _configDao.getValue(LDAPParams.truststore.toString()); + String trustStorePassword = DBEncryptionUtil.decrypt(_configDao.getValue(LDAPParams.truststorepass.toString())); + + try { + // get all params + Hashtable env = new Hashtable(11); + env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); + String protocol = "ldap://" ; + if (new Boolean(useSSL)){ + env.put(Context.SECURITY_PROTOCOL, "ssl"); + protocol="ldaps://" ; + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); + } + env.put(Context.PROVIDER_URL, protocol + url + ":" + port); + + if (bindDN != null && bindPasswd != null){ + env.put(Context.SECURITY_PRINCIPAL, bindDN); + env.put(Context.SECURITY_CREDENTIALS, bindPasswd); + } + else { + // Use anonymous authentication + env.put(Context.SECURITY_AUTHENTICATION, "none"); + } + // Create the initial context + DirContext ctx = new InitialDirContext(env); + // use this context to search + + // substitute the queryFilter with this user info + queryFilter = queryFilter.replaceAll("\\%u", username); + queryFilter = queryFilter.replaceAll("\\%n", user.getFirstname() + " " + user.getLastname()); + queryFilter = queryFilter.replaceAll("\\%e", user.getEmail()); + + + SearchControls sc = new SearchControls(); + String[] searchFilter = { "dn" }; + sc.setReturningAttributes(new String[0]); //return no attributes + sc.setReturningAttributes(searchFilter); + sc.setSearchScope(SearchControls.SUBTREE_SCOPE); + sc.setCountLimit(1); + + // Search for objects with those matching attributes + NamingEnumeration answer = ctx.search(searchBase, queryFilter, sc); + SearchResult sr = (SearchResult)answer.next(); + String cn = sr.getName(); + answer.close(); + ctx.close(); + + s_logger.info("DN from LDAP =" + cn); + + // check the password + env = new Hashtable(11); + env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); + protocol = "ldap://" ; + if (new Boolean(useSSL)){ + env.put(Context.SECURITY_PROTOCOL, "ssl"); + protocol="ldaps://" ; + } + env.put(Context.PROVIDER_URL, protocol + url + ":" + port); + env.put(Context.SECURITY_PRINCIPAL, cn + "," + searchBase); + env.put(Context.SECURITY_CREDENTIALS, password); + // Create the initial context + ctx = new InitialDirContext(env); + ctx.close(); + + } catch (NamingException ne) { + ne.printStackTrace(); + s_logger.warn("Authentication failed due to " + ne.getMessage()); + return false; + } + catch (Exception e){ + e.printStackTrace(); + s_logger.warn("Unknown error encountered " + e.getMessage()); + return false; + } + + // authenticate + return true; + } + + public boolean configure(String name, Map params) + throws ConfigurationException { + super.configure(name, params); + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + _configDao = locator.getDao(ConfigurationDao.class); + _userAccountDao = locator.getDao(UserAccountDao.class); + return true; + } +} diff --git a/server/src/com/cloud/server/auth/MD5UserAuthenticator.java b/server/src/com/cloud/server/auth/MD5UserAuthenticator.java index b94c002d075..1f1e65bb2dd 100644 --- a/server/src/com/cloud/server/auth/MD5UserAuthenticator.java +++ b/server/src/com/cloud/server/auth/MD5UserAuthenticator.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server.auth; - +package com.cloud.server.auth; + import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -27,64 +27,64 @@ import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; - -/** - * Simple UserAuthenticator that performs a MD5 hash of the password before - * comparing it against the local database. - * - * @author Will Chan - */ -@Local(value={UserAuthenticator.class}) -public class MD5UserAuthenticator extends DefaultUserAuthenticator { - public static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class); - - 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 = _userAccountDao.getUserAccount(username, domainId); - if (user == null) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId); - return false; - } - - MessageDigest md5; - try { - md5 = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new CloudRuntimeException("Error", e); - } - md5.reset(); - BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); - - // make sure our MD5 hash value is 32 digits long... - StringBuffer sb = new StringBuffer(); - String pwStr = pwInt.toString(16); - int padding = 32 - pwStr.length(); - for (int i = 0; i < padding; i++) { - sb.append('0'); - } + +/** + * Simple UserAuthenticator that performs a MD5 hash of the password before + * comparing it against the local database. + * + * @author Will Chan + */ +@Local(value={UserAuthenticator.class}) +public class MD5UserAuthenticator extends DefaultUserAuthenticator { + public static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class); + + 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 = _userAccountDao.getUserAccount(username, domainId); + if (user == null) { + s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + return false; + } + + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Error", e); + } + md5.reset(); + BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); + + // make sure our MD5 hash value is 32 digits long... + StringBuffer sb = new StringBuffer(); + String pwStr = pwInt.toString(16); + int padding = 32 - pwStr.length(); + for (int i = 0; i < padding; i++) { + sb.append('0'); + } sb.append(pwStr); // Will: The MD5Authenticator is now a straight pass-through comparison of the // the passwords because we will not assume that the password passed in has // already been MD5 hashed. I am keeping the above code in case this requirement changes - // or people need examples of how to MD5 hash passwords in java. - if (!user.getPassword().equals(sb.toString())) { - s_logger.debug("Password does not match"); - return false; - } - return true; - } - - public boolean configure(String name, Map params) - throws ConfigurationException { - super.configure(name, params); - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - _userAccountDao = locator.getDao(UserAccountDao.class); - return true; - } -} + // or people need examples of how to MD5 hash passwords in java. + if (!user.getPassword().equals(sb.toString())) { + s_logger.debug("Password does not match"); + return false; + } + return true; + } + + public boolean configure(String name, Map params) + throws ConfigurationException { + super.configure(name, params); + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + _userAccountDao = locator.getDao(UserAccountDao.class); + return true; + } +} diff --git a/server/src/com/cloud/server/auth/UserAuthenticator.java b/server/src/com/cloud/server/auth/UserAuthenticator.java index 520fa09ead8..0bde1a25334 100644 --- a/server/src/com/cloud/server/auth/UserAuthenticator.java +++ b/server/src/com/cloud/server/auth/UserAuthenticator.java @@ -10,25 +10,25 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.server.auth; - +package com.cloud.server.auth; + import java.util.Map; import com.cloud.utils.component.Adapter; - -/** - * which UserAuthenticator to user in components.xml. - * - * @author Will Chan - */ -public interface UserAuthenticator extends Adapter { - - /** - * - * @param username - * @param password - * @param domainId - * @return true if the user has been successfully authenticated, false otherwise - */ - public boolean authenticate(String username, String password, Long domainId, Map requestParameters); -} + +/** + * which UserAuthenticator to user in components.xml. + * + * @author Will Chan + */ +public interface UserAuthenticator extends Adapter { + + /** + * + * @param username + * @param password + * @param domainId + * @return true if the user has been successfully authenticated, false otherwise + */ + public boolean authenticate(String username, String password, Long domainId, Map requestParameters); +} diff --git a/server/src/com/cloud/service/ServiceOfferingVO.java b/server/src/com/cloud/service/ServiceOfferingVO.java index d51c17e613e..19305ac814f 100755 --- a/server/src/com/cloud/service/ServiceOfferingVO.java +++ b/server/src/com/cloud/service/ServiceOfferingVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.service; - +package com.cloud.service; + import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -22,29 +22,29 @@ import javax.persistence.Transient; import com.cloud.offering.ServiceOffering; import com.cloud.storage.DiskOfferingVO; import com.cloud.vm.VirtualMachine; - + @Entity @Table(name="service_offering") @DiscriminatorValue(value="Service") @PrimaryKeyJoinColumn(name="id") -public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering { - @Column(name="cpu") - private int cpu; - - @Column(name="speed") - private int speed; - - @Column(name="ram_size") - private int ramSize; - - @Column(name="nw_rate") - private Integer rateMbps; - - @Column(name="mc_rate") - private Integer multicastRateMbps; - - @Column(name="ha_enabled") - private boolean offerHA; +public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering { + @Column(name="cpu") + private int cpu; + + @Column(name="speed") + private int speed; + + @Column(name="ram_size") + private int ramSize; + + @Column(name="nw_rate") + private Integer rateMbps; + + @Column(name="mc_rate") + private Integer multicastRateMbps; + + @Column(name="ha_enabled") + private boolean offerHA; @Column(name="limit_cpu_use") private boolean limitCpuUse; @@ -60,23 +60,23 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering @Column(name="sort_key") int sortKey; - + protected ServiceOfferingVO() { - super(); - } - + super(); + } + public ServiceOfferingVO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vm_type, boolean defaultUse) { - super(name, displayText, false, tags, recreatable, useLocalStorage, systemUse, true); - this.cpu = cpu; - this.ramSize = ramSize; - this.speed = speed; - this.rateMbps = rateMbps; - this.multicastRateMbps = multicastRateMbps; + super(name, displayText, false, tags, recreatable, useLocalStorage, systemUse, true); + this.cpu = cpu; + this.ramSize = ramSize; + this.speed = speed; + this.rateMbps = rateMbps; + this.multicastRateMbps = multicastRateMbps; this.offerHA = offerHA; this.limitCpuUse = false; this.default_use = defaultUse; - this.vm_type = vm_type == null ? null : vm_type.toString().toLowerCase(); - } + this.vm_type = vm_type == null ? null : vm_type.toString().toLowerCase(); + } public ServiceOfferingVO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, boolean limitCpuUse, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vm_type, Long domainId) { super(name, displayText, false, tags, recreatable, useLocalStorage, systemUse, true, domainId); @@ -93,16 +93,16 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering public ServiceOfferingVO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, boolean limitResourceUse, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vm_type, Long domainId, String hostTag) { this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, limitResourceUse, displayText, useLocalStorage, recreatable, tags, systemUse, vm_type, domainId); this.hostTag = hostTag; - } + } - @Override - public boolean getOfferHA() { - return offerHA; - } + @Override + public boolean getOfferHA() { + return offerHA; + } public void setOfferHA(boolean offerHA) { this.offerHA = offerHA; - } + } @Override public boolean getLimitCpuUse() { @@ -117,7 +117,7 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering public boolean getDefaultUse() { return default_use; } - + @Override @Transient public String[] getTagsArray() { @@ -127,51 +127,51 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering } return tags.split(","); - } - - @Override - public int getCpu() { - return cpu; - } - - public void setCpu(int cpu) { - this.cpu = cpu; - } - - public void setSpeed(int speed) { - this.speed = speed; - } - - public void setRamSize(int ramSize) { - this.ramSize = ramSize; - } - - @Override - public int getSpeed() { - return speed; - } - - @Override - public int getRamSize() { - return ramSize; - } - - public void setRateMbps(Integer rateMbps) { - this.rateMbps = rateMbps; - } - - @Override - public Integer getRateMbps() { - return rateMbps; - } - - public void setMulticastRateMbps(Integer multicastRateMbps) { - this.multicastRateMbps = multicastRateMbps; } @Override - public Integer getMulticastRateMbps() { - return multicastRateMbps; + public int getCpu() { + return cpu; + } + + public void setCpu(int cpu) { + this.cpu = cpu; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + + public void setRamSize(int ramSize) { + this.ramSize = ramSize; + } + + @Override + public int getSpeed() { + return speed; + } + + @Override + public int getRamSize() { + return ramSize; + } + + public void setRateMbps(Integer rateMbps) { + this.rateMbps = rateMbps; + } + + @Override + public Integer getRateMbps() { + return rateMbps; + } + + public void setMulticastRateMbps(Integer multicastRateMbps) { + this.multicastRateMbps = multicastRateMbps; + } + + @Override + public Integer getMulticastRateMbps() { + return multicastRateMbps; } public void setHostTag(String hostTag) { @@ -193,5 +193,5 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering public int getSortKey() { return sortKey; } - -} + +} diff --git a/server/src/com/cloud/service/dao/ServiceOfferingDao.java b/server/src/com/cloud/service/dao/ServiceOfferingDao.java index 05364dae57f..1a3e5135071 100644 --- a/server/src/com/cloud/service/dao/ServiceOfferingDao.java +++ b/server/src/com/cloud/service/dao/ServiceOfferingDao.java @@ -10,21 +10,21 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.service.dao; - +package com.cloud.service.dao; + import java.util.List; import com.cloud.service.ServiceOfferingVO; import com.cloud.utils.db.GenericDao; - -/* - * Data Access Object for service_offering table - */ + +/* + * Data Access Object for service_offering table + */ public interface ServiceOfferingDao extends GenericDao { ServiceOfferingVO findByName(String name); ServiceOfferingVO persistSystemServiceOffering(ServiceOfferingVO vo); List findPublicServiceOfferings(); List findServiceOfferingByDomainId(Long domainId); List findSystemOffering(Long domainId, Boolean isSystem, String vm_type); - ServiceOfferingVO persistDeafultServiceOffering(ServiceOfferingVO offering); -} + ServiceOfferingVO persistDeafultServiceOffering(ServiceOfferingVO offering); +} diff --git a/server/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java b/server/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java index 3f6a8e2287e..19d3bca6b4a 100644 --- a/server/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java +++ b/server/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.service.dao; - +package com.cloud.service.dao; + import java.util.Date; import java.util.List; @@ -26,17 +26,17 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={ServiceOfferingDao.class}) @DB(txn=false) -public class ServiceOfferingDaoImpl extends GenericDaoBase implements ServiceOfferingDao { - protected static final Logger s_logger = Logger.getLogger(ServiceOfferingDaoImpl.class); + +@Local(value={ServiceOfferingDao.class}) @DB(txn=false) +public class ServiceOfferingDaoImpl extends GenericDaoBase implements ServiceOfferingDao { + protected static final Logger s_logger = Logger.getLogger(ServiceOfferingDaoImpl.class); protected final SearchBuilder UniqueNameSearch; protected final SearchBuilder ServiceOfferingsByDomainIdSearch; protected final SearchBuilder SystemServiceOffering; protected final SearchBuilder ServiceOfferingsByKeywordSearch; protected final SearchBuilder PublicServiceOfferingSearch; - + protected ServiceOfferingDaoImpl() { super(); @@ -147,5 +147,5 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase

Console access will be ready in a few minutes. Please try it again later.

"); - return; - } + } + } + } + + private void handleAccessRequest(HttpServletRequest req, HttpServletResponse resp, long vmId) { + VMInstanceVO vm = _vmMgr.findById(vmId); + if(vm == null) { + s_logger.warn("VM " + vmId + " does not exist, sending blank response for console access request"); + sendResponse(resp, ""); + return; + } + + if(vm.getHostId() == null) { + s_logger.warn("VM " + vmId + " lost host info, sending blank response for console access request"); + sendResponse(resp, ""); + return; + } + + HostVO host = _ms.getHostBy(vm.getHostId()); + if(host == null) { + s_logger.warn("VM " + vmId + "'s host does not exist, sending blank response for console access request"); + sendResponse(resp, ""); + return; + } + + String rootUrl = _ms.getConsoleAccessUrlRoot(vmId); + if(rootUrl == null) { + sendResponse(resp, "

Console access will be ready in a few minutes. Please try it again later.

"); + return; + } String vmName = vm.getHostName(); if(vm.getType() == VirtualMachine.Type.User) { @@ -370,14 +370,14 @@ public class ConsoleProxyServlet extends HttpServlet { private void sendResponse(HttpServletResponse resp, String content) { try { resp.setContentType("text/html"); - resp.getWriter().print(content); - } catch(IOException e) { + resp.getWriter().print(content); + } catch(IOException e) { if(s_logger.isInfoEnabled()) { s_logger.info("Client may already close the connection"); - } - } - } - + } + } + } + private boolean checkSessionPermision(HttpServletRequest req, long vmId, Account accountObj) { VMInstanceVO vm = _vmMgr.findById(vmId); @@ -421,15 +421,15 @@ public class ConsoleProxyServlet extends HttpServlet { return false; } - return true; - } - - private boolean isValidCmd(String cmd) { + return true; + } + + private boolean isValidCmd(String cmd) { if(cmd.equalsIgnoreCase("thumbnail") || cmd.equalsIgnoreCase("access") || cmd.equalsIgnoreCase("auth")) { return true; - } - - return false; + } + + return false; } public boolean verifyUser(Long userId) { @@ -563,4 +563,4 @@ public class ConsoleProxyServlet extends HttpServlet { } return sb.toString(); } -} +} diff --git a/server/src/com/cloud/storage/OCFS2Manager.java b/server/src/com/cloud/storage/OCFS2Manager.java index 840b7489ff4..4497978bcd0 100755 --- a/server/src/com/cloud/storage/OCFS2Manager.java +++ b/server/src/com/cloud/storage/OCFS2Manager.java @@ -10,18 +10,18 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - -import java.util.List; -import java.util.Map; - -import com.cloud.host.HostVO; -import com.cloud.utils.component.Manager; - -public interface OCFS2Manager extends Manager { - static final String CLUSTER_NAME = "clusterName"; - - boolean prepareNodes(List hosts, StoragePool pool); - - boolean prepareNodes(Long clusterId); -} +package com.cloud.storage; + +import java.util.List; +import java.util.Map; + +import com.cloud.host.HostVO; +import com.cloud.utils.component.Manager; + +public interface OCFS2Manager extends Manager { + static final String CLUSTER_NAME = "clusterName"; + + boolean prepareNodes(List hosts, StoragePool pool); + + boolean prepareNodes(Long clusterId); +} diff --git a/server/src/com/cloud/storage/OCFS2ManagerImpl.java b/server/src/com/cloud/storage/OCFS2ManagerImpl.java index d078731342b..b7c81c5a38a 100755 --- a/server/src/com/cloud/storage/OCFS2ManagerImpl.java +++ b/server/src/com/cloud/storage/OCFS2ManagerImpl.java @@ -10,218 +10,218 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - -import java.net.URI; -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.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.PrepareOCFS2NodesCommand; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceListener; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ServerResource; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.dao.StoragePoolDao; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.Ternary; -import com.cloud.utils.component.Inject; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value ={OCFS2Manager.class}) -public class OCFS2ManagerImpl implements OCFS2Manager, ResourceListener { - String _name; - private static final Logger s_logger = Logger.getLogger(OCFS2ManagerImpl.class); - - @Inject ClusterDetailsDao _clusterDetailsDao; - @Inject AgentManager _agentMgr; - @Inject HostDao _hostDao; - @Inject ClusterDao _clusterDao; - @Inject ResourceManager _resourceMgr; - @Inject StoragePoolHostDao _poolHostDao; - @Inject StoragePoolDao _poolDao; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } - - @Override - public boolean start() { - _resourceMgr.registerResourceEvent(ResourceListener.EVENT_DELETE_HOST_AFTER, this); - return true; - } - - @Override - public boolean stop() { - _resourceMgr.unregisterResourceEvent(this); - return true; - } - - @Override - public String getName() { - return _name; - } - - private List> marshalNodes(List hosts) { - Integer i = 0; - List> lst = new ArrayList>(); - for (HostVO h : hosts) { - /** - * Don't show "node" in node name otherwise OVM's utils/config_o2cb.sh will be going crazy - */ - String nodeName = "ovm_" + h.getPrivateIpAddress().replace(".", "_"); - Ternary node = new Ternary(i, h.getPrivateIpAddress(), nodeName); - lst.add(node); - i ++; - } - return lst; - } - - - private boolean prepareNodes(String clusterName, List hosts) { - PrepareOCFS2NodesCommand cmd = new PrepareOCFS2NodesCommand(clusterName, marshalNodes(hosts)); - for (HostVO h : hosts) { - Answer ans = _agentMgr.easySend(h.getId(), cmd); - if (ans == null) { - s_logger.debug("Host " + h.getId() + " is not in UP state, skip preparing OCFS2 node on it"); - continue; - } - if (!ans.getResult()) { - s_logger.warn("PrepareOCFS2NodesCommand failed on host " + h.getId() + " " + ans.getDetails()); - return false; - } - } - - return true; - } - - private String getClusterName(Long clusterId) { - ClusterVO cluster = _clusterDao.findById(clusterId); - if (cluster == null) { - throw new CloudRuntimeException("Cannot get cluster for id " + clusterId); - } - - String clusterName = "OvmCluster" + cluster.getId(); - return clusterName; - } - - @Override - public boolean prepareNodes(List hosts, StoragePool pool) { - if (pool.getPoolType() != StoragePoolType.OCFS2) { - throw new CloudRuntimeException("None OCFS2 storage pool is getting into OCFS2 manager!"); - } - - return prepareNodes(getClusterName(pool.getClusterId()), hosts); - } - - @Override - public boolean prepareNodes(Long clusterId) { - ClusterVO cluster = _clusterDao.findById(clusterId); - if (cluster == null) { - throw new CloudRuntimeException("Cannot find cluster for ID " + clusterId); - } - - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cluster.getPodId()); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, cluster.getDataCenterId()); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); - List hosts = sc.list(); - if (hosts.isEmpty()) { - s_logger.debug("There is no host in cluster " + clusterId + ", no need to prepare OCFS2 nodes"); - return true; - } - - return prepareNodes(getClusterName(clusterId), hosts); - } - - @Override - public void processDiscoverEventBefore(Long dcid, Long podId, Long clusterId, URI uri, String username, String password, List hostTags) { - // TODO Auto-generated method stub - - } - - @Override - public void processDiscoverEventAfter(Map> resources) { - // TODO Auto-generated method stub - - } - - @Override - public void processDeleteHostEventBefore(HostVO host) { - // TODO Auto-generated method stub - - } - - @Override - public void processDeletHostEventAfter(HostVO host) { - String errMsg = String.format("Prepare OCFS2 nodes failed after delete host %1$s (zone:%2$s, pod:%3$s, cluster:%4$s", host.getId(), host.getDataCenterId(), host.getPodId(), host.getClusterId()); - - if (host.getHypervisorType() != HypervisorType.Ovm) { - return; - } - - boolean hasOcfs2 = false; - List poolRefs = _poolHostDao.listByHostId(host.getId()); - for (StoragePoolHostVO poolRef : poolRefs) { - StoragePoolVO pool = _poolDao.findById(poolRef.getPoolId()); - if (pool.getPoolType() == StoragePoolType.OCFS2) { - hasOcfs2 = true; - break; - } - } - - if (hasOcfs2) { - try { - if (!prepareNodes(host.getClusterId())) { - s_logger.warn(errMsg); - } - } catch (Exception e) { - s_logger.error(errMsg, e); - } - } - } - - @Override - public void processCancelMaintenaceEventBefore(Long hostId) { - // TODO Auto-generated method stub - - } - - @Override - public void processCancelMaintenaceEventAfter(Long hostId) { - // TODO Auto-generated method stub - - } - - @Override - public void processPrepareMaintenaceEventBefore(Long hostId) { - // TODO Auto-generated method stub - - } - - @Override - public void processPrepareMaintenaceEventAfter(Long hostId) { - // TODO Auto-generated method stub - - } -} +package com.cloud.storage; + +import java.net.URI; +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.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.PrepareOCFS2NodesCommand; +import com.cloud.dc.ClusterDetailsDao; +import com.cloud.dc.ClusterVO; +import com.cloud.dc.dao.ClusterDao; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.resource.ResourceListener; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ServerResource; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.dao.StoragePoolDao; +import com.cloud.storage.dao.StoragePoolHostDao; +import com.cloud.utils.Ternary; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.exception.CloudRuntimeException; + +@Local(value ={OCFS2Manager.class}) +public class OCFS2ManagerImpl implements OCFS2Manager, ResourceListener { + String _name; + private static final Logger s_logger = Logger.getLogger(OCFS2ManagerImpl.class); + + @Inject ClusterDetailsDao _clusterDetailsDao; + @Inject AgentManager _agentMgr; + @Inject HostDao _hostDao; + @Inject ClusterDao _clusterDao; + @Inject ResourceManager _resourceMgr; + @Inject StoragePoolHostDao _poolHostDao; + @Inject StoragePoolDao _poolDao; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public boolean start() { + _resourceMgr.registerResourceEvent(ResourceListener.EVENT_DELETE_HOST_AFTER, this); + return true; + } + + @Override + public boolean stop() { + _resourceMgr.unregisterResourceEvent(this); + return true; + } + + @Override + public String getName() { + return _name; + } + + private List> marshalNodes(List hosts) { + Integer i = 0; + List> lst = new ArrayList>(); + for (HostVO h : hosts) { + /** + * Don't show "node" in node name otherwise OVM's utils/config_o2cb.sh will be going crazy + */ + String nodeName = "ovm_" + h.getPrivateIpAddress().replace(".", "_"); + Ternary node = new Ternary(i, h.getPrivateIpAddress(), nodeName); + lst.add(node); + i ++; + } + return lst; + } + + + private boolean prepareNodes(String clusterName, List hosts) { + PrepareOCFS2NodesCommand cmd = new PrepareOCFS2NodesCommand(clusterName, marshalNodes(hosts)); + for (HostVO h : hosts) { + Answer ans = _agentMgr.easySend(h.getId(), cmd); + if (ans == null) { + s_logger.debug("Host " + h.getId() + " is not in UP state, skip preparing OCFS2 node on it"); + continue; + } + if (!ans.getResult()) { + s_logger.warn("PrepareOCFS2NodesCommand failed on host " + h.getId() + " " + ans.getDetails()); + return false; + } + } + + return true; + } + + private String getClusterName(Long clusterId) { + ClusterVO cluster = _clusterDao.findById(clusterId); + if (cluster == null) { + throw new CloudRuntimeException("Cannot get cluster for id " + clusterId); + } + + String clusterName = "OvmCluster" + cluster.getId(); + return clusterName; + } + + @Override + public boolean prepareNodes(List hosts, StoragePool pool) { + if (pool.getPoolType() != StoragePoolType.OCFS2) { + throw new CloudRuntimeException("None OCFS2 storage pool is getting into OCFS2 manager!"); + } + + return prepareNodes(getClusterName(pool.getClusterId()), hosts); + } + + @Override + public boolean prepareNodes(Long clusterId) { + ClusterVO cluster = _clusterDao.findById(clusterId); + if (cluster == null) { + throw new CloudRuntimeException("Cannot find cluster for ID " + clusterId); + } + + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); + sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cluster.getPodId()); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, cluster.getDataCenterId()); + sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + List hosts = sc.list(); + if (hosts.isEmpty()) { + s_logger.debug("There is no host in cluster " + clusterId + ", no need to prepare OCFS2 nodes"); + return true; + } + + return prepareNodes(getClusterName(clusterId), hosts); + } + + @Override + public void processDiscoverEventBefore(Long dcid, Long podId, Long clusterId, URI uri, String username, String password, List hostTags) { + // TODO Auto-generated method stub + + } + + @Override + public void processDiscoverEventAfter(Map> resources) { + // TODO Auto-generated method stub + + } + + @Override + public void processDeleteHostEventBefore(HostVO host) { + // TODO Auto-generated method stub + + } + + @Override + public void processDeletHostEventAfter(HostVO host) { + String errMsg = String.format("Prepare OCFS2 nodes failed after delete host %1$s (zone:%2$s, pod:%3$s, cluster:%4$s", host.getId(), host.getDataCenterId(), host.getPodId(), host.getClusterId()); + + if (host.getHypervisorType() != HypervisorType.Ovm) { + return; + } + + boolean hasOcfs2 = false; + List poolRefs = _poolHostDao.listByHostId(host.getId()); + for (StoragePoolHostVO poolRef : poolRefs) { + StoragePoolVO pool = _poolDao.findById(poolRef.getPoolId()); + if (pool.getPoolType() == StoragePoolType.OCFS2) { + hasOcfs2 = true; + break; + } + } + + if (hasOcfs2) { + try { + if (!prepareNodes(host.getClusterId())) { + s_logger.warn(errMsg); + } + } catch (Exception e) { + s_logger.error(errMsg, e); + } + } + } + + @Override + public void processCancelMaintenaceEventBefore(Long hostId) { + // TODO Auto-generated method stub + + } + + @Override + public void processCancelMaintenaceEventAfter(Long hostId) { + // TODO Auto-generated method stub + + } + + @Override + public void processPrepareMaintenaceEventBefore(Long hostId) { + // TODO Auto-generated method stub + + } + + @Override + public void processPrepareMaintenaceEventAfter(Long hostId) { + // TODO Auto-generated method stub + + } +} diff --git a/server/src/com/cloud/storage/StorageManager.java b/server/src/com/cloud/storage/StorageManager.java index 0ffa368db8d..2fa5c350b23 100755 --- a/server/src/com/cloud/storage/StorageManager.java +++ b/server/src/com/cloud/storage/StorageManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.List; import com.cloud.agent.api.Answer; @@ -38,159 +38,159 @@ import com.cloud.vm.DiskProfile; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; - -public interface StorageManager extends StorageService, Manager { - boolean canVmRestartOnAnotherServer(long vmId); - - /** Returns the absolute path of the specified ISO - * @param templateId - the ID of the template that represents the ISO - * @param datacenterId - * @return absolute ISO path - */ - public Pair getAbsoluteIsoPath(long templateId, long dataCenterId); - - /** - * Returns the URL of the secondary storage host - * @param zoneId - * @return URL - */ - public String getSecondaryStorageURL(long zoneId); - - /** - * Returns a comma separated list of tags for the specified storage pool - * @param poolId - * @return comma separated list of tags - */ - public String getStoragePoolTags(long poolId); - - /** - * Returns the secondary storage host - * @param zoneId - * @return secondary storage host - */ - public HostVO getSecondaryStorageHost(long zoneId); - - /** - * Returns the secondary storage host - * @param zoneId - * @return secondary storage host - */ - public VMTemplateHostVO findVmTemplateHost(long templateId, StoragePool pool); - - /** - * Moves a volume from its current storage pool to a storage pool with enough capacity in the specified zone, pod, or cluster - * @param volume - * @param destPoolDcId - * @param destPoolPodId - * @param destPoolClusterId - * @return VolumeVO - * @throws ConcurrentOperationException - */ - VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) throws ConcurrentOperationException; - - /** - * Create a volume based on the given criteria - * @param volume - * @param vm - * @param template - * @param dc - * @param pod - * @param clusterId - * @param offering - * @param diskOffering - * @param avoids - * @param size - * @param hyperType - * @return volume VO if success, null otherwise - */ - VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, - ServiceOfferingVO offering, DiskOfferingVO diskOffering, List avoids, long size, HypervisorType hyperType); - - /** - * Marks the specified volume as destroyed in the management server database. The expunge thread will delete the volume from its storage pool. + +public interface StorageManager extends StorageService, Manager { + boolean canVmRestartOnAnotherServer(long vmId); + + /** Returns the absolute path of the specified ISO + * @param templateId - the ID of the template that represents the ISO + * @param datacenterId + * @return absolute ISO path + */ + public Pair getAbsoluteIsoPath(long templateId, long dataCenterId); + + /** + * Returns the URL of the secondary storage host + * @param zoneId + * @return URL + */ + public String getSecondaryStorageURL(long zoneId); + + /** + * Returns a comma separated list of tags for the specified storage pool + * @param poolId + * @return comma separated list of tags + */ + public String getStoragePoolTags(long poolId); + + /** + * Returns the secondary storage host + * @param zoneId + * @return secondary storage host + */ + public HostVO getSecondaryStorageHost(long zoneId); + + /** + * Returns the secondary storage host + * @param zoneId + * @return secondary storage host + */ + public VMTemplateHostVO findVmTemplateHost(long templateId, StoragePool pool); + + /** + * Moves a volume from its current storage pool to a storage pool with enough capacity in the specified zone, pod, or cluster * @param volume - * @return - */ - boolean destroyVolume(VolumeVO volume) throws ConcurrentOperationException; - - /** Create capacity entries in the op capacity table - * @param storagePool - */ - public void createCapacityEntry(StoragePoolVO storagePool); - - /** - * Checks that the volume is stored on a shared storage pool - * @param volume - * @return true if the volume is on a shared storage pool, false otherwise - */ - boolean volumeOnSharedStoragePool(VolumeVO volume); - - Answer sendToPool(long poolId, Command cmd) throws StorageUnavailableException; - Answer sendToPool(StoragePool pool, Command cmd) throws StorageUnavailableException; - Answer[] sendToPool(long poolId, Commands cmd) throws StorageUnavailableException; - Answer[] sendToPool(StoragePool pool, Commands cmds) throws StorageUnavailableException; - Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Commands cmds) throws StorageUnavailableException; - Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Command cmd) throws StorageUnavailableException; - - /** - * Checks that one of the following is true: - * 1. The volume is not attached to any VM - * 2. The volume is attached to a VM that is running on a host with the KVM hypervisor, and the VM is stopped - * 3. The volume is attached to a VM that is running on a host with the XenServer hypervisor (the VM can be stopped or running) - * @return true if one of the above conditions is true - */ - boolean volumeInactive(VolumeVO volume); - - String getVmNameOnVolume(VolumeVO volume); - - /** - * Checks if a host has running VMs that are using its local storage pool. - * @return true if local storage is active on the host - */ - boolean isLocalStorageActiveOnHost(Host host); - - /** - * Cleans up storage pools by removing unused templates. - * @param recurring - true if this cleanup is part of a recurring garbage collection thread - */ - void cleanupStorage(boolean recurring); - - String getPrimaryStorageNameLabel(VolumeVO volume); - - /** - * Allocates one volume. - * @param - * @param type - * @param offering - * @param name - * @param size - * @param template - * @param vm - * @param account - * @return VolumeVO a persisted volume. - */ - DiskProfile allocateRawVolume(Type type, String name, DiskOfferingVO offering, Long size, T vm, Account owner); - DiskProfile allocateTemplatedVolume(Type type, String name, DiskOfferingVO offering, VMTemplateVO template, T vm, Account owner); - - void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated); - - - void prepare(VirtualMachineProfile vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException, ConcurrentOperationException; - - void release(VirtualMachineProfile profile); - - void cleanupVolumes(long vmId) throws ConcurrentOperationException; - - void prepareForMigration(VirtualMachineProfile vm, DeployDestination dest); - - Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException; - - CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId); - - CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId); - - boolean createStoragePool(long hostId, StoragePoolVO pool); - + * @param destPoolDcId + * @param destPoolPodId + * @param destPoolClusterId + * @return VolumeVO + * @throws ConcurrentOperationException + */ + VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) throws ConcurrentOperationException; + + /** + * Create a volume based on the given criteria + * @param volume + * @param vm + * @param template + * @param dc + * @param pod + * @param clusterId + * @param offering + * @param diskOffering + * @param avoids + * @param size + * @param hyperType + * @return volume VO if success, null otherwise + */ + VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, + ServiceOfferingVO offering, DiskOfferingVO diskOffering, List avoids, long size, HypervisorType hyperType); + + /** + * Marks the specified volume as destroyed in the management server database. The expunge thread will delete the volume from its storage pool. + * @param volume + * @return + */ + boolean destroyVolume(VolumeVO volume) throws ConcurrentOperationException; + + /** Create capacity entries in the op capacity table + * @param storagePool + */ + public void createCapacityEntry(StoragePoolVO storagePool); + + /** + * Checks that the volume is stored on a shared storage pool + * @param volume + * @return true if the volume is on a shared storage pool, false otherwise + */ + boolean volumeOnSharedStoragePool(VolumeVO volume); + + Answer sendToPool(long poolId, Command cmd) throws StorageUnavailableException; + Answer sendToPool(StoragePool pool, Command cmd) throws StorageUnavailableException; + Answer[] sendToPool(long poolId, Commands cmd) throws StorageUnavailableException; + Answer[] sendToPool(StoragePool pool, Commands cmds) throws StorageUnavailableException; + Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Commands cmds) throws StorageUnavailableException; + Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Command cmd) throws StorageUnavailableException; + + /** + * Checks that one of the following is true: + * 1. The volume is not attached to any VM + * 2. The volume is attached to a VM that is running on a host with the KVM hypervisor, and the VM is stopped + * 3. The volume is attached to a VM that is running on a host with the XenServer hypervisor (the VM can be stopped or running) + * @return true if one of the above conditions is true + */ + boolean volumeInactive(VolumeVO volume); + + String getVmNameOnVolume(VolumeVO volume); + + /** + * Checks if a host has running VMs that are using its local storage pool. + * @return true if local storage is active on the host + */ + boolean isLocalStorageActiveOnHost(Host host); + + /** + * Cleans up storage pools by removing unused templates. + * @param recurring - true if this cleanup is part of a recurring garbage collection thread + */ + void cleanupStorage(boolean recurring); + + String getPrimaryStorageNameLabel(VolumeVO volume); + + /** + * Allocates one volume. + * @param + * @param type + * @param offering + * @param name + * @param size + * @param template + * @param vm + * @param account + * @return VolumeVO a persisted volume. + */ + DiskProfile allocateRawVolume(Type type, String name, DiskOfferingVO offering, Long size, T vm, Account owner); + DiskProfile allocateTemplatedVolume(Type type, String name, DiskOfferingVO offering, VMTemplateVO template, T vm, Account owner); + + void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated); + + + void prepare(VirtualMachineProfile vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException, ConcurrentOperationException; + + void release(VirtualMachineProfile profile); + + void cleanupVolumes(long vmId) throws ConcurrentOperationException; + + void prepareForMigration(VirtualMachineProfile vm, DeployDestination dest); + + Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException; + + CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId); + + CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId); + + boolean createStoragePool(long hostId, StoragePoolVO pool); + boolean delPoolFromHost(long hostId); HostVO getSecondaryStorageHost(long zoneId, long tmpltId); @@ -220,4 +220,4 @@ public interface StorageManager extends StorageService, Manager { List getUpHostsInPool(long poolId); void cleanupSecondaryStorage(boolean recurring); -} +} diff --git a/server/src/com/cloud/storage/dao/DiskOfferingDao.java b/server/src/com/cloud/storage/dao/DiskOfferingDao.java index b31d21eae65..1d3747816ad 100644 --- a/server/src/com/cloud/storage/dao/DiskOfferingDao.java +++ b/server/src/com/cloud/storage/dao/DiskOfferingDao.java @@ -10,18 +10,18 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.util.List; import com.cloud.storage.DiskOfferingVO; import com.cloud.utils.db.GenericDao; - -public interface DiskOfferingDao extends GenericDao { + +public interface DiskOfferingDao extends GenericDao { List listByDomainId(long domainId); List findPrivateDiskOffering(); List findPublicDiskOfferings(); DiskOfferingVO findByUniqueName(String uniqueName); DiskOfferingVO persistDeafultDiskOffering(DiskOfferingVO offering); - -} + +} diff --git a/server/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java b/server/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java index 6ecd8d650f3..654c51be7ab 100644 --- a/server/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java +++ b/server/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.util.Date; import java.util.List; @@ -28,21 +28,21 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; - -@Local(value={DiskOfferingDao.class}) -public class DiskOfferingDaoImpl extends GenericDaoBase implements DiskOfferingDao { + +@Local(value={DiskOfferingDao.class}) +public class DiskOfferingDaoImpl extends GenericDaoBase implements DiskOfferingDao { private static final Logger s_logger = Logger.getLogger(DiskOfferingDaoImpl.class); - + private final SearchBuilder DomainIdSearch; private final SearchBuilder PrivateDiskOfferingSearch; private final SearchBuilder PublicDiskOfferingSearch; protected final SearchBuilder UniqueNameSearch; - private final Attribute _typeAttr; - - protected DiskOfferingDaoImpl() { - DomainIdSearch = createSearchBuilder(); + private final Attribute _typeAttr; + + protected DiskOfferingDaoImpl() { + DomainIdSearch = createSearchBuilder(); DomainIdSearch.and("domainId", DomainIdSearch.entity().getDomainId(), SearchCriteria.Op.EQ); - DomainIdSearch.and("removed", DomainIdSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + DomainIdSearch.and("removed", DomainIdSearch.entity().getRemoved(), SearchCriteria.Op.NULL); DomainIdSearch.done(); PrivateDiskOfferingSearch = createSearchBuilder(); @@ -60,14 +60,14 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im UniqueNameSearch.done(); _typeAttr = _allAttributes.get("type"); - } - - @Override - public List listByDomainId(long domainId) { - SearchCriteria sc = DomainIdSearch.create(); - sc.setParameters("domainId", domainId); - // FIXME: this should not be exact match, but instead should find all available disk offerings from parent domains - return listBy(sc); + } + + @Override + public List listByDomainId(long domainId) { + SearchCriteria sc = DomainIdSearch.create(); + sc.setParameters("domainId", domainId); + // FIXME: this should not be exact match, but instead should find all available disk offerings from parent domains + return listBy(sc); } @Override @@ -142,5 +142,5 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im diskOffering.setRemoved(new Date()); return update(id, diskOffering); - } -} + } +} diff --git a/server/src/com/cloud/storage/dao/LaunchPermissionDao.java b/server/src/com/cloud/storage/dao/LaunchPermissionDao.java index e379cffd595..44f75aa793c 100644 --- a/server/src/com/cloud/storage/dao/LaunchPermissionDao.java +++ b/server/src/com/cloud/storage/dao/LaunchPermissionDao.java @@ -10,47 +10,47 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - -import java.util.List; - +package com.cloud.storage.dao; + +import java.util.List; + import com.cloud.storage.LaunchPermissionVO; import com.cloud.storage.VMTemplateVO; import com.cloud.utils.db.GenericDao; - -public interface LaunchPermissionDao extends GenericDao { - /** - * remove the ability to launch vms from the given template for the given account names which are valid in the given domain - * @param templateId id of the template to modify launch permissions - * @param accountIds list of account ids - */ - void removePermissions(long templateId, List accountIds); - - /** - * remove all launch permissions associated with a template - * @param templateId - */ - void removeAllPermissions(long templateId); - - /** - * Find a launch permission by templateId, accountName, and domainId - * @param templateId the id of the template to search for - * @param accountId the id of the account for which permission is being searched - * @return launch permission if found, null otherwise - */ - LaunchPermissionVO findByTemplateAndAccount(long templateId, long accountId); - - /** - * List all launch permissions for the given template - * @param templateId id of the template for which launch permissions will be queried - * @return list of launch permissions - */ - List findByTemplate(long templateId); - - /** - * List all templates for which permission to launch instances has been granted to the given account - * @param accountId - * @return - */ - List listPermittedTemplates(long accountId); -} + +public interface LaunchPermissionDao extends GenericDao { + /** + * remove the ability to launch vms from the given template for the given account names which are valid in the given domain + * @param templateId id of the template to modify launch permissions + * @param accountIds list of account ids + */ + void removePermissions(long templateId, List accountIds); + + /** + * remove all launch permissions associated with a template + * @param templateId + */ + void removeAllPermissions(long templateId); + + /** + * Find a launch permission by templateId, accountName, and domainId + * @param templateId the id of the template to search for + * @param accountId the id of the account for which permission is being searched + * @return launch permission if found, null otherwise + */ + LaunchPermissionVO findByTemplateAndAccount(long templateId, long accountId); + + /** + * List all launch permissions for the given template + * @param templateId id of the template for which launch permissions will be queried + * @return list of launch permissions + */ + List findByTemplate(long templateId); + + /** + * List all templates for which permission to launch instances has been granted to the given account + * @param accountId + * @return + */ + List listPermittedTemplates(long accountId); +} diff --git a/server/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java b/server/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java index 72524d45fa0..ee46ac2273e 100644 --- a/server/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java +++ b/server/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; @@ -32,121 +32,121 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={LaunchPermissionDao.class}) -public class LaunchPermissionDaoImpl extends GenericDaoBase implements LaunchPermissionDao { + +@Local(value={LaunchPermissionDao.class}) +public class LaunchPermissionDaoImpl extends GenericDaoBase implements LaunchPermissionDao { private static final Logger s_logger = Logger.getLogger(LaunchPermissionDaoImpl.class); - private static final String REMOVE_LAUNCH_PERMISSION = "DELETE FROM `cloud`.`launch_permission`" + - " WHERE template_id = ? AND account_id = ?"; - - private static final String LIST_PERMITTED_TEMPLATES = "SELECT t.id, t.unique_name, t.name, t.public, t.format, t.type, t.hvm, t.bits, t.url, t.created, t.account_id, t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.featured" + - " FROM `cloud`.`vm_template` t INNER JOIN (SELECT lp.template_id as lptid" + - " FROM `cloud`.`launch_permission` lp" + - " WHERE lp.account_id = ?) joinlp" + - " WHERE t.id = joinlp.lptid" + - " ORDER BY t.created DESC"; - - private final SearchBuilder TemplateAndAccountSearch; - private final SearchBuilder TemplateIdSearch; - - protected LaunchPermissionDaoImpl() { - TemplateAndAccountSearch = createSearchBuilder(); - TemplateAndAccountSearch.and("templateId", TemplateAndAccountSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateAndAccountSearch.and("accountId", TemplateAndAccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - TemplateAndAccountSearch.done(); - - TemplateIdSearch = createSearchBuilder(); - TemplateIdSearch.and("templateId", TemplateIdSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateIdSearch.done(); - } - - @Override - public void removePermissions(long templateId, List accountIds) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = REMOVE_LAUNCH_PERMISSION; - pstmt = txn.prepareAutoCloseStatement(sql); - for (Long accountId : accountIds) { - pstmt.setLong(1, templateId); - pstmt.setLong(2, accountId.longValue()); - pstmt.addBatch(); - } - pstmt.executeBatch(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error removing launch permissions", e); - throw new CloudRuntimeException("Error removing launch permissions", e); - } - } - - @Override - public void removeAllPermissions(long templateId) { - SearchCriteria sc = TemplateIdSearch.create(); - sc.setParameters("templateId", templateId); - expunge(sc); - } - - @Override - public LaunchPermissionVO findByTemplateAndAccount(long templateId, long accountId) { - SearchCriteria sc = TemplateAndAccountSearch.create(); - sc.setParameters("templateId", templateId); - sc.setParameters("accountId", accountId); - return findOneBy(sc); - } - - @Override - public List listPermittedTemplates(long accountId) { - Transaction txn = Transaction.currentTxn(); - List permittedTemplates = new ArrayList(); - PreparedStatement pstmt = null; - try { - String sql = LIST_PERMITTED_TEMPLATES; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - long id = rs.getLong(1); - String uniqueName = rs.getString(2); - String name = rs.getString(3); - boolean isPublic = rs.getBoolean(4); - String value = rs.getString(5); - ImageFormat format = ImageFormat.valueOf(value); - String tmpltType = rs.getString(6); - boolean requiresHVM = rs.getBoolean(7); - int bits = rs.getInt(8); - String url = rs.getString(9); - String createdTS = rs.getString(10); - long templateAccountId = rs.getLong(11); - String checksum = rs.getString(12); - String displayText = rs.getString(13); - boolean enablePassword = rs.getBoolean(14); + private static final String REMOVE_LAUNCH_PERMISSION = "DELETE FROM `cloud`.`launch_permission`" + + " WHERE template_id = ? AND account_id = ?"; + + private static final String LIST_PERMITTED_TEMPLATES = "SELECT t.id, t.unique_name, t.name, t.public, t.format, t.type, t.hvm, t.bits, t.url, t.created, t.account_id, t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.featured" + + " FROM `cloud`.`vm_template` t INNER JOIN (SELECT lp.template_id as lptid" + + " FROM `cloud`.`launch_permission` lp" + + " WHERE lp.account_id = ?) joinlp" + + " WHERE t.id = joinlp.lptid" + + " ORDER BY t.created DESC"; + + private final SearchBuilder TemplateAndAccountSearch; + private final SearchBuilder TemplateIdSearch; + + protected LaunchPermissionDaoImpl() { + TemplateAndAccountSearch = createSearchBuilder(); + TemplateAndAccountSearch.and("templateId", TemplateAndAccountSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateAndAccountSearch.and("accountId", TemplateAndAccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + TemplateAndAccountSearch.done(); + + TemplateIdSearch = createSearchBuilder(); + TemplateIdSearch.and("templateId", TemplateIdSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateIdSearch.done(); + } + + @Override + public void removePermissions(long templateId, List accountIds) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = REMOVE_LAUNCH_PERMISSION; + pstmt = txn.prepareAutoCloseStatement(sql); + for (Long accountId : accountIds) { + pstmt.setLong(1, templateId); + pstmt.setLong(2, accountId.longValue()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error removing launch permissions", e); + throw new CloudRuntimeException("Error removing launch permissions", e); + } + } + + @Override + public void removeAllPermissions(long templateId) { + SearchCriteria sc = TemplateIdSearch.create(); + sc.setParameters("templateId", templateId); + expunge(sc); + } + + @Override + public LaunchPermissionVO findByTemplateAndAccount(long templateId, long accountId) { + SearchCriteria sc = TemplateAndAccountSearch.create(); + sc.setParameters("templateId", templateId); + sc.setParameters("accountId", accountId); + return findOneBy(sc); + } + + @Override + public List listPermittedTemplates(long accountId) { + Transaction txn = Transaction.currentTxn(); + List permittedTemplates = new ArrayList(); + PreparedStatement pstmt = null; + try { + String sql = LIST_PERMITTED_TEMPLATES; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + long id = rs.getLong(1); + String uniqueName = rs.getString(2); + String name = rs.getString(3); + boolean isPublic = rs.getBoolean(4); + String value = rs.getString(5); + ImageFormat format = ImageFormat.valueOf(value); + String tmpltType = rs.getString(6); + boolean requiresHVM = rs.getBoolean(7); + int bits = rs.getInt(8); + String url = rs.getString(9); + String createdTS = rs.getString(10); + long templateAccountId = rs.getLong(11); + String checksum = rs.getString(12); + String displayText = rs.getString(13); + boolean enablePassword = rs.getBoolean(14); long guestOSId = rs.getLong(15); - boolean featured = rs.getBoolean(16); - Date createdDate = null; - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - - if (isPublic) { - continue; // if it's public already, skip adding it to permitted templates as this for private templates only - } - VMTemplateVO template = new VMTemplateVO(id, uniqueName, name, format, isPublic, featured, TemplateType.valueOf(tmpltType), url, createdDate, requiresHVM, bits, templateAccountId, checksum, displayText, enablePassword, guestOSId, true, null); - permittedTemplates.add(template); - } - } catch (Exception e) { - s_logger.warn("Error listing permitted templates", e); - } - return permittedTemplates; - } - - @Override - public List findByTemplate(long templateId) { - SearchCriteria sc = TemplateIdSearch.create(); - sc.setParameters("templateId", templateId); - return listBy(sc); - } -} + boolean featured = rs.getBoolean(16); + Date createdDate = null; + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + + if (isPublic) { + continue; // if it's public already, skip adding it to permitted templates as this for private templates only + } + VMTemplateVO template = new VMTemplateVO(id, uniqueName, name, format, isPublic, featured, TemplateType.valueOf(tmpltType), url, createdDate, requiresHVM, bits, templateAccountId, checksum, displayText, enablePassword, guestOSId, true, null); + permittedTemplates.add(template); + } + } catch (Exception e) { + s_logger.warn("Error listing permitted templates", e); + } + return permittedTemplates; + } + + @Override + public List findByTemplate(long templateId) { + SearchCriteria sc = TemplateIdSearch.create(); + sc.setParameters("templateId", templateId); + return listBy(sc); + } +} diff --git a/server/src/com/cloud/storage/dao/SnapshotDao.java b/server/src/com/cloud/storage/dao/SnapshotDao.java index f9cc3c8afc9..86d1b6087a3 100644 --- a/server/src/com/cloud/storage/dao/SnapshotDao.java +++ b/server/src/com/cloud/storage/dao/SnapshotDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.util.List; import com.cloud.storage.Snapshot; @@ -19,11 +19,11 @@ import com.cloud.storage.Snapshot.Type; import com.cloud.storage.SnapshotVO; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; - -public interface SnapshotDao extends GenericDao { - List listByVolumeId(long volumeId); - List listByVolumeId(Filter filter, long volumeId); - SnapshotVO findNextSnapshot(long parentSnapId); + +public interface SnapshotDao extends GenericDao { + List listByVolumeId(long volumeId); + List listByVolumeId(Filter filter, long volumeId); + SnapshotVO findNextSnapshot(long parentSnapId); long getLastSnapshot(long volumeId, long snapId); List listByVolumeIdType(long volumeId, Type type); List listByVolumeIdIncludingRemoved(long volumeId); @@ -37,4 +37,4 @@ public interface SnapshotDao extends GenericDao { public Long countSnapshotsForAccount(long accountId); List listByInstanceId(long instanceId, Snapshot.Status... status); List listByStatus(long volumeId, Snapshot.Status... status); -} +} diff --git a/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java b/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java index f752fba8186..1dbf84a60f8 100644 --- a/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java +++ b/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java @@ -10,22 +10,22 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - -import java.util.List; - +package com.cloud.storage.dao; + +import java.util.List; + import com.cloud.storage.SnapshotPolicyVO; import com.cloud.utils.DateUtil.IntervalType; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; - -/* - * Data Access Object for snapshot_policy table - */ -public interface SnapshotPolicyDao extends GenericDao { - List listByVolumeId(long volumeId); - List listByVolumeId(long volumeId, Filter filter); + +/* + * Data Access Object for snapshot_policy table + */ +public interface SnapshotPolicyDao extends GenericDao { + List listByVolumeId(long volumeId); + List listByVolumeId(long volumeId, Filter filter); SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType); List listActivePolicies(); - SnapshotPolicyVO findOneByVolume(long volumeId); -} + SnapshotPolicyVO findOneByVolume(long volumeId); +} diff --git a/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java b/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java index 055c1c5249b..292a7eabccf 100644 --- a/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java +++ b/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java @@ -10,9 +10,9 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - - +package com.cloud.storage.dao; + + import java.util.List; import javax.ejb.Local; @@ -23,19 +23,19 @@ import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local (value={SnapshotPolicyDao.class}) -public class SnapshotPolicyDaoImpl extends GenericDaoBase implements SnapshotPolicyDao { - private final SearchBuilder VolumeIdSearch; + +@Local (value={SnapshotPolicyDao.class}) +public class SnapshotPolicyDaoImpl extends GenericDaoBase implements SnapshotPolicyDao { + private final SearchBuilder VolumeIdSearch; private final SearchBuilder VolumeIdIntervalSearch; - private final SearchBuilder ActivePolicySearch; - - @Override - public SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType) { - SearchCriteria sc = VolumeIdIntervalSearch.create(); - sc.setParameters("volumeId", volumeId); - sc.setParameters("interval", intvType.ordinal()); - return findOneBy(sc); + private final SearchBuilder ActivePolicySearch; + + @Override + public SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType) { + SearchCriteria sc = VolumeIdIntervalSearch.create(); + sc.setParameters("volumeId", volumeId); + sc.setParameters("interval", intvType.ordinal()); + return findOneBy(sc); } @Override @@ -44,35 +44,35 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase listByVolumeId(long volumeId) { - return listByVolumeId(volumeId, null); - } - - @Override - public List listByVolumeId(long volumeId, Filter filter) { - SearchCriteria sc = VolumeIdSearch.create(); + } + + @Override + public List listByVolumeId(long volumeId) { + return listByVolumeId(volumeId, null); + } + + @Override + public List listByVolumeId(long volumeId, Filter filter) { + SearchCriteria sc = VolumeIdSearch.create(); sc.setParameters("volumeId", volumeId); - sc.setParameters("active", true); - return listBy(sc, filter); - } - - protected SnapshotPolicyDaoImpl() { - VolumeIdSearch = createSearchBuilder(); + sc.setParameters("active", true); + return listBy(sc, filter); + } + + protected SnapshotPolicyDaoImpl() { + VolumeIdSearch = createSearchBuilder(); VolumeIdSearch.and("volumeId", VolumeIdSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - VolumeIdSearch.and("active", VolumeIdSearch.entity().isActive(), SearchCriteria.Op.EQ); - VolumeIdSearch.done(); - - VolumeIdIntervalSearch = createSearchBuilder(); - VolumeIdIntervalSearch.and("volumeId", VolumeIdIntervalSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - VolumeIdIntervalSearch.and("interval", VolumeIdIntervalSearch.entity().getInterval(), SearchCriteria.Op.EQ); + VolumeIdSearch.and("active", VolumeIdSearch.entity().isActive(), SearchCriteria.Op.EQ); + VolumeIdSearch.done(); + + VolumeIdIntervalSearch = createSearchBuilder(); + VolumeIdIntervalSearch.and("volumeId", VolumeIdIntervalSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); + VolumeIdIntervalSearch.and("interval", VolumeIdIntervalSearch.entity().getInterval(), SearchCriteria.Op.EQ); VolumeIdIntervalSearch.done(); ActivePolicySearch = createSearchBuilder(); ActivePolicySearch.and("active", ActivePolicySearch.entity().isActive(), SearchCriteria.Op.EQ); - ActivePolicySearch.done(); + ActivePolicySearch.done(); } @Override @@ -80,5 +80,5 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase sc = ActivePolicySearch.create(); sc.setParameters("active", true); return listIncludingRemovedBy(sc); - } + } } \ No newline at end of file diff --git a/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java b/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java index 287eae3b65b..c1e0baf0db2 100644 --- a/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java +++ b/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java @@ -10,29 +10,29 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - - -import java.util.Date; -import java.util.List; - +package com.cloud.storage.dao; + + +import java.util.Date; +import java.util.List; + import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.SnapshotScheduleVO; import com.cloud.utils.db.GenericDao; - -/* - * Data Access Object for snapshot_schedule table - */ -public interface SnapshotScheduleDao extends GenericDao { - - List getCoincidingSnapshotSchedules(long volumeId, Date date); - - List getSchedulesToExecute(Date currentTimestamp); - + +/* + * Data Access Object for snapshot_schedule table + */ +public interface SnapshotScheduleDao extends GenericDao { + + List getCoincidingSnapshotSchedules(long volumeId, Date date); + + List getSchedulesToExecute(Date currentTimestamp); + SnapshotScheduleVO getCurrentSchedule(Long volumeId, Long policyId, boolean executing); SnapshotScheduleVO findOneByVolume(long volumeId); SnapshotScheduleVO findOneByVolumePolicy(long volumeId, long policyId); -} +} diff --git a/server/src/com/cloud/storage/dao/StoragePoolDao.java b/server/src/com/cloud/storage/dao/StoragePoolDao.java index e8da69234ed..721083e8944 100644 --- a/server/src/com/cloud/storage/dao/StoragePoolDao.java +++ b/server/src/com/cloud/storage/dao/StoragePoolDao.java @@ -99,4 +99,4 @@ public interface StoragePoolDao extends GenericDao { List listByStatusInZone(long dcId, StoragePoolStatus status); List listPoolsByCluster(long clusterId); -} +} diff --git a/server/src/com/cloud/storage/dao/SwiftDaoImpl.java b/server/src/com/cloud/storage/dao/SwiftDaoImpl.java index 66c9307f416..06de2193054 100644 --- a/server/src/com/cloud/storage/dao/SwiftDaoImpl.java +++ b/server/src/com/cloud/storage/dao/SwiftDaoImpl.java @@ -10,7 +10,7 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; +package com.cloud.storage.dao; import java.util.Collections; import java.util.List; @@ -28,7 +28,7 @@ import com.cloud.utils.db.GenericDaoBase; * */ -@Local (value={SwiftDao.class}) +@Local (value={SwiftDao.class}) public class SwiftDaoImpl extends GenericDaoBase implements SwiftDao { public static final Logger s_logger = Logger.getLogger(SwiftDaoImpl.class.getName()); diff --git a/server/src/com/cloud/storage/dao/VMTemplateDao.java b/server/src/com/cloud/storage/dao/VMTemplateDao.java index dd97277e79d..64c5f7386d1 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDao.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.util.List; import java.util.Set; @@ -23,26 +23,26 @@ import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; - -/* - * Data Access Object for vm_templates table - */ + +/* + * Data Access Object for vm_templates table + */ public interface VMTemplateDao extends GenericDao { - + public List listByPublic(); public VMTemplateVO findByName(String templateName); public VMTemplateVO findByTemplateName(String templateName); - - //public void update(VMTemplateVO template); - public List listAllSystemVMTemplates(); + //public void update(VMTemplateVO template); - public List listDefaultBuiltinTemplates(); - public String getRoutingTemplateUniqueName(); - public List findIsosByIdAndPath(Long domainId, Long accountId, String path); - public List listReadyTemplates(); - public List listByAccountId(long accountId); + public List listAllSystemVMTemplates(); + + public List listDefaultBuiltinTemplates(); + public String getRoutingTemplateUniqueName(); + public List findIsosByIdAndPath(Long domainId, Long accountId, String path); + public List listReadyTemplates(); + public List listByAccountId(long accountId); public Set> searchTemplates(String name, String keyword, TemplateFilter templateFilter, boolean isIso, List hypers, Boolean bootable, DomainVO domain, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr, List permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria); @@ -60,5 +60,5 @@ public interface VMTemplateDao extends GenericDao { VMTemplateVO findRoutingTemplate(HypervisorType type); List listPrivateTemplatesByHost(Long hostId); public Long countTemplatesForAccount(long accountId); - -} + +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java index a9800276858..17a45a255b5 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -57,9 +57,9 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={VMTemplateDao.class}) -public class VMTemplateDaoImpl extends GenericDaoBase implements VMTemplateDao { + +@Local(value={VMTemplateDao.class}) +public class VMTemplateDaoImpl extends GenericDaoBase implements VMTemplateDao { private static final Logger s_logger = Logger.getLogger(VMTemplateDaoImpl.class); @Inject @@ -85,12 +85,12 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem private final String SELECT_TEMPLATE_SWIFT_REF = "SELECT t.id, t.unique_name, t.name, t.public, t.featured, t.type, t.hvm, t.bits, t.url, t.format, t.created, t.account_id, " + "t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.bootable, t.prepopulate, t.cross_zones, t.hypervisor_type FROM vm_template t"; - protected SearchBuilder TemplateNameSearch; + protected SearchBuilder TemplateNameSearch; protected SearchBuilder UniqueNameSearch; protected SearchBuilder tmpltTypeSearch; protected SearchBuilder tmpltTypeHyperSearch; protected SearchBuilder tmpltTypeHyperSearch2; - + protected SearchBuilder AccountIdSearch; protected SearchBuilder NameSearch; protected SearchBuilder TmpltsInZoneSearch; @@ -98,26 +98,26 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem private SearchBuilder NameAccountIdSearch; private SearchBuilder PublicIsoSearch; private GenericSearchBuilder CountTemplatesByAccount; - - private String routerTmpltName; - private String consoleProxyTmpltName; - - protected VMTemplateDaoImpl() { - } - + + private String routerTmpltName; + private String consoleProxyTmpltName; + + protected VMTemplateDaoImpl() { + } + @Override - public List listByPublic() { - SearchCriteria sc = PublicSearch.create(); - sc.setParameters("public", 1); - return listBy(sc); - } - - @Override - public VMTemplateVO findByName(String templateName) { - SearchCriteria sc = UniqueNameSearch.create(); - sc.setParameters("uniqueName", templateName); - return findOneIncludingRemovedBy(sc); - } + public List listByPublic() { + SearchCriteria sc = PublicSearch.create(); + sc.setParameters("public", 1); + return listBy(sc); + } + + @Override + public VMTemplateVO findByName(String templateName) { + SearchCriteria sc = UniqueNameSearch.create(); + sc.setParameters("uniqueName", templateName); + return findOneIncludingRemovedBy(sc); + } @Override public VMTemplateVO findByTemplateName(String templateName) { @@ -176,35 +176,35 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem return l; } - @Override - public List listReadyTemplates() { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("ready", SearchCriteria.Op.EQ, true); - sc.addAnd("format", SearchCriteria.Op.NEQ, Storage.ImageFormat.ISO); - return listIncludingRemovedBy(sc); - } - - @Override - public List findIsosByIdAndPath(Long domainId, Long accountId, String path) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("iso", SearchCriteria.Op.EQ, true); + @Override + public List listReadyTemplates() { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("ready", SearchCriteria.Op.EQ, true); + sc.addAnd("format", SearchCriteria.Op.NEQ, Storage.ImageFormat.ISO); + return listIncludingRemovedBy(sc); + } + + @Override + public List findIsosByIdAndPath(Long domainId, Long accountId, String path) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("iso", SearchCriteria.Op.EQ, true); if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); - } + } if (accountId != null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); - } + } if (path != null) { sc.addAnd("path", SearchCriteria.Op.EQ, path); - } - return listIncludingRemovedBy(sc); - } - - @Override - public List listByAccountId(long accountId) { - SearchCriteria sc = AccountIdSearch.create(); - sc.setParameters("accountId", accountId); - return listBy(sc); + } + return listIncludingRemovedBy(sc); + } + + @Override + public List listByAccountId(long accountId) { + SearchCriteria sc = AccountIdSearch.create(); + sc.setParameters("accountId", accountId); + return listBy(sc); } @Override @@ -213,34 +213,34 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem hyperTypes.add(HypervisorType.None); sc.addAnd("hypervisorType", SearchCriteria.Op.IN, hyperTypes.toArray()); return listBy(sc); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - boolean result = super.configure(name, params); - - PublicSearch = createSearchBuilder(); - PublicSearch.and("public", PublicSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); - - routerTmpltName = (String)params.get("routing.uniquename"); - - s_logger.debug("Found parameter routing unique name " + routerTmpltName); - if (routerTmpltName==null) { - routerTmpltName="routing"; - } - - consoleProxyTmpltName = (String)params.get("consoleproxy.uniquename"); + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + boolean result = super.configure(name, params); + + PublicSearch = createSearchBuilder(); + PublicSearch.and("public", PublicSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); + + routerTmpltName = (String)params.get("routing.uniquename"); + + s_logger.debug("Found parameter routing unique name " + routerTmpltName); + if (routerTmpltName==null) { + routerTmpltName="routing"; + } + + consoleProxyTmpltName = (String)params.get("consoleproxy.uniquename"); if(consoleProxyTmpltName == null) { consoleProxyTmpltName = "routing"; - } + } if(s_logger.isDebugEnabled()) { s_logger.debug("Use console proxy template : " + consoleProxyTmpltName); - } + } - UniqueNameSearch = createSearchBuilder(); + UniqueNameSearch = createSearchBuilder(); UniqueNameSearch.and("uniqueName", UniqueNameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ); NameSearch = createSearchBuilder(); - NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); + NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); NameAccountIdSearch = createSearchBuilder(); NameAccountIdSearch.and("name", NameAccountIdSearch.entity().getName(), SearchCriteria.Op.EQ); @@ -274,9 +274,9 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem tmpltTypeSearch.and("removed", tmpltTypeSearch.entity().getRemoved(), SearchCriteria.Op.NULL); tmpltTypeSearch.and("templateType", tmpltTypeSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); - AccountIdSearch = createSearchBuilder(); - AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountIdSearch.and("publicTemplate", AccountIdSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); + AccountIdSearch = createSearchBuilder(); + AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountIdSearch.and("publicTemplate", AccountIdSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); AccountIdSearch.done(); SearchBuilder tmpltZoneSearch = _templateZoneDao.createSearchBuilder(); @@ -297,13 +297,13 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem CountTemplatesByAccount.and("account", CountTemplatesByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); CountTemplatesByAccount.and("removed", CountTemplatesByAccount.entity().getRemoved(), SearchCriteria.Op.NULL); CountTemplatesByAccount.done(); - - return result; - } - - @Override - public String getRoutingTemplateUniqueName() { - return routerTmpltName; + + return result; + } + + @Override + public String getRoutingTemplateUniqueName() { + return routerTmpltName; } @Override @@ -423,8 +423,8 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem return templateZonePairList; } - - @Override + + @Override public Set> searchTemplates(String name, String keyword, TemplateFilter templateFilter, boolean isIso, List hypers, Boolean bootable, DomainVO domain, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr,List permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria) { StringBuilder builder = new StringBuilder(); if (!permittedAccounts.isEmpty()) { @@ -441,14 +441,14 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } Transaction txn = Transaction.currentTxn(); - txn.start(); + txn.start(); /* Use LinkedHashSet here to guarantee iteration order */ - Set> templateZonePairList = new LinkedHashSet>(); + Set> templateZonePairList = new LinkedHashSet>(); PreparedStatement pstmt = null; ResultSet rs = null; StringBuilder relatedDomainIds = new StringBuilder(); - String sql = SELECT_TEMPLATE_ZONE_REF; + String sql = SELECT_TEMPLATE_ZONE_REF; String groupByClause = ""; try { //short accountType; @@ -573,11 +573,11 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem sql += whereClause + getExtrasWhere(templateFilter, name, keyword, isIso, bootable, hyperType, zoneId, onlyReady, showDomr) + groupByClause + getOrderByLimit(pageSize, startIndex); - pstmt = txn.prepareStatement(sql); - rs = pstmt.executeQuery(); + pstmt = txn.prepareStatement(sql); + rs = pstmt.executeQuery(); while (rs.next()) { Pair templateZonePair = new Pair(rs.getLong(1), rs.getLong(2)); - templateZonePairList.add(templateZonePair); + templateZonePairList.add(templateZonePair); } //for now, defaulting pageSize to a large val if null; may need to revisit post 2.2RC2 @@ -596,9 +596,9 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem templateZonePairList.add(new Pair(publicIsos.get(i).getId(), null)); } } - } - } catch (Exception e) { - s_logger.warn("Error listing templates", e); + } + } catch (Exception e) { + s_logger.warn("Error listing templates", e); } finally { try { if (rs != null) { @@ -613,31 +613,31 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } } - return templateZonePairList; - } - - private String getExtrasWhere(TemplateFilter templateFilter, String name, String keyword, boolean isIso, Boolean bootable, HypervisorType hyperType, Long zoneId, boolean onlyReady, boolean showDomr) { - String sql = ""; - if (keyword != null) { - sql += " t.name LIKE \"%" + keyword + "%\" AND"; - } else if (name != null) { - sql += " t.name LIKE \"%" + name + "%\" AND"; - } - - if (isIso) { + return templateZonePairList; + } + + private String getExtrasWhere(TemplateFilter templateFilter, String name, String keyword, boolean isIso, Boolean bootable, HypervisorType hyperType, Long zoneId, boolean onlyReady, boolean showDomr) { + String sql = ""; + if (keyword != null) { + sql += " t.name LIKE \"%" + keyword + "%\" AND"; + } else if (name != null) { + sql += " t.name LIKE \"%" + name + "%\" AND"; + } + + if (isIso) { sql += " t.format = 'ISO'"; if (!hyperType.equals(HypervisorType.None)) { sql += " AND goh.hypervisor_type = '" + hyperType.toString() + "'"; - } - } else { + } + } else { sql += " t.format <> 'ISO'"; if (!hyperType.equals(HypervisorType.None)) { sql += " AND t.hypervisor_type = '" + hyperType.toString() + "'"; - } - } - - if (bootable != null) { - sql += " AND t.bootable = " + bootable; + } + } + + if (bootable != null) { + sql += " AND t.bootable = " + bootable; } if (onlyReady){ @@ -652,13 +652,13 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } if (!showDomr){ sql += " AND t.type != '" +Storage.TemplateType.SYSTEM.toString() + "'"; - } - - sql += " AND t.removed IS NULL"; - - return sql; - } - + } + + sql += " AND t.removed IS NULL"; + + return sql; + } + private String getOrderByLimit(Long pageSize, Long startIndex) { Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); isAscending = (isAscending == null ? true : isAscending); @@ -669,11 +669,11 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } else { sql = " ORDER BY t.sort_key DESC"; } - - if ((pageSize != null) && (startIndex != null)) { - sql += " LIMIT " + startIndex.toString() + "," + pageSize.toString(); - } - return sql; + + if ((pageSize != null) && (startIndex != null)) { + sql += " LIMIT " + startIndex.toString() + "," + pageSize.toString(); + } + return sql; } @Override @@ -793,5 +793,5 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } - -} + +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateDetailsDao.java b/server/src/com/cloud/storage/dao/VMTemplateDetailsDao.java index 420be503f41..9ebbb066781 100644 --- a/server/src/com/cloud/storage/dao/VMTemplateDetailsDao.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDetailsDao.java @@ -10,19 +10,19 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - -import java.util.Map; - -import com.cloud.storage.VMTemplateDetailVO; -import com.cloud.utils.db.GenericDao; - -public interface VMTemplateDetailsDao extends GenericDao { - Map findDetails(long templateId); - - void persist(long templateId, Map details); - - VMTemplateDetailVO findDetail(long templateId, String name); - - void deleteDetails(long vmId); -} +package com.cloud.storage.dao; + +import java.util.Map; + +import com.cloud.storage.VMTemplateDetailVO; +import com.cloud.utils.db.GenericDao; + +public interface VMTemplateDetailsDao extends GenericDao { + Map findDetails(long templateId); + + void persist(long templateId, Map details); + + VMTemplateDetailVO findDetail(long templateId, String name); + + void deleteDetails(long vmId); +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java index 54ddb9cdedb..e496ee8b5d5 100644 --- a/server/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java @@ -10,83 +10,83 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; - -import com.cloud.storage.VMTemplateDetailVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Local(value=VMTemplateDetailsDao.class) -public class VMTemplateDetailsDaoImpl extends GenericDaoBase implements VMTemplateDetailsDao { - - protected final SearchBuilder TemplateSearch; - protected final SearchBuilder DetailSearch; - - protected VMTemplateDetailsDaoImpl() { - TemplateSearch = createSearchBuilder(); - TemplateSearch.and("templateId", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateSearch.done(); - - DetailSearch = createSearchBuilder(); - DetailSearch.and("templateId", DetailSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - DetailSearch.and("name", DetailSearch.entity().getName(), SearchCriteria.Op.EQ); - DetailSearch.done(); - } - - @Override - public void deleteDetails(long templateId) { - SearchCriteria sc = TemplateSearch.create(); - sc.setParameters("templateId", templateId); - - List results = search(sc, null); - for (VMTemplateDetailVO result : results) { - remove(result.getId()); - } - } - - @Override - public VMTemplateDetailVO findDetail(long templateId, String name) { - SearchCriteria sc = DetailSearch.create(); - sc.setParameters("templateId", templateId); - sc.setParameters("name", name); - - return findOneBy(sc); - } - - @Override - public Map findDetails(long templateId) { - SearchCriteria sc = TemplateSearch.create(); - sc.setParameters("templateId", templateId); - - List results = search(sc, null); - Map details = new HashMap(results.size()); - for (VMTemplateDetailVO result : results) { - details.put(result.getName(), result.getValue()); - } - - return details; - } - - @Override - public void persist(long templateId, Map details) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - SearchCriteria sc = TemplateSearch.create(); - sc.setParameters("templateId", templateId); - expunge(sc); - - for (Map.Entry detail : details.entrySet()) { - VMTemplateDetailVO vo = new VMTemplateDetailVO(templateId, detail.getKey(), detail.getValue()); - persist(vo); - } - txn.commit(); - } -} +package com.cloud.storage.dao; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; + +import com.cloud.storage.VMTemplateDetailVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Local(value=VMTemplateDetailsDao.class) +public class VMTemplateDetailsDaoImpl extends GenericDaoBase implements VMTemplateDetailsDao { + + protected final SearchBuilder TemplateSearch; + protected final SearchBuilder DetailSearch; + + protected VMTemplateDetailsDaoImpl() { + TemplateSearch = createSearchBuilder(); + TemplateSearch.and("templateId", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateSearch.done(); + + DetailSearch = createSearchBuilder(); + DetailSearch.and("templateId", DetailSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + DetailSearch.and("name", DetailSearch.entity().getName(), SearchCriteria.Op.EQ); + DetailSearch.done(); + } + + @Override + public void deleteDetails(long templateId) { + SearchCriteria sc = TemplateSearch.create(); + sc.setParameters("templateId", templateId); + + List results = search(sc, null); + for (VMTemplateDetailVO result : results) { + remove(result.getId()); + } + } + + @Override + public VMTemplateDetailVO findDetail(long templateId, String name) { + SearchCriteria sc = DetailSearch.create(); + sc.setParameters("templateId", templateId); + sc.setParameters("name", name); + + return findOneBy(sc); + } + + @Override + public Map findDetails(long templateId) { + SearchCriteria sc = TemplateSearch.create(); + sc.setParameters("templateId", templateId); + + List results = search(sc, null); + Map details = new HashMap(results.size()); + for (VMTemplateDetailVO result : results) { + details.put(result.getName(), result.getValue()); + } + + return details; + } + + @Override + public void persist(long templateId, Map details) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + SearchCriteria sc = TemplateSearch.create(); + sc.setParameters("templateId", templateId); + expunge(sc); + + for (Map.Entry detail : details.entrySet()) { + VMTemplateDetailVO vo = new VMTemplateDetailVO(templateId, detail.getKey(), detail.getValue()); + persist(vo); + } + txn.commit(); + } +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java index f4a693246aa..1910550a0ed 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -38,18 +38,18 @@ import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value={VMTemplateHostDao.class}) + +@Local(value={VMTemplateHostDao.class}) public class VMTemplateHostDaoImpl extends GenericDaoBase implements VMTemplateHostDao { - public static final Logger s_logger = Logger.getLogger(VMTemplateHostDaoImpl.class.getName()); + public static final Logger s_logger = Logger.getLogger(VMTemplateHostDaoImpl.class.getName()); @Inject - HostDao _hostDao; - protected final SearchBuilder HostSearch; - protected final SearchBuilder TemplateSearch; + HostDao _hostDao; + protected final SearchBuilder HostSearch; + protected final SearchBuilder TemplateSearch; protected final SearchBuilder HostTemplateSearch; protected final SearchBuilder HostTemplateStateSearch; - protected final SearchBuilder HostDestroyedSearch; - protected final SearchBuilder TemplateStatusSearch; + protected final SearchBuilder HostDestroyedSearch; + protected final SearchBuilder TemplateStatusSearch; protected final SearchBuilder TemplateStatesSearch; protected SearchBuilder ZONE_TEMPLATE_SEARCH; protected SearchBuilder LOCAL_SECONDARY_STORAGE_SEARCH; @@ -58,35 +58,35 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase params) throws ConfigurationException { @@ -140,42 +140,42 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase listByHostId(long id) { - SearchCriteria sc = HostSearch.create(); - sc.setParameters("host_id", id); - return listIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateId(long templateId) { - SearchCriteria sc = TemplateSearch.create(); + public void update(VMTemplateHostVO instance) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + Date now = new Date(); + String sql = UPDATE_TEMPLATE_HOST_REF; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setString(1, instance.getDownloadState().toString()); + pstmt.setInt(2, instance.getDownloadPercent()); + pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), now)); + pstmt.setString(4, instance.getErrorString()); + pstmt.setString(5, instance.getLocalDownloadPath()); + pstmt.setString(6, instance.getJobId()); + pstmt.setLong(7, instance.getHostId()); + pstmt.setLong(8, instance.getTemplateId()); + pstmt.executeUpdate(); + } catch (Exception e) { + s_logger.warn("Exception: ", e); + } + } + + @Override + public List listByHostId(long id) { + SearchCriteria sc = HostSearch.create(); + sc.setParameters("host_id", id); + return listIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateId(long templateId) { + SearchCriteria sc = TemplateSearch.create(); sc.setParameters("template_id", templateId); sc.setParameters("destroyed", false); - return listIncludingRemovedBy(sc); + return listIncludingRemovedBy(sc); } @@ -185,45 +185,45 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase sc = HostTemplateSearch.create(); - sc.setParameters("host_id", hostId); + } + + @Override + public VMTemplateHostVO findByHostTemplate(long hostId, long templateId) { + SearchCriteria sc = HostTemplateSearch.create(); + sc.setParameters("host_id", hostId); sc.setParameters("template_id", templateId); sc.setParameters("destroyed", false); - return findOneIncludingRemovedBy(sc); + return findOneIncludingRemovedBy(sc); } - @Override - public List listByTemplateStatus(long templateId, VMTemplateHostVO.Status downloadState) { - SearchCriteria sc = TemplateStatusSearch.create(); - sc.setParameters("template_id", templateId); + @Override + public List listByTemplateStatus(long templateId, VMTemplateHostVO.Status downloadState) { + SearchCriteria sc = TemplateStatusSearch.create(); + sc.setParameters("template_id", templateId); sc.setParameters("download_state", downloadState.toString()); sc.setParameters("destroyed", false); - return listIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateHostVO.Status downloadState) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - try { - String sql = DOWNLOADS_STATE_DC; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, datacenterId); - pstmt.setLong(2, templateId); - pstmt.setString(3, downloadState.toString()); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - result.add(toEntityBean(rs, false)); - } - } catch (Exception e) { - s_logger.warn("Exception: ", e); - } - return result; + return listIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateHostVO.Status downloadState) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + try { + String sql = DOWNLOADS_STATE_DC; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, datacenterId); + pstmt.setLong(2, templateId); + pstmt.setString(3, downloadState.toString()); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + result.add(toEntityBean(rs, false)); + } + } catch (Exception e) { + s_logger.warn("Exception: ", e); + } + return result; } @Override @@ -235,60 +235,60 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateHostVO.Status downloadState) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - ResultSet rs = null; - try { - String sql = DOWNLOADS_STATE_DC_POD; - pstmt = txn.prepareStatement(sql); - - pstmt.setLong(1, datacenterId); - pstmt.setLong(2, podId); - pstmt.setLong(3, templateId); - pstmt.setString(4, downloadState.toString()); - rs = pstmt.executeQuery(); - while (rs.next()) { - // result.add(toEntityBean(rs, false)); TODO: this is buggy in GenericDaoBase for hand constructed queries - long id = rs.getLong(1); //ID column - result.add(findById(id)); - } - } catch (Exception e) { - s_logger.warn("Exception: ", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - return result; - - } - - @Override - public boolean templateAvailable(long templateId, long hostId) { - VMTemplateHostVO tmpltHost = findByHostTemplate(hostId, templateId); - if (tmpltHost == null) - return false; - - return tmpltHost.getDownloadState()==Status.DOWNLOADED; - } - - @Override - public List listByTemplateStates(long templateId, VMTemplateHostVO.Status... states) { - SearchCriteria sc = TemplateStatesSearch.create(); - sc.setParameters("states", (Object[])states); + + @Override + public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateHostVO.Status downloadState) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + ResultSet rs = null; + try { + String sql = DOWNLOADS_STATE_DC_POD; + pstmt = txn.prepareStatement(sql); + + pstmt.setLong(1, datacenterId); + pstmt.setLong(2, podId); + pstmt.setLong(3, templateId); + pstmt.setString(4, downloadState.toString()); + rs = pstmt.executeQuery(); + while (rs.next()) { + // result.add(toEntityBean(rs, false)); TODO: this is buggy in GenericDaoBase for hand constructed queries + long id = rs.getLong(1); //ID column + result.add(findById(id)); + } + } catch (Exception e) { + s_logger.warn("Exception: ", e); + } finally { + try { + if (rs != null) { + rs.close(); + } + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + return result; + + } + + @Override + public boolean templateAvailable(long templateId, long hostId) { + VMTemplateHostVO tmpltHost = findByHostTemplate(hostId, templateId); + if (tmpltHost == null) + return false; + + return tmpltHost.getDownloadState()==Status.DOWNLOADED; + } + + @Override + public List listByTemplateStates(long templateId, VMTemplateHostVO.Status... states) { + SearchCriteria sc = TemplateStatesSearch.create(); + sc.setParameters("states", (Object[])states); sc.setParameters("template_id", templateId); sc.setParameters("destroyed", false); - return search(sc, null); + return search(sc, null); } @Override @@ -298,15 +298,15 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase listByHostTemplate(long hostId, long templateId) { - SearchCriteria sc = HostTemplateSearch.create(); - sc.setParameters("host_id", hostId); + + @Override + public List listByHostTemplate(long hostId, long templateId) { + SearchCriteria sc = HostTemplateSearch.create(); + sc.setParameters("host_id", hostId); sc.setParameters("template_id", templateId); sc.setParameters("destroyed", false); - return listIncludingRemovedBy(sc); - } + return listIncludingRemovedBy(sc); + } @Override public List listByZoneTemplate(long dcId, long templateId, boolean readyOnly) { @@ -360,6 +360,6 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase { - public List listByPoolId(long id); - - public List listByTemplateId(long templateId); - - public VMTemplateStoragePoolVO findByPoolTemplate(long poolId, long templateId); - - public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState); - - public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId); - - public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateStoragePoolVO.Status downloadState); - - public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateStoragePoolVO.Status downloadState); - - public List listByTemplateStates(long templateId, VMTemplateStoragePoolVO.Status ... states); - - - boolean templateAvailable(long templateId, long poolId); - - public VMTemplateStoragePoolVO findByHostTemplate(Long hostId, Long templateId); - -} + +public interface VMTemplatePoolDao extends GenericDao { + public List listByPoolId(long id); + + public List listByTemplateId(long templateId); + + public VMTemplateStoragePoolVO findByPoolTemplate(long poolId, long templateId); + + public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState); + + public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId); + + public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateStoragePoolVO.Status downloadState); + + public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateStoragePoolVO.Status downloadState); + + public List listByTemplateStates(long templateId, VMTemplateStoragePoolVO.Status ... states); + + + boolean templateAvailable(long templateId, long poolId); + + public VMTemplateStoragePoolVO findByHostTemplate(Long hostId, Long templateId); + +} diff --git a/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java index b5f8e4f9349..6b9c0672b0e 100644 --- a/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -29,221 +29,221 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value={VMTemplatePoolDao.class}) -public class VMTemplatePoolDaoImpl extends GenericDaoBase implements VMTemplatePoolDao { - public static final Logger s_logger = Logger.getLogger(VMTemplatePoolDaoImpl.class.getName()); - - protected final SearchBuilder PoolSearch; - protected final SearchBuilder TemplateSearch; - protected final SearchBuilder PoolTemplateSearch; - protected final SearchBuilder TemplateStatusSearch; - protected final SearchBuilder TemplatePoolStatusSearch; - protected final SearchBuilder TemplateStatesSearch; - - protected static final String UPDATE_TEMPLATE_HOST_REF = - "UPDATE template_spool_ref SET download_state = ?, download_pct= ?, last_updated = ? " - + ", error_str = ?, local_path = ?, job_id = ? " - + "WHERE pool_id = ? and template_id = ?"; - - protected static final String DOWNLOADS_STATE_DC= - "SELECT * FROM template_spool_ref t, storage_pool p where t.pool_id = p.id and p.data_center_id=? " - + " and t.template_id=? and t.download_state = ?" ; - - protected static final String DOWNLOADS_STATE_DC_POD= - "SELECT * FROM template_spool_ref tp, storage_pool_host_ref ph, host h where tp.pool_id = ph.pool_id and ph.host_id = h.id and h.data_center_id=? and h.pod_id=? " - + " and tp.template_id=? and tp.download_state=?" ; - - protected static final String HOST_TEMPLATE_SEARCH= - "SELECT * FROM template_spool_ref tp, storage_pool_host_ref ph, host h where tp.pool_id = ph.pool_id and ph.host_id = h.id and h.id=? " - + " and tp.template_id=? " ; - - - public VMTemplatePoolDaoImpl () { - PoolSearch = createSearchBuilder(); - PoolSearch.and("pool_id", PoolSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - PoolSearch.done(); - - TemplateSearch = createSearchBuilder(); - TemplateSearch.and("template_id", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateSearch.done(); - - PoolTemplateSearch = createSearchBuilder(); - PoolTemplateSearch.and("pool_id", PoolTemplateSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - PoolTemplateSearch.and("template_id", PoolTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - PoolTemplateSearch.done(); - - TemplateStatusSearch = createSearchBuilder(); - TemplateStatusSearch.and("template_id", TemplateStatusSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateStatusSearch.and("download_state", TemplateStatusSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); - TemplateStatusSearch.done(); - - TemplatePoolStatusSearch = createSearchBuilder(); - TemplatePoolStatusSearch.and("pool_id", TemplatePoolStatusSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - TemplatePoolStatusSearch.and("template_id", TemplatePoolStatusSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplatePoolStatusSearch.and("download_state", TemplatePoolStatusSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); - TemplatePoolStatusSearch.done(); - - TemplateStatesSearch = createSearchBuilder(); - TemplateStatesSearch.and("template_id", TemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateStatesSearch.and("states", TemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.IN); - TemplateStatesSearch.done(); - } - - @Override - public List listByPoolId(long id) { - SearchCriteria sc = PoolSearch.create(); - sc.setParameters("pool_id", id); - return listIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateId(long templateId) { - SearchCriteria sc = TemplateSearch.create(); - sc.setParameters("template_id", templateId); - return listIncludingRemovedBy(sc); - } - - @Override - public VMTemplateStoragePoolVO findByPoolTemplate(long hostId, long templateId) { - SearchCriteria sc = PoolTemplateSearch.create(); - sc.setParameters("pool_id", hostId); - sc.setParameters("template_id", templateId); - return findOneIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState) { - SearchCriteria sc = TemplateStatusSearch.create(); - sc.setParameters("template_id", templateId); - sc.setParameters("download_state", downloadState.toString()); - return listIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId) { - SearchCriteria sc = TemplatePoolStatusSearch.create(); - sc.setParameters("pool_id", poolId); - sc.setParameters("template_id", templateId); - sc.setParameters("download_state", downloadState.toString()); - return listIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateStoragePoolVO.Status downloadState) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - try { - String sql = DOWNLOADS_STATE_DC; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, datacenterId); - pstmt.setLong(2, templateId); - pstmt.setString(3, downloadState.toString()); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - result.add(toEntityBean(rs, false)); - } - } catch (Exception e) { - s_logger.warn("Exception: ", e); - } - return result; - - } - - @Override - public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateStoragePoolVO.Status downloadState) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - ResultSet rs = null; - try { - String sql = DOWNLOADS_STATE_DC_POD; - pstmt = txn.prepareStatement(sql); - - pstmt.setLong(1, datacenterId); - pstmt.setLong(2, podId); - pstmt.setLong(3, templateId); - pstmt.setString(4, downloadState.toString()); - rs = pstmt.executeQuery(); - while (rs.next()) { - // result.add(toEntityBean(rs, false)); TODO: this is buggy in GenericDaoBase for hand constructed queries - long id = rs.getLong(1); //ID column - result.add(findById(id)); - } - } catch (Exception e) { - s_logger.warn("Exception: ", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - return result; - - } - - public List listByHostTemplate(long hostId, long templateId) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - ResultSet rs = null; - try { - String sql = HOST_TEMPLATE_SEARCH; - pstmt = txn.prepareStatement(sql); - - pstmt.setLong(1, hostId); - pstmt.setLong(2, templateId); - rs = pstmt.executeQuery(); - while (rs.next()) { - // result.add(toEntityBean(rs, false)); TODO: this is buggy in GenericDaoBase for hand constructed queries - long id = rs.getLong(1); //ID column - result.add(findById(id)); - } - } catch (Exception e) { - s_logger.warn("Exception: ", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - return result; - - } - - @Override - public boolean templateAvailable(long templateId, long hostId) { - VMTemplateStorageResourceAssoc tmpltPool = findByPoolTemplate(hostId, templateId); - if (tmpltPool == null) - return false; - - return tmpltPool.getDownloadState()==Status.DOWNLOADED; - } - - @Override - public List listByTemplateStates(long templateId, VMTemplateStoragePoolVO.Status... states) { - SearchCriteria sc = TemplateStatesSearch.create(); - sc.setParameters("states", (Object[])states); - sc.setParameters("template_id", templateId); - - return search(sc, null); - } - - @Override - public VMTemplateStoragePoolVO findByHostTemplate(Long hostId, Long templateId) { - List result = listByHostTemplate(hostId, templateId); - return (result.size() == 0)?null:result.get(1); - } - -} + +@Local(value={VMTemplatePoolDao.class}) +public class VMTemplatePoolDaoImpl extends GenericDaoBase implements VMTemplatePoolDao { + public static final Logger s_logger = Logger.getLogger(VMTemplatePoolDaoImpl.class.getName()); + + protected final SearchBuilder PoolSearch; + protected final SearchBuilder TemplateSearch; + protected final SearchBuilder PoolTemplateSearch; + protected final SearchBuilder TemplateStatusSearch; + protected final SearchBuilder TemplatePoolStatusSearch; + protected final SearchBuilder TemplateStatesSearch; + + protected static final String UPDATE_TEMPLATE_HOST_REF = + "UPDATE template_spool_ref SET download_state = ?, download_pct= ?, last_updated = ? " + + ", error_str = ?, local_path = ?, job_id = ? " + + "WHERE pool_id = ? and template_id = ?"; + + protected static final String DOWNLOADS_STATE_DC= + "SELECT * FROM template_spool_ref t, storage_pool p where t.pool_id = p.id and p.data_center_id=? " + + " and t.template_id=? and t.download_state = ?" ; + + protected static final String DOWNLOADS_STATE_DC_POD= + "SELECT * FROM template_spool_ref tp, storage_pool_host_ref ph, host h where tp.pool_id = ph.pool_id and ph.host_id = h.id and h.data_center_id=? and h.pod_id=? " + + " and tp.template_id=? and tp.download_state=?" ; + + protected static final String HOST_TEMPLATE_SEARCH= + "SELECT * FROM template_spool_ref tp, storage_pool_host_ref ph, host h where tp.pool_id = ph.pool_id and ph.host_id = h.id and h.id=? " + + " and tp.template_id=? " ; + + + public VMTemplatePoolDaoImpl () { + PoolSearch = createSearchBuilder(); + PoolSearch.and("pool_id", PoolSearch.entity().getPoolId(), SearchCriteria.Op.EQ); + PoolSearch.done(); + + TemplateSearch = createSearchBuilder(); + TemplateSearch.and("template_id", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateSearch.done(); + + PoolTemplateSearch = createSearchBuilder(); + PoolTemplateSearch.and("pool_id", PoolTemplateSearch.entity().getPoolId(), SearchCriteria.Op.EQ); + PoolTemplateSearch.and("template_id", PoolTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + PoolTemplateSearch.done(); + + TemplateStatusSearch = createSearchBuilder(); + TemplateStatusSearch.and("template_id", TemplateStatusSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateStatusSearch.and("download_state", TemplateStatusSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); + TemplateStatusSearch.done(); + + TemplatePoolStatusSearch = createSearchBuilder(); + TemplatePoolStatusSearch.and("pool_id", TemplatePoolStatusSearch.entity().getPoolId(), SearchCriteria.Op.EQ); + TemplatePoolStatusSearch.and("template_id", TemplatePoolStatusSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplatePoolStatusSearch.and("download_state", TemplatePoolStatusSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); + TemplatePoolStatusSearch.done(); + + TemplateStatesSearch = createSearchBuilder(); + TemplateStatesSearch.and("template_id", TemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateStatesSearch.and("states", TemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.IN); + TemplateStatesSearch.done(); + } + + @Override + public List listByPoolId(long id) { + SearchCriteria sc = PoolSearch.create(); + sc.setParameters("pool_id", id); + return listIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateId(long templateId) { + SearchCriteria sc = TemplateSearch.create(); + sc.setParameters("template_id", templateId); + return listIncludingRemovedBy(sc); + } + + @Override + public VMTemplateStoragePoolVO findByPoolTemplate(long hostId, long templateId) { + SearchCriteria sc = PoolTemplateSearch.create(); + sc.setParameters("pool_id", hostId); + sc.setParameters("template_id", templateId); + return findOneIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState) { + SearchCriteria sc = TemplateStatusSearch.create(); + sc.setParameters("template_id", templateId); + sc.setParameters("download_state", downloadState.toString()); + return listIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId) { + SearchCriteria sc = TemplatePoolStatusSearch.create(); + sc.setParameters("pool_id", poolId); + sc.setParameters("template_id", templateId); + sc.setParameters("download_state", downloadState.toString()); + return listIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateStoragePoolVO.Status downloadState) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + try { + String sql = DOWNLOADS_STATE_DC; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, datacenterId); + pstmt.setLong(2, templateId); + pstmt.setString(3, downloadState.toString()); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + result.add(toEntityBean(rs, false)); + } + } catch (Exception e) { + s_logger.warn("Exception: ", e); + } + return result; + + } + + @Override + public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateStoragePoolVO.Status downloadState) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + ResultSet rs = null; + try { + String sql = DOWNLOADS_STATE_DC_POD; + pstmt = txn.prepareStatement(sql); + + pstmt.setLong(1, datacenterId); + pstmt.setLong(2, podId); + pstmt.setLong(3, templateId); + pstmt.setString(4, downloadState.toString()); + rs = pstmt.executeQuery(); + while (rs.next()) { + // result.add(toEntityBean(rs, false)); TODO: this is buggy in GenericDaoBase for hand constructed queries + long id = rs.getLong(1); //ID column + result.add(findById(id)); + } + } catch (Exception e) { + s_logger.warn("Exception: ", e); + } finally { + try { + if (rs != null) { + rs.close(); + } + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + return result; + + } + + public List listByHostTemplate(long hostId, long templateId) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + ResultSet rs = null; + try { + String sql = HOST_TEMPLATE_SEARCH; + pstmt = txn.prepareStatement(sql); + + pstmt.setLong(1, hostId); + pstmt.setLong(2, templateId); + rs = pstmt.executeQuery(); + while (rs.next()) { + // result.add(toEntityBean(rs, false)); TODO: this is buggy in GenericDaoBase for hand constructed queries + long id = rs.getLong(1); //ID column + result.add(findById(id)); + } + } catch (Exception e) { + s_logger.warn("Exception: ", e); + } finally { + try { + if (rs != null) { + rs.close(); + } + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + return result; + + } + + @Override + public boolean templateAvailable(long templateId, long hostId) { + VMTemplateStorageResourceAssoc tmpltPool = findByPoolTemplate(hostId, templateId); + if (tmpltPool == null) + return false; + + return tmpltPool.getDownloadState()==Status.DOWNLOADED; + } + + @Override + public List listByTemplateStates(long templateId, VMTemplateStoragePoolVO.Status... states) { + SearchCriteria sc = TemplateStatesSearch.create(); + sc.setParameters("states", (Object[])states); + sc.setParameters("template_id", templateId); + + return search(sc, null); + } + + @Override + public VMTemplateStoragePoolVO findByHostTemplate(Long hostId, Long templateId) { + List result = listByHostTemplate(hostId, templateId); + return (result.size() == 0)?null:result.get(1); + } + +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java index 0e972fae118..282ccdf31ca 100644 --- a/server/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.dao; - +package com.cloud.storage.dao; + import java.util.List; import javax.ejb.Local; @@ -22,62 +22,62 @@ import com.cloud.storage.VMTemplateZoneVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={VMTemplateZoneDao.class}) -public class VMTemplateZoneDaoImpl extends GenericDaoBase implements VMTemplateZoneDao { - public static final Logger s_logger = Logger.getLogger(VMTemplateZoneDaoImpl.class.getName()); - - protected final SearchBuilder ZoneSearch; - protected final SearchBuilder TemplateSearch; - protected final SearchBuilder ZoneTemplateSearch; + +@Local(value={VMTemplateZoneDao.class}) +public class VMTemplateZoneDaoImpl extends GenericDaoBase implements VMTemplateZoneDao { + public static final Logger s_logger = Logger.getLogger(VMTemplateZoneDaoImpl.class.getName()); - - public VMTemplateZoneDaoImpl () { - ZoneSearch = createSearchBuilder(); - ZoneSearch.and("zone_id", ZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); - ZoneSearch.done(); - - TemplateSearch = createSearchBuilder(); - TemplateSearch.and("template_id", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateSearch.done(); - - ZoneTemplateSearch = createSearchBuilder(); - ZoneTemplateSearch.and("zone_id", ZoneTemplateSearch.entity().getZoneId(), SearchCriteria.Op.EQ); - ZoneTemplateSearch.and("template_id", ZoneTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - ZoneTemplateSearch.done(); - } - - - @Override - public List listByZoneId(long id) { - SearchCriteria sc = ZoneSearch.create(); - sc.setParameters("zone_id", id); - return listIncludingRemovedBy(sc); - } - - @Override - public List listByTemplateId(long templateId) { - SearchCriteria sc = TemplateSearch.create(); - sc.setParameters("template_id", templateId); - return listIncludingRemovedBy(sc); - } - - @Override - public VMTemplateZoneVO findByZoneTemplate(long zoneId, long templateId) { - SearchCriteria sc = ZoneTemplateSearch.create(); - sc.setParameters("zone_id", zoneId); - sc.setParameters("template_id", templateId); - return findOneIncludingRemovedBy(sc); - } - - @Override - public List listByZoneTemplate(Long zoneId, long templateId) { + protected final SearchBuilder ZoneSearch; + protected final SearchBuilder TemplateSearch; + protected final SearchBuilder ZoneTemplateSearch; + + + public VMTemplateZoneDaoImpl () { + ZoneSearch = createSearchBuilder(); + ZoneSearch.and("zone_id", ZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + ZoneSearch.done(); + + TemplateSearch = createSearchBuilder(); + TemplateSearch.and("template_id", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateSearch.done(); + + ZoneTemplateSearch = createSearchBuilder(); + ZoneTemplateSearch.and("zone_id", ZoneTemplateSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + ZoneTemplateSearch.and("template_id", ZoneTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + ZoneTemplateSearch.done(); + } + + + @Override + public List listByZoneId(long id) { + SearchCriteria sc = ZoneSearch.create(); + sc.setParameters("zone_id", id); + return listIncludingRemovedBy(sc); + } + + @Override + public List listByTemplateId(long templateId) { + SearchCriteria sc = TemplateSearch.create(); + sc.setParameters("template_id", templateId); + return listIncludingRemovedBy(sc); + } + + @Override + public VMTemplateZoneVO findByZoneTemplate(long zoneId, long templateId) { + SearchCriteria sc = ZoneTemplateSearch.create(); + sc.setParameters("zone_id", zoneId); + sc.setParameters("template_id", templateId); + return findOneIncludingRemovedBy(sc); + } + + @Override + public List listByZoneTemplate(Long zoneId, long templateId) { SearchCriteria sc = ZoneTemplateSearch.create(); if (zoneId != null) { sc.setParameters("zone_id", zoneId); - } - sc.setParameters("template_id", templateId); - return listBy(sc); - } - -} + } + sc.setParameters("template_id", templateId); + return listBy(sc); + } + +} diff --git a/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java b/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java index fa326137f19..a4afe6a9995 100644 --- a/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java +++ b/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.resource; - +package com.cloud.storage.resource; + import java.io.File; import java.util.HashMap; import java.util.List; @@ -47,119 +47,119 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.template.TemplateConstants; import com.cloud.storage.template.TemplateInfo; import com.cloud.utils.component.ComponentLocator; - -public class DummySecondaryStorageResource extends ServerResourceBase implements ServerResource { - private static final Logger s_logger = Logger.getLogger(DummySecondaryStorageResource.class); - - String _dc; - String _pod; - String _guid; + +public class DummySecondaryStorageResource extends ServerResourceBase implements ServerResource { + private static final Logger s_logger = Logger.getLogger(DummySecondaryStorageResource.class); + + String _dc; + String _pod; + String _guid; String _dummyPath; VMTemplateDao _tmpltDao; private boolean _useServiceVm; - - + + public DummySecondaryStorageResource(boolean useServiceVM) { setUseServiceVm(useServiceVM); } - @Override - protected String getDefaultScriptsDir() { - return "dummy"; - } - - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof DownloadProgressCommand) { - return new DownloadAnswer(null, 100, cmd, - com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, - "dummyFS", - "/dummy"); - } else if (cmd instanceof DownloadCommand) { - return new DownloadAnswer(null, 100, cmd, - com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, - "dummyFS", - "/dummy"); - } else if (cmd instanceof GetStorageStatsCommand) { - return execute((GetStorageStatsCommand)cmd); - } else if (cmd instanceof CheckHealthCommand) { + @Override + protected String getDefaultScriptsDir() { + return "dummy"; + } + + @Override + public Answer executeRequest(Command cmd) { + if (cmd instanceof DownloadProgressCommand) { + return new DownloadAnswer(null, 100, cmd, + com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, + "dummyFS", + "/dummy"); + } else if (cmd instanceof DownloadCommand) { + return new DownloadAnswer(null, 100, cmd, + com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, + "dummyFS", + "/dummy"); + } else if (cmd instanceof GetStorageStatsCommand) { + return execute((GetStorageStatsCommand)cmd); + } else if (cmd instanceof CheckHealthCommand) { return new CheckHealthAnswer((CheckHealthCommand)cmd, true); } else if (cmd instanceof ReadyCommand) { - return new ReadyAnswer((ReadyCommand)cmd); - } else { - return Answer.createUnsupportedCommandAnswer(cmd); - } - } - - @Override - public PingCommand getCurrentStatus(long id) { - return new PingStorageCommand(Host.Type.Storage, id, new HashMap()); - } - - @Override - public Type getType() { - return Host.Type.SecondaryStorage; - } - - @Override - public StartupCommand[] initialize() { - final StartupStorageCommand cmd = new StartupStorageCommand("dummy", - StoragePoolType.NetworkFilesystem, 1024*1024*1024*100L, - new HashMap()); - - cmd.setResourceType(Storage.StorageResourceType.SECONDARY_STORAGE); + return new ReadyAnswer((ReadyCommand)cmd); + } else { + return Answer.createUnsupportedCommandAnswer(cmd); + } + } + + @Override + public PingCommand getCurrentStatus(long id) { + return new PingStorageCommand(Host.Type.Storage, id, new HashMap()); + } + + @Override + public Type getType() { + return Host.Type.SecondaryStorage; + } + + @Override + public StartupCommand[] initialize() { + final StartupStorageCommand cmd = new StartupStorageCommand("dummy", + StoragePoolType.NetworkFilesystem, 1024*1024*1024*100L, + new HashMap()); + + cmd.setResourceType(Storage.StorageResourceType.SECONDARY_STORAGE); cmd.setIqn(null); - cmd.setNfsShare(_guid); - - fillNetworkInformation(cmd); - cmd.setDataCenter(_dc); + cmd.setNfsShare(_guid); + + fillNetworkInformation(cmd); + cmd.setDataCenter(_dc); cmd.setPod(_pod); cmd.setGuid(_guid); - - cmd.setName(_guid); - cmd.setVersion(DummySecondaryStorageResource.class.getPackage().getImplementationVersion()); - /* gather TemplateInfo in second storage */ - cmd.setTemplateInfo(getDefaultSystemVmTemplateInfo()); - cmd.getHostDetails().put("mount.parent", "dummy"); - cmd.getHostDetails().put("mount.path", "dummy"); - cmd.getHostDetails().put("orig.url", _guid); - - String tok[] = _dummyPath.split(":"); - cmd.setPrivateIpAddress(tok[0]); - return new StartupCommand [] {cmd}; - } - - protected GetStorageStatsAnswer execute(GetStorageStatsCommand cmd) { - long size = 1024*1024*1024*100L; - return new GetStorageStatsAnswer(cmd, 0, size); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - _dc = (String)params.get("zone"); - if (_dc == null) { - throw new ConfigurationException("Unable to find the zone"); - } - _pod = (String)params.get("pod"); - - _dummyPath = (String)params.get("mount.path"); - if (_dummyPath == null) { - throw new ConfigurationException("Unable to find mount.path"); + + cmd.setName(_guid); + cmd.setVersion(DummySecondaryStorageResource.class.getPackage().getImplementationVersion()); + /* gather TemplateInfo in second storage */ + cmd.setTemplateInfo(getDefaultSystemVmTemplateInfo()); + cmd.getHostDetails().put("mount.parent", "dummy"); + cmd.getHostDetails().put("mount.path", "dummy"); + cmd.getHostDetails().put("orig.url", _guid); + + String tok[] = _dummyPath.split(":"); + cmd.setPrivateIpAddress(tok[0]); + return new StartupCommand [] {cmd}; + } + + protected GetStorageStatsAnswer execute(GetStorageStatsCommand cmd) { + long size = 1024*1024*1024*100L; + return new GetStorageStatsAnswer(cmd, 0, size); + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + + _guid = (String)params.get("guid"); + if (_guid == null) { + throw new ConfigurationException("Unable to find the guid"); + } + + _dc = (String)params.get("zone"); + if (_dc == null) { + throw new ConfigurationException("Unable to find the zone"); + } + _pod = (String)params.get("pod"); + + _dummyPath = (String)params.get("mount.path"); + if (_dummyPath == null) { + throw new ConfigurationException("Unable to find mount.path"); } ComponentLocator locator = ComponentLocator.getLocator("management-server"); _tmpltDao = locator.getDao(VMTemplateDao.class); if (_tmpltDao == null) { throw new ConfigurationException("Unable to find VMTemplate dao"); - } - return true; + } + return true; } public void setUseServiceVm(boolean _useServiceVm) { @@ -180,5 +180,5 @@ public class DummySecondaryStorageResource extends ServerResourceBase implements } } return tmpltInfo; - } -} + } +} diff --git a/server/src/com/cloud/storage/secondary/SecStorageVmAlertEventArgs.java b/server/src/com/cloud/storage/secondary/SecStorageVmAlertEventArgs.java index a851ea7f960..083acb43390 100644 --- a/server/src/com/cloud/storage/secondary/SecStorageVmAlertEventArgs.java +++ b/server/src/com/cloud/storage/secondary/SecStorageVmAlertEventArgs.java @@ -10,61 +10,61 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.secondary; - +package com.cloud.storage.secondary; + import com.cloud.utils.events.EventArgs; import com.cloud.vm.SecondaryStorageVmVO; - -public class SecStorageVmAlertEventArgs extends EventArgs { - - private static final long serialVersionUID = 23773987551479885L; - - public static final int SSVM_CREATED = 1; - public static final int SSVM_UP = 2; - public static final int SSVM_DOWN = 3; - public static final int SSVM_CREATE_FAILURE = 4; - public static final int SSVM_START_FAILURE = 5; - public static final int SSVM_FIREWALL_ALERT = 6; - public static final int SSVM_STORAGE_ALERT = 7; + +public class SecStorageVmAlertEventArgs extends EventArgs { + + private static final long serialVersionUID = 23773987551479885L; + + public static final int SSVM_CREATED = 1; + public static final int SSVM_UP = 2; + public static final int SSVM_DOWN = 3; + public static final int SSVM_CREATE_FAILURE = 4; + public static final int SSVM_START_FAILURE = 5; + public static final int SSVM_FIREWALL_ALERT = 6; + public static final int SSVM_STORAGE_ALERT = 7; public static final int SSVM_REBOOTED = 8; public static final String ALERT_SUBJECT = "ssvm-alert"; - - - private int type; - private long zoneId; - private long ssVmId; - private SecondaryStorageVmVO ssVm; - private String message; - - public SecStorageVmAlertEventArgs(int type, long zoneId, - long ssVmId, SecondaryStorageVmVO ssVm, String message) { - - super(ALERT_SUBJECT); - this.type = type; - this.zoneId = zoneId; - this.ssVmId = ssVmId; - this.ssVm = ssVm; - this.message = message; - } - - public int getType() { - return type; - } - - public long getZoneId() { - return zoneId; - } - - public long getSecStorageVmId() { - return ssVmId; - } - - public SecondaryStorageVmVO getSecStorageVm() { - return ssVm; - } - - public String getMessage() { - return message; - } -} + + + private int type; + private long zoneId; + private long ssVmId; + private SecondaryStorageVmVO ssVm; + private String message; + + public SecStorageVmAlertEventArgs(int type, long zoneId, + long ssVmId, SecondaryStorageVmVO ssVm, String message) { + + super(ALERT_SUBJECT); + this.type = type; + this.zoneId = zoneId; + this.ssVmId = ssVmId; + this.ssVm = ssVm; + this.message = message; + } + + public int getType() { + return type; + } + + public long getZoneId() { + return zoneId; + } + + public long getSecStorageVmId() { + return ssVmId; + } + + public SecondaryStorageVmVO getSecStorageVm() { + return ssVm; + } + + public String getMessage() { + return message; + } +} diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageVmAllocator.java b/server/src/com/cloud/storage/secondary/SecondaryStorageVmAllocator.java index 0817a7a9cc1..c8a381b6d60 100644 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageVmAllocator.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageVmAllocator.java @@ -10,14 +10,14 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.secondary; - -import java.util.List; -import java.util.Map; - +package com.cloud.storage.secondary; + +import java.util.List; +import java.util.Map; + import com.cloud.utils.component.Adapter; import com.cloud.vm.SecondaryStorageVmVO; - -public interface SecondaryStorageVmAllocator extends Adapter { - public SecondaryStorageVmVO allocSecondaryStorageVm(List candidates, Map loadInfo, long dataCenterId); -} + +public interface SecondaryStorageVmAllocator extends Adapter { + public SecondaryStorageVmVO allocSecondaryStorageVm(List candidates, Map loadInfo, long dataCenterId); +} diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageVmDefaultAllocator.java b/server/src/com/cloud/storage/secondary/SecondaryStorageVmDefaultAllocator.java index e960b3e6982..51410b092dc 100644 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageVmDefaultAllocator.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageVmDefaultAllocator.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.secondary; - +package com.cloud.storage.secondary; + import java.util.List; import java.util.Map; import java.util.Random; @@ -20,45 +20,45 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import com.cloud.vm.SecondaryStorageVmVO; - -@Local(value={SecondaryStorageVmAllocator.class}) -public class SecondaryStorageVmDefaultAllocator implements SecondaryStorageVmAllocator { - - private String _name; - private Random _rand = new Random(System.currentTimeMillis()); - - @Override - public SecondaryStorageVmVO allocSecondaryStorageVm(List candidates, Map loadInfo, long dataCenterId) { - if(candidates.size() > 0) - return candidates.get(_rand.nextInt(candidates.size())); - return null; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - /* _name = name; - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - if (configDao == null) { - throw new ConfigurationException("Unable to get the configuration dao."); - } - */ - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } -} + +@Local(value={SecondaryStorageVmAllocator.class}) +public class SecondaryStorageVmDefaultAllocator implements SecondaryStorageVmAllocator { + + private String _name; + private Random _rand = new Random(System.currentTimeMillis()); + + @Override + public SecondaryStorageVmVO allocSecondaryStorageVm(List candidates, Map loadInfo, long dataCenterId) { + if(candidates.size() > 0) + return candidates.get(_rand.nextInt(candidates.size())); + return null; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + /* _name = name; + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + if (configDao == null) { + throw new ConfigurationException("Unable to get the configuration dao."); + } + */ + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } +} diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java b/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java index 1dd670c6418..0b9c316d929 100755 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.secondary; - +package com.cloud.storage.secondary; + import java.util.List; import com.cloud.agent.api.Command; @@ -20,20 +20,20 @@ import com.cloud.host.HostVO; import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; import com.cloud.vm.SecondaryStorageVmVO; - -public interface SecondaryStorageVmManager extends Manager { - - public static final int DEFAULT_SS_VM_RAMSIZE = 256; // 256M + +public interface SecondaryStorageVmManager extends Manager { + + public static final int DEFAULT_SS_VM_RAMSIZE = 256; // 256M public static final int DEFAULT_SS_VM_CPUMHZ = 500; // 500 MHz public static final int DEFAULT_SS_VM_MTUSIZE = 1500; public static final int DEFAULT_SS_VM_CAPACITY = 50; // max command execution session per SSVM public static final int DEFAULT_STANDBY_CAPACITY = 10; // standy capacity to reserve per zone - - public static final String ALERT_SUBJECT = "secondarystoragevm-alert"; - - public SecondaryStorageVmVO startSecStorageVm(long ssVmVmId); - public boolean stopSecStorageVm(long ssVmVmId); - public boolean rebootSecStorageVm(long ssVmVmId); + + public static final String ALERT_SUBJECT = "secondarystoragevm-alert"; + + public SecondaryStorageVmVO startSecStorageVm(long ssVmVmId); + public boolean stopSecStorageVm(long ssVmVmId); + public boolean rebootSecStorageVm(long ssVmVmId); public boolean destroySecStorageVm(long ssVmVmId); public void onAgentConnect(Long dcId, StartupCommand cmd); public boolean generateFirewallConfiguration(Long agentId); @@ -48,5 +48,5 @@ public interface SecondaryStorageVmManager extends Manager { public List listLocalSecondaryStorageHostsInOneZone(long dataCenterId); public List listAllTypesSecondaryStorageHostsInOneZone(long dataCenterId); public List listUpAndConnectingSecondaryStorageVmHost(Long dcId); - public HostVO pickSsvmHost(HostVO ssHost); -} + public HostVO pickSsvmHost(HostVO ssHost); +} diff --git a/server/src/com/cloud/upgrade/DatabaseIntegrityChecker.java b/server/src/com/cloud/upgrade/DatabaseIntegrityChecker.java index e81a05e7c09..d9628b90710 100755 --- a/server/src/com/cloud/upgrade/DatabaseIntegrityChecker.java +++ b/server/src/com/cloud/upgrade/DatabaseIntegrityChecker.java @@ -10,232 +10,232 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.upgrade; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.maint.Version; -import com.cloud.upgrade.dao.VersionDao; -import com.cloud.upgrade.dao.VersionDaoImpl; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.SystemIntegrityChecker; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value = {SystemIntegrityChecker.class}) -public class DatabaseIntegrityChecker implements SystemIntegrityChecker { - private final Logger s_logger = Logger.getLogger(DatabaseIntegrityChecker.class); - - VersionDao _dao; - - public DatabaseIntegrityChecker() { - _dao = ComponentLocator.inject(VersionDaoImpl.class); - } - - /* - * Check if there were multiple hosts connect to the same local storage. This is from a 2.1.x bug, - * we didn't prevent adding host with the same IP. - */ - private String formatDuplicateHostToReadText(Long poolId, ResultSet rs) throws SQLException { - boolean has = false; - StringBuffer buf = new StringBuffer(); - String fmt = "|%1$-8s|%2$-16s|%3$-16s|%4$-24s|%5$-8s|\n"; - String head = String.format(fmt, "id", "status", "removed", "private_ip_address", "pool_id"); - buf.append(head); - while (rs.next()) { - String h = String.format(fmt, rs.getLong(1), rs.getString(2), rs.getString(3), rs.getString(4), poolId); - buf.append(h); - has = true; - } - - if (!has) { - throw new CloudRuntimeException("Local storage with Id " + poolId + " shows there are multiple hosts connect to it, but 'select id, status, removed, private_ip_address from host where id in (select host_id from storage_pool_host_ref where pool_id=?)' returns nothing"); - } else { - return buf.toString(); - } - } - - private Boolean checkDuplicateHostWithTheSameLocalStorage() { - Transaction txn = Transaction.open("Integrity"); - txn.start(); - try { - Connection conn; - try { - conn = txn.getConnection(); - PreparedStatement pstmt = conn.prepareStatement("SELECT pool_id FROM host INNER JOIN storage_pool_host_ref INNER JOIN storage_pool WHERE storage_pool.id = storage_pool_host_ref.pool_id and storage_pool.pool_type='LVM' AND host.id=storage_pool_host_ref.host_id AND host.removed IS NULL group by pool_id having count(*) > 1"); - ResultSet rs = pstmt.executeQuery(); - - boolean noDuplicate = true; - StringBuffer helpInfo = new StringBuffer(); - String note = "DATABASE INTEGRITY ERROR\nManagement server detected there are some hosts connect to the same loacal storage, please contact CloudStack support team for solution. Below are detialed info, please attach all of them to CloudStack support. Thank you\n"; - helpInfo.append(note); - while (rs.next()) { - long poolId = rs.getLong(1); - pstmt = conn.prepareStatement("select id, status, removed, private_ip_address from host where id in (select host_id from storage_pool_host_ref where pool_id=?)"); - pstmt.setLong(1, poolId); - ResultSet dhrs = pstmt.executeQuery(); - String help = formatDuplicateHostToReadText(poolId, dhrs); - helpInfo.append(help); - helpInfo.append("\n"); - noDuplicate = false; - } - - if (noDuplicate) { - s_logger.debug("No duplicate hosts with the same local storage found in database"); - } else { - s_logger.error(helpInfo.toString()); - } - - return noDuplicate; - } catch (SQLException e) { - s_logger.error("Unable to check duplicate hosts with the same local storage in database", e); - throw new CloudRuntimeException("Unable to check duplicate hosts with the same local storage in database", e); - } - } finally { - txn.commit(); - txn.close(); - } - } - - private boolean check21to22PremiumUprage(Connection conn) throws SQLException { - PreparedStatement pstmt = conn.prepareStatement("show tables in cloud_usage"); - ResultSet rs = pstmt.executeQuery(); - int num = 0; - - while (rs.next()) { - String tableName = rs.getString(1); - if (tableName.equalsIgnoreCase("usage_event") || tableName.equalsIgnoreCase("usage_port_forwarding") || tableName.equalsIgnoreCase("usage_network_offering")) { - num ++; - s_logger.debug("Checking 21to22PremiumUprage table " + tableName + " found"); - } - if (num == 3) { - return true; - } - } - - return false; - } - - private boolean isColumnExisted(Connection conn, String dbName, String tableName, String column) throws SQLException { - PreparedStatement pstmt = conn.prepareStatement(String.format("describe %1$s.%2$s", dbName, tableName)); - ResultSet rs = pstmt.executeQuery(); - boolean found = false; - while (rs.next()) { - if (column.equalsIgnoreCase(rs.getString(1))) { - s_logger.debug(String.format("Column %1$s.%2$s.%3$s found", dbName, tableName, column)); - found = true; - break; - } - } - return found; - } - - private boolean check221to222PremiumUprage(Connection conn) throws SQLException { - if (!isColumnExisted(conn, "cloud_usage", "cloud_usage", "network_id")) { - return false; - } - - if (!isColumnExisted(conn, "cloud_usage", "usage_network", "network_id")) { - return false; - } - - return isColumnExisted(conn, "cloud_usage", "user_statistics", "network_id"); - } - - private boolean check222to224PremiumUpgrade(Connection conn) throws SQLException { - if (!isColumnExisted(conn, "cloud_usage", "usage_vm_instance", "hypervisor_type")) { - return false; - } - - return isColumnExisted(conn, "cloud_usage", "usage_event", "resource_type"); - } - - private boolean checkMissedPremiumUpgradeFor228() { - Transaction txn = Transaction.open("Integrity"); - txn.start(); - try { - String dbVersion = _dao.getCurrentVersion(); - if (Version.compare(Version.trimToPatch(dbVersion), Version.trimToPatch("2.2.8")) != 0) { - return true; - } - - Connection conn; - try { - conn = txn.getConnection(); - PreparedStatement pstmt = conn.prepareStatement("show databases"); - ResultSet rs = pstmt.executeQuery(); - boolean hasUsage = false; - while (rs.next()) { - String dbName = rs.getString(1); - if (dbName.equalsIgnoreCase("cloud_usage")) { - hasUsage = true; - break; - } - } - - if (!hasUsage) { - s_logger.debug("No cloud_usage found in database, no need to check missed premium upgrade"); - return true; - } - - if (!check21to22PremiumUprage(conn)) { - s_logger.error("21to22 premium upgrade missed"); - return false; - } - - if (!check221to222PremiumUprage(conn)) { - s_logger.error("221to222 premium upgrade missed"); - return false; - } - - if (!check222to224PremiumUpgrade(conn)) { - s_logger.error("222to224 premium upgrade missed"); - return false; - } - - return true; - } catch (SQLException e) { - s_logger.error("Unable to check missed premiumg upgrade"); - throw new CloudRuntimeException("Unable to check missed premiumg upgrade"); - } - } finally { - txn.commit(); - txn.close(); - } - } - - @Override - public void check() { - GlobalLock lock = GlobalLock.getInternLock("DatabaseIntegrity"); - try { - s_logger.info("Grabbing lock to check for database integrity."); - if (!lock.lock(20 * 60)) { - throw new CloudRuntimeException("Unable to acquire lock to check for database integrity."); - } - - try { - s_logger.info("Performing database integrity check"); - if (!checkDuplicateHostWithTheSameLocalStorage()) { - throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage detected error"); - } - - if (!checkMissedPremiumUpgradeFor228()) { - s_logger.error("Your current database version is 2.2.8, management server detected some missed premium upgrade, please contact CloudStack support and attach log file. Thank you!"); - throw new CloudRuntimeException("Detected missed premium upgrade"); - } - } finally { - lock.unlock(); - } - } finally { - lock.releaseRef(); - } - } -} +package com.cloud.upgrade; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.maint.Version; +import com.cloud.upgrade.dao.VersionDao; +import com.cloud.upgrade.dao.VersionDaoImpl; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.SystemIntegrityChecker; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; + +@Local(value = {SystemIntegrityChecker.class}) +public class DatabaseIntegrityChecker implements SystemIntegrityChecker { + private final Logger s_logger = Logger.getLogger(DatabaseIntegrityChecker.class); + + VersionDao _dao; + + public DatabaseIntegrityChecker() { + _dao = ComponentLocator.inject(VersionDaoImpl.class); + } + + /* + * Check if there were multiple hosts connect to the same local storage. This is from a 2.1.x bug, + * we didn't prevent adding host with the same IP. + */ + private String formatDuplicateHostToReadText(Long poolId, ResultSet rs) throws SQLException { + boolean has = false; + StringBuffer buf = new StringBuffer(); + String fmt = "|%1$-8s|%2$-16s|%3$-16s|%4$-24s|%5$-8s|\n"; + String head = String.format(fmt, "id", "status", "removed", "private_ip_address", "pool_id"); + buf.append(head); + while (rs.next()) { + String h = String.format(fmt, rs.getLong(1), rs.getString(2), rs.getString(3), rs.getString(4), poolId); + buf.append(h); + has = true; + } + + if (!has) { + throw new CloudRuntimeException("Local storage with Id " + poolId + " shows there are multiple hosts connect to it, but 'select id, status, removed, private_ip_address from host where id in (select host_id from storage_pool_host_ref where pool_id=?)' returns nothing"); + } else { + return buf.toString(); + } + } + + private Boolean checkDuplicateHostWithTheSameLocalStorage() { + Transaction txn = Transaction.open("Integrity"); + txn.start(); + try { + Connection conn; + try { + conn = txn.getConnection(); + PreparedStatement pstmt = conn.prepareStatement("SELECT pool_id FROM host INNER JOIN storage_pool_host_ref INNER JOIN storage_pool WHERE storage_pool.id = storage_pool_host_ref.pool_id and storage_pool.pool_type='LVM' AND host.id=storage_pool_host_ref.host_id AND host.removed IS NULL group by pool_id having count(*) > 1"); + ResultSet rs = pstmt.executeQuery(); + + boolean noDuplicate = true; + StringBuffer helpInfo = new StringBuffer(); + String note = "DATABASE INTEGRITY ERROR\nManagement server detected there are some hosts connect to the same loacal storage, please contact CloudStack support team for solution. Below are detialed info, please attach all of them to CloudStack support. Thank you\n"; + helpInfo.append(note); + while (rs.next()) { + long poolId = rs.getLong(1); + pstmt = conn.prepareStatement("select id, status, removed, private_ip_address from host where id in (select host_id from storage_pool_host_ref where pool_id=?)"); + pstmt.setLong(1, poolId); + ResultSet dhrs = pstmt.executeQuery(); + String help = formatDuplicateHostToReadText(poolId, dhrs); + helpInfo.append(help); + helpInfo.append("\n"); + noDuplicate = false; + } + + if (noDuplicate) { + s_logger.debug("No duplicate hosts with the same local storage found in database"); + } else { + s_logger.error(helpInfo.toString()); + } + + return noDuplicate; + } catch (SQLException e) { + s_logger.error("Unable to check duplicate hosts with the same local storage in database", e); + throw new CloudRuntimeException("Unable to check duplicate hosts with the same local storage in database", e); + } + } finally { + txn.commit(); + txn.close(); + } + } + + private boolean check21to22PremiumUprage(Connection conn) throws SQLException { + PreparedStatement pstmt = conn.prepareStatement("show tables in cloud_usage"); + ResultSet rs = pstmt.executeQuery(); + int num = 0; + + while (rs.next()) { + String tableName = rs.getString(1); + if (tableName.equalsIgnoreCase("usage_event") || tableName.equalsIgnoreCase("usage_port_forwarding") || tableName.equalsIgnoreCase("usage_network_offering")) { + num ++; + s_logger.debug("Checking 21to22PremiumUprage table " + tableName + " found"); + } + if (num == 3) { + return true; + } + } + + return false; + } + + private boolean isColumnExisted(Connection conn, String dbName, String tableName, String column) throws SQLException { + PreparedStatement pstmt = conn.prepareStatement(String.format("describe %1$s.%2$s", dbName, tableName)); + ResultSet rs = pstmt.executeQuery(); + boolean found = false; + while (rs.next()) { + if (column.equalsIgnoreCase(rs.getString(1))) { + s_logger.debug(String.format("Column %1$s.%2$s.%3$s found", dbName, tableName, column)); + found = true; + break; + } + } + return found; + } + + private boolean check221to222PremiumUprage(Connection conn) throws SQLException { + if (!isColumnExisted(conn, "cloud_usage", "cloud_usage", "network_id")) { + return false; + } + + if (!isColumnExisted(conn, "cloud_usage", "usage_network", "network_id")) { + return false; + } + + return isColumnExisted(conn, "cloud_usage", "user_statistics", "network_id"); + } + + private boolean check222to224PremiumUpgrade(Connection conn) throws SQLException { + if (!isColumnExisted(conn, "cloud_usage", "usage_vm_instance", "hypervisor_type")) { + return false; + } + + return isColumnExisted(conn, "cloud_usage", "usage_event", "resource_type"); + } + + private boolean checkMissedPremiumUpgradeFor228() { + Transaction txn = Transaction.open("Integrity"); + txn.start(); + try { + String dbVersion = _dao.getCurrentVersion(); + if (Version.compare(Version.trimToPatch(dbVersion), Version.trimToPatch("2.2.8")) != 0) { + return true; + } + + Connection conn; + try { + conn = txn.getConnection(); + PreparedStatement pstmt = conn.prepareStatement("show databases"); + ResultSet rs = pstmt.executeQuery(); + boolean hasUsage = false; + while (rs.next()) { + String dbName = rs.getString(1); + if (dbName.equalsIgnoreCase("cloud_usage")) { + hasUsage = true; + break; + } + } + + if (!hasUsage) { + s_logger.debug("No cloud_usage found in database, no need to check missed premium upgrade"); + return true; + } + + if (!check21to22PremiumUprage(conn)) { + s_logger.error("21to22 premium upgrade missed"); + return false; + } + + if (!check221to222PremiumUprage(conn)) { + s_logger.error("221to222 premium upgrade missed"); + return false; + } + + if (!check222to224PremiumUpgrade(conn)) { + s_logger.error("222to224 premium upgrade missed"); + return false; + } + + return true; + } catch (SQLException e) { + s_logger.error("Unable to check missed premiumg upgrade"); + throw new CloudRuntimeException("Unable to check missed premiumg upgrade"); + } + } finally { + txn.commit(); + txn.close(); + } + } + + @Override + public void check() { + GlobalLock lock = GlobalLock.getInternLock("DatabaseIntegrity"); + try { + s_logger.info("Grabbing lock to check for database integrity."); + if (!lock.lock(20 * 60)) { + throw new CloudRuntimeException("Unable to acquire lock to check for database integrity."); + } + + try { + s_logger.info("Performing database integrity check"); + if (!checkDuplicateHostWithTheSameLocalStorage()) { + throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage detected error"); + } + + if (!checkMissedPremiumUpgradeFor228()) { + s_logger.error("Your current database version is 2.2.8, management server detected some missed premium upgrade, please contact CloudStack support and attach log file. Thank you!"); + throw new CloudRuntimeException("Detected missed premium upgrade"); + } + } finally { + lock.unlock(); + } + } finally { + lock.releaseRef(); + } + } +} diff --git a/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java b/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java index e53b492145f..d7737bc9968 100755 --- a/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java @@ -841,7 +841,7 @@ public class Upgrade2214to30 implements DbUpgrade { throw new CloudRuntimeException("Unable to close statement for router table. ", e); } } - } + } protected void updateReduntantRouters(Connection conn) { PreparedStatement pstmt = null; diff --git a/server/src/com/cloud/usage/StorageTypes.java b/server/src/com/cloud/usage/StorageTypes.java index a478805dc26..9db1ad80f04 100644 --- a/server/src/com/cloud/usage/StorageTypes.java +++ b/server/src/com/cloud/usage/StorageTypes.java @@ -10,10 +10,10 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -public class StorageTypes { - public static final int TEMPLATE = 1; - public static final int ISO = 2; - public static final int SNAPSHOT = 3; -} +package com.cloud.usage; + +public class StorageTypes { + public static final int TEMPLATE = 1; + public static final int ISO = 2; + public static final int SNAPSHOT = 3; +} diff --git a/server/src/com/cloud/usage/UsageIPAddressVO.java b/server/src/com/cloud/usage/UsageIPAddressVO.java index e8f351d6d93..8671455942e 100644 --- a/server/src/com/cloud/usage/UsageIPAddressVO.java +++ b/server/src/com/cloud/usage/UsageIPAddressVO.java @@ -10,61 +10,61 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_ip_address") -public class UsageIPAddressVO { - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="zone_id") - private long zoneId; - - @Column(name="id") - private long id; - - @Column(name="public_ip_address") - private String address = null; - - @Column(name="is_source_nat") - private boolean isSourceNat = false; +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_ip_address") +public class UsageIPAddressVO { + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="zone_id") + private long zoneId; + + @Column(name="id") + private long id; + + @Column(name="public_ip_address") + private String address = null; + + @Column(name="is_source_nat") + private boolean isSourceNat = false; @Column(name="is_system") private boolean isSystem = false; - - @Column(name="assigned") - @Temporal(value=TemporalType.TIMESTAMP) - private Date assigned = null; - - @Column(name="released") - @Temporal(value=TemporalType.TIMESTAMP) - private Date released = null; - - protected UsageIPAddressVO() { - } - - public UsageIPAddressVO(long id, long accountId, long domainId, long zoneId, String address, boolean isSourceNat, boolean isSystem, Date assigned, Date released) { - this.id = id; - this.accountId = accountId; - this.domainId = domainId; - this.zoneId = zoneId; - this.address = address; + + @Column(name="assigned") + @Temporal(value=TemporalType.TIMESTAMP) + private Date assigned = null; + + @Column(name="released") + @Temporal(value=TemporalType.TIMESTAMP) + private Date released = null; + + protected UsageIPAddressVO() { + } + + public UsageIPAddressVO(long id, long accountId, long domainId, long zoneId, String address, boolean isSourceNat, boolean isSystem, Date assigned, Date released) { + this.id = id; + this.accountId = accountId; + this.domainId = domainId; + this.zoneId = zoneId; + this.address = address; this.isSourceNat = isSourceNat; - this.isSystem = isSystem; - this.assigned = assigned; - this.released = released; + this.isSystem = isSystem; + this.assigned = assigned; + this.released = released; } public UsageIPAddressVO(long accountId, String address, Date assigned, Date released) { @@ -72,44 +72,44 @@ public class UsageIPAddressVO { this.address = address; this.assigned = assigned; this.released = released; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getZoneId() { - return zoneId; - } - - public long getId() { - return id; - } - - public String getAddress() { - return address; - } - - public boolean isSourceNat() { - return isSourceNat; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getZoneId() { + return zoneId; + } + + public long getId() { + return id; + } + + public String getAddress() { + return address; + } + + public boolean isSourceNat() { + return isSourceNat; } public boolean isSystem() { return isSystem; - } - - public Date getAssigned() { - return assigned; - } - - public Date getReleased() { - return released; - } - public void setReleased(Date released) { - this.released = released; - } -} + } + + public Date getAssigned() { + return assigned; + } + + public Date getReleased() { + return released; + } + public void setReleased(Date released) { + this.released = released; + } +} diff --git a/server/src/com/cloud/usage/UsageJobVO.java b/server/src/com/cloud/usage/UsageJobVO.java index dc512216174..37ef0596ea5 100644 --- a/server/src/com/cloud/usage/UsageJobVO.java +++ b/server/src/com/cloud/usage/UsageJobVO.java @@ -10,165 +10,165 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_job") -public class UsageJobVO { - - public static final int JOB_TYPE_RECURRING = 0; - public static final int JOB_TYPE_SINGLE = 1; - - public static final int JOB_NOT_SCHEDULED = 0; - public static final int JOB_SCHEDULED = 1; - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id; - - @Column(name="host") - private String host; - - @Column(name="pid") - private Integer pid; - - @Column(name="job_type") - private int jobType; - - @Column(name="scheduled") - private int scheduled; - - @Column(name="start_millis") - private long startMillis; - - @Column(name="end_millis") - private long endMillis; - - @Column(name="exec_time") - private long execTime; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="start_date") - private Date startDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="end_date") - private Date endDate; - - @Column(name="success") - private Boolean success; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="heartbeat") - private Date heartbeat; - - public UsageJobVO() {} - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public Integer getPid() { - return pid; - } - - public void setPid(Integer pid) { - this.pid = pid; - } - - public int getJobType() { - return jobType; - } - - public void setJobType(int jobType) { - this.jobType = jobType; - } - - public int getScheduled() { - return scheduled; - } - - public void setScheduled(int scheduled) { - this.scheduled = scheduled; - } - - public long getStartMillis() { - return startMillis; - } - - public void setStartMillis(long startMillis) { - this.startMillis = startMillis; - } - - public long getEndMillis() { - return endMillis; - } - - public void setEndMillis(long endMillis) { - this.endMillis = endMillis; - } - - public long getExecTime() { - return execTime; - } - - public void setExecTime(long execTime) { - this.execTime = execTime; - } - - public Date getStartDate() { - return startDate; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public Date getEndDate() { - return endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public Boolean getSuccess() { - return success; - } - - public void setSuccess(Boolean success) { - this.success = success; - } - - public Date getHeartbeat() { - return heartbeat; - } - - public void setHeartbeat(Date heartbeat) { - this.heartbeat = heartbeat; - } -} +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_job") +public class UsageJobVO { + + public static final int JOB_TYPE_RECURRING = 0; + public static final int JOB_TYPE_SINGLE = 1; + + public static final int JOB_NOT_SCHEDULED = 0; + public static final int JOB_SCHEDULED = 1; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id; + + @Column(name="host") + private String host; + + @Column(name="pid") + private Integer pid; + + @Column(name="job_type") + private int jobType; + + @Column(name="scheduled") + private int scheduled; + + @Column(name="start_millis") + private long startMillis; + + @Column(name="end_millis") + private long endMillis; + + @Column(name="exec_time") + private long execTime; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="start_date") + private Date startDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="end_date") + private Date endDate; + + @Column(name="success") + private Boolean success; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="heartbeat") + private Date heartbeat; + + public UsageJobVO() {} + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public Integer getPid() { + return pid; + } + + public void setPid(Integer pid) { + this.pid = pid; + } + + public int getJobType() { + return jobType; + } + + public void setJobType(int jobType) { + this.jobType = jobType; + } + + public int getScheduled() { + return scheduled; + } + + public void setScheduled(int scheduled) { + this.scheduled = scheduled; + } + + public long getStartMillis() { + return startMillis; + } + + public void setStartMillis(long startMillis) { + this.startMillis = startMillis; + } + + public long getEndMillis() { + return endMillis; + } + + public void setEndMillis(long endMillis) { + this.endMillis = endMillis; + } + + public long getExecTime() { + return execTime; + } + + public void setExecTime(long execTime) { + this.execTime = execTime; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public Date getHeartbeat() { + return heartbeat; + } + + public void setHeartbeat(Date heartbeat) { + this.heartbeat = heartbeat; + } +} diff --git a/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java b/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java index 77c0895157f..49c9ba1c4d4 100644 --- a/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java +++ b/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java @@ -10,76 +10,76 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_load_balancer_policy") -public class UsageLoadBalancerPolicyVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="id") - private long id; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; - - protected UsageLoadBalancerPolicyVO() { - } - - public UsageLoadBalancerPolicyVO(long id, long zoneId, long accountId, long domainId, Date created, Date deleted) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.id = id; - this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getId() { - return id; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; - } -} +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_load_balancer_policy") +public class UsageLoadBalancerPolicyVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="id") + private long id; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; + + protected UsageLoadBalancerPolicyVO() { + } + + public UsageLoadBalancerPolicyVO(long id, long zoneId, long accountId, long domainId, Date created, Date deleted) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.id = id; + this.created = created; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getId() { + return id; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; + } +} diff --git a/server/src/com/cloud/usage/UsageNetworkOfferingVO.java b/server/src/com/cloud/usage/UsageNetworkOfferingVO.java index 2cf0dfe34da..4cafda96a43 100644 --- a/server/src/com/cloud/usage/UsageNetworkOfferingVO.java +++ b/server/src/com/cloud/usage/UsageNetworkOfferingVO.java @@ -10,92 +10,92 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_network_offering") -public class UsageNetworkOfferingVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="vm_instance_id") - private long vmInstanceId; - - @Column(name="network_offering_id") - private Long networkOfferingId; - - @Column(name="is_default") - private boolean isDefault = false; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; - - protected UsageNetworkOfferingVO() { - } - - public UsageNetworkOfferingVO(long zoneId, long accountId, long domainId, long vmInstanceId, long networkOfferingId, boolean isDefault, Date created, Date deleted) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.vmInstanceId = vmInstanceId; - this.networkOfferingId = networkOfferingId; - this.isDefault = isDefault; - this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getVmInstanceId() { - return vmInstanceId; - } - - public Long getNetworkOfferingId() { - return networkOfferingId; - } - - public boolean isDefault() { - return isDefault; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; - } -} +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_network_offering") +public class UsageNetworkOfferingVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="vm_instance_id") + private long vmInstanceId; + + @Column(name="network_offering_id") + private Long networkOfferingId; + + @Column(name="is_default") + private boolean isDefault = false; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; + + protected UsageNetworkOfferingVO() { + } + + public UsageNetworkOfferingVO(long zoneId, long accountId, long domainId, long vmInstanceId, long networkOfferingId, boolean isDefault, Date created, Date deleted) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.vmInstanceId = vmInstanceId; + this.networkOfferingId = networkOfferingId; + this.isDefault = isDefault; + this.created = created; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getVmInstanceId() { + return vmInstanceId; + } + + public Long getNetworkOfferingId() { + return networkOfferingId; + } + + public boolean isDefault() { + return isDefault; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; + } +} diff --git a/server/src/com/cloud/usage/UsageNetworkVO.java b/server/src/com/cloud/usage/UsageNetworkVO.java index 487bd1cb348..7454d936b94 100644 --- a/server/src/com/cloud/usage/UsageNetworkVO.java +++ b/server/src/com/cloud/usage/UsageNetworkVO.java @@ -10,116 +10,116 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="usage_network") -public class UsageNetworkVO { - @Id - @Column(name="account_id") - private long accountId; - - @Column(name="zone_id") - private long zoneId; - - @Column(name="host_id") - private long hostId; - - @Column(name="host_type") - private String hostType; - - @Column(name="network_id") - private Long networkId; - - - @Column(name="bytes_sent") - private long bytesSent; - - @Column(name="bytes_received") - private long bytesReceived; - - @Column(name="agg_bytes_received") - private long aggBytesReceived; - - @Column(name="agg_bytes_sent") - private long aggBytesSent; - - @Column(name="event_time_millis") - private long eventTimeMillis = 0; - - protected UsageNetworkVO() { - } - - public UsageNetworkVO(Long accountId, long zoneId, long hostId, String hostType, Long networkId, long bytesSent, long bytesReceived, long aggBytesReceived, long aggBytesSent, long eventTimeMillis) { - this.accountId = accountId; - this.zoneId = zoneId; - this.hostId = hostId; - this.hostType = hostType; - this.networkId = networkId; - this.bytesSent = bytesSent; - this.bytesReceived = bytesReceived; - this.aggBytesReceived = aggBytesReceived; - this.aggBytesSent = aggBytesSent; - this.eventTimeMillis = eventTimeMillis; - } - - public long getAccountId() { - return accountId; - } - - public void setAccountId(long accountId) { - this.accountId = accountId; - } - - public long getZoneId() { - return zoneId; - } - public void setZoneId(long zoneId) { - this.zoneId = zoneId; - } - - public Long getBytesSent() { - return bytesSent; - } - - public void setBytesSent(Long bytesSent) { - this.bytesSent = bytesSent; - } - - public Long getBytesReceived() { - return bytesReceived; - } - - public void setBytes(Long bytesReceived) { - this.bytesReceived = bytesReceived; - } - - public long getEventTimeMillis() { - return eventTimeMillis; - } - public void setEventTimeMillis(long eventTimeMillis) { - this.eventTimeMillis = eventTimeMillis; - } - - public void setHostId(long hostId) { - this.hostId = hostId; - } - - public long getHostId() { - return hostId; - } - - public String getHostType() { - return hostType; - } - - public Long getNetworkId() { - return networkId; +package com.cloud.usage; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="usage_network") +public class UsageNetworkVO { + @Id + @Column(name="account_id") + private long accountId; + + @Column(name="zone_id") + private long zoneId; + + @Column(name="host_id") + private long hostId; + + @Column(name="host_type") + private String hostType; + + @Column(name="network_id") + private Long networkId; + + + @Column(name="bytes_sent") + private long bytesSent; + + @Column(name="bytes_received") + private long bytesReceived; + + @Column(name="agg_bytes_received") + private long aggBytesReceived; + + @Column(name="agg_bytes_sent") + private long aggBytesSent; + + @Column(name="event_time_millis") + private long eventTimeMillis = 0; + + protected UsageNetworkVO() { + } + + public UsageNetworkVO(Long accountId, long zoneId, long hostId, String hostType, Long networkId, long bytesSent, long bytesReceived, long aggBytesReceived, long aggBytesSent, long eventTimeMillis) { + this.accountId = accountId; + this.zoneId = zoneId; + this.hostId = hostId; + this.hostType = hostType; + this.networkId = networkId; + this.bytesSent = bytesSent; + this.bytesReceived = bytesReceived; + this.aggBytesReceived = aggBytesReceived; + this.aggBytesSent = aggBytesSent; + this.eventTimeMillis = eventTimeMillis; + } + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public long getZoneId() { + return zoneId; + } + public void setZoneId(long zoneId) { + this.zoneId = zoneId; + } + + public Long getBytesSent() { + return bytesSent; + } + + public void setBytesSent(Long bytesSent) { + this.bytesSent = bytesSent; + } + + public Long getBytesReceived() { + return bytesReceived; + } + + public void setBytes(Long bytesReceived) { + this.bytesReceived = bytesReceived; + } + + public long getEventTimeMillis() { + return eventTimeMillis; + } + public void setEventTimeMillis(long eventTimeMillis) { + this.eventTimeMillis = eventTimeMillis; + } + + public void setHostId(long hostId) { + this.hostId = hostId; + } + + public long getHostId() { + return hostId; + } + + public String getHostType() { + return hostType; + } + + public Long getNetworkId() { + return networkId; } public long getAggBytesReceived() { @@ -136,5 +136,5 @@ public class UsageNetworkVO { public void setAggBytesSent(long aggBytesSent) { this.aggBytesSent = aggBytesSent; - } -} + } +} diff --git a/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java b/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java index ca4162ec33b..7e3fb3f9fb1 100644 --- a/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java +++ b/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java @@ -10,76 +10,76 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_port_forwarding") -public class UsagePortForwardingRuleVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="id") - private long id; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; - - protected UsagePortForwardingRuleVO() { - } - - public UsagePortForwardingRuleVO(long id, long zoneId, long accountId, long domainId, Date created, Date deleted) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.id = id; - this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getId() { - return id; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; - } -} +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_port_forwarding") +public class UsagePortForwardingRuleVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="id") + private long id; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; + + protected UsagePortForwardingRuleVO() { + } + + public UsagePortForwardingRuleVO(long id, long zoneId, long accountId, long domainId, Date created, Date deleted) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.id = id; + this.created = created; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getId() { + return id; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; + } +} diff --git a/server/src/com/cloud/usage/UsageSecurityGroupVO.java b/server/src/com/cloud/usage/UsageSecurityGroupVO.java index 5af5ec3449f..cd430bd651b 100644 --- a/server/src/com/cloud/usage/UsageSecurityGroupVO.java +++ b/server/src/com/cloud/usage/UsageSecurityGroupVO.java @@ -10,84 +10,84 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_security_group") -public class UsageSecurityGroupVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="vm_instance_id") - private long vmInstanceId; - - @Column(name="security_group_id") - private Long securityGroupId; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_security_group") +public class UsageSecurityGroupVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="vm_instance_id") + private long vmInstanceId; + + @Column(name="security_group_id") + private Long securityGroupId; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; public UsageSecurityGroupVO(){ } - - public UsageSecurityGroupVO(long zoneId, long accountId, long domainId, long vmInstanceId, long securityGroupId, Date created, Date deleted) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.vmInstanceId = vmInstanceId; - this.securityGroupId = securityGroupId; - this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getVmInstanceId() { - return vmInstanceId; - } - - public Long getSecurityGroupId() { - return securityGroupId; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; - } -} + + public UsageSecurityGroupVO(long zoneId, long accountId, long domainId, long vmInstanceId, long securityGroupId, Date created, Date deleted) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.vmInstanceId = vmInstanceId; + this.securityGroupId = securityGroupId; + this.created = created; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getVmInstanceId() { + return vmInstanceId; + } + + public Long getSecurityGroupId() { + return securityGroupId; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; + } +} diff --git a/server/src/com/cloud/usage/UsageStorageVO.java b/server/src/com/cloud/usage/UsageStorageVO.java index b9490e90a40..ef2bb974b3d 100644 --- a/server/src/com/cloud/usage/UsageStorageVO.java +++ b/server/src/com/cloud/usage/UsageStorageVO.java @@ -10,100 +10,100 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_storage") -public class UsageStorageVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="id") - private long id; - - @Column(name="storage_type") - private int storageType; +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_storage") +public class UsageStorageVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="id") + private long id; + + @Column(name="storage_type") + private int storageType; @Column(name="source_id") private Long sourceId; - - @Column(name="size") - private long size; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; - - protected UsageStorageVO() { - } - - public UsageStorageVO(long id, long zoneId, long accountId, long domainId, int storageType, Long sourceId, long size, Date created, Date deleted) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.id = id; + + @Column(name="size") + private long size; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; + + protected UsageStorageVO() { + } + + public UsageStorageVO(long id, long zoneId, long accountId, long domainId, int storageType, Long sourceId, long size, Date created, Date deleted) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.id = id; this.storageType = storageType; - this.sourceId = sourceId; - this.size = size; - this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getId() { - return id; - } - - public int getStorageType(){ - return storageType; - } + this.sourceId = sourceId; + this.size = size; + this.created = created; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getId() { + return id; + } + + public int getStorageType(){ + return storageType; + } public Long getSourceId(){ return sourceId; } - - public long getSize(){ - return size; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; - } -} + + public long getSize(){ + return size; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; + } +} diff --git a/server/src/com/cloud/usage/UsageTypes.java b/server/src/com/cloud/usage/UsageTypes.java index f26d6e4d18f..988fdc533d2 100644 --- a/server/src/com/cloud/usage/UsageTypes.java +++ b/server/src/com/cloud/usage/UsageTypes.java @@ -10,26 +10,26 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; +package com.cloud.usage; import java.util.ArrayList; import java.util.List; import com.cloud.server.api.response.UsageTypeResponse; - -public class UsageTypes { - public static final int RUNNING_VM = 1; - public static final int ALLOCATED_VM = 2; // used for tracking how long storage has been allocated for a VM - public static final int IP_ADDRESS = 3; - public static final int NETWORK_BYTES_SENT = 4; - public static final int NETWORK_BYTES_RECEIVED = 5; - public static final int VOLUME = 6; - public static final int TEMPLATE = 7; - public static final int ISO = 8; - public static final int SNAPSHOT = 9; - public static final int SECURITY_GROUP = 10; - public static final int LOAD_BALANCER_POLICY = 11; - public static final int PORT_FORWARDING_RULE = 12; + +public class UsageTypes { + public static final int RUNNING_VM = 1; + public static final int ALLOCATED_VM = 2; // used for tracking how long storage has been allocated for a VM + public static final int IP_ADDRESS = 3; + public static final int NETWORK_BYTES_SENT = 4; + public static final int NETWORK_BYTES_RECEIVED = 5; + public static final int VOLUME = 6; + public static final int TEMPLATE = 7; + public static final int ISO = 8; + public static final int SNAPSHOT = 9; + public static final int SECURITY_GROUP = 10; + public static final int LOAD_BALANCER_POLICY = 11; + public static final int PORT_FORWARDING_RULE = 12; public static final int NETWORK_OFFERING = 13; public static final int VPN_USERS = 14; @@ -50,5 +50,5 @@ public class UsageTypes { responseList.add(new UsageTypeResponse(NETWORK_OFFERING, "Network Offering Usage")); responseList.add(new UsageTypeResponse(VPN_USERS, "VPN users usage")); return responseList; - } -} + } +} diff --git a/server/src/com/cloud/usage/UsageVMInstanceVO.java b/server/src/com/cloud/usage/UsageVMInstanceVO.java index f5d180f2ae8..ae685c3cf1e 100644 --- a/server/src/com/cloud/usage/UsageVMInstanceVO.java +++ b/server/src/com/cloud/usage/UsageVMInstanceVO.java @@ -10,108 +10,108 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_vm_instance") -public class UsageVMInstanceVO { - @Column(name="usage_type") - private int usageType; - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="vm_instance_id") - private long vmInstanceId; - - @Column(name="vm_name") - private String vmName = null; - - @Column(name="service_offering_id") - private long serviceOfferingId; - - @Column(name="template_id") - private long templateId; - - @Column(name="hypervisor_type") - private String hypervisorType; - - @Column(name="start_date") - @Temporal(value=TemporalType.TIMESTAMP) - private Date startDate = null; - - @Column(name="end_date") - @Temporal(value=TemporalType.TIMESTAMP) - private Date endDate = null; - - protected UsageVMInstanceVO() { - } - - public UsageVMInstanceVO(int usageType, long zoneId, long accountId, long vmInstanceId, String vmName, long serviceOfferingId, - long templateId, String hypervisorType, Date startDate, Date endDate) { - this.usageType = usageType; - this.zoneId = zoneId; - this.accountId = accountId; - this.vmInstanceId = vmInstanceId; - this.vmName = vmName; - this.serviceOfferingId = serviceOfferingId; - this.templateId = templateId; - this.hypervisorType = hypervisorType; - this.startDate = startDate; - this.endDate = endDate; - } - - public int getUsageType() { - return usageType; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getVmInstanceId() { - return vmInstanceId; - } - - public String getVmName() { - return vmName; - } - - public long getSerivceOfferingId() { - return serviceOfferingId; - } - - public long getTemplateId() { - return templateId; - } - - public String getHypervisorType() { - return hypervisorType; - } - - public Date getStartDate() { - return startDate; - } - - public Date getEndDate() { - return endDate; - } - public void setEndDate(Date endDate) { - this.endDate = endDate; - } -} +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_vm_instance") +public class UsageVMInstanceVO { + @Column(name="usage_type") + private int usageType; + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="vm_instance_id") + private long vmInstanceId; + + @Column(name="vm_name") + private String vmName = null; + + @Column(name="service_offering_id") + private long serviceOfferingId; + + @Column(name="template_id") + private long templateId; + + @Column(name="hypervisor_type") + private String hypervisorType; + + @Column(name="start_date") + @Temporal(value=TemporalType.TIMESTAMP) + private Date startDate = null; + + @Column(name="end_date") + @Temporal(value=TemporalType.TIMESTAMP) + private Date endDate = null; + + protected UsageVMInstanceVO() { + } + + public UsageVMInstanceVO(int usageType, long zoneId, long accountId, long vmInstanceId, String vmName, long serviceOfferingId, + long templateId, String hypervisorType, Date startDate, Date endDate) { + this.usageType = usageType; + this.zoneId = zoneId; + this.accountId = accountId; + this.vmInstanceId = vmInstanceId; + this.vmName = vmName; + this.serviceOfferingId = serviceOfferingId; + this.templateId = templateId; + this.hypervisorType = hypervisorType; + this.startDate = startDate; + this.endDate = endDate; + } + + public int getUsageType() { + return usageType; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getVmInstanceId() { + return vmInstanceId; + } + + public String getVmName() { + return vmName; + } + + public long getSerivceOfferingId() { + return serviceOfferingId; + } + + public long getTemplateId() { + return templateId; + } + + public String getHypervisorType() { + return hypervisorType; + } + + public Date getStartDate() { + return startDate; + } + + public Date getEndDate() { + return endDate; + } + public void setEndDate(Date endDate) { + this.endDate = endDate; + } +} diff --git a/server/src/com/cloud/usage/UsageVO.java b/server/src/com/cloud/usage/UsageVO.java index 202e34aee66..334a8fc4c02 100644 --- a/server/src/com/cloud/usage/UsageVO.java +++ b/server/src/com/cloud/usage/UsageVO.java @@ -10,139 +10,139 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="cloud_usage") -public class UsageVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id = null; - - @Column(name="zone_id") - private Long zoneId = null; - - @Column(name="account_id") - private Long accountId = null; - - @Column(name="domain_id") - private Long domainId = null; - - @Column(name="description") - private String description = null; - - @Column(name="usage_display") - private String usageDisplay = null; - - @Column(name="usage_type") - private int usageType; - - @Column(name="raw_usage") - private Double rawUsage = null; - - @Column(name="vm_instance_id") - private Long vmInstanceId; - - @Column(name="vm_name") - private String vmName = null; - - @Column(name="offering_id") - private Long offeringId = null; - - @Column(name="template_id") - private Long templateId = null; - - @Column(name="usage_id") - private Long usageId = null; - - @Column(name="type") - private String type = null; - - @Column(name="size") - private Long size = null; - - @Column(name="network_id") - private Long networkId = null; - - - @Column(name="start_date") - @Temporal(value=TemporalType.TIMESTAMP) - private Date startDate = null; - - @Column(name="end_date") - @Temporal(value=TemporalType.TIMESTAMP) - private Date endDate = null; - - public UsageVO() { - } - - public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, - int usageType, Double rawUsage, Long vmId, String vmName, Long offeringId, Long templateId, - Long usageId, Long size, Date startDate, Date endDate) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.description = description; - this.usageDisplay = usageDisplay; - this.usageType = usageType; - this.rawUsage = rawUsage; - this.vmInstanceId = vmId; - this.vmName = vmName; - this.offeringId = offeringId; - this.templateId = templateId; - this.usageId = usageId; - this.size = size; - this.startDate = startDate; - this.endDate = endDate; - } - - public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, - int usageType, Double rawUsage, Long usageId, String type, Long networkId, Date startDate, Date endDate) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.description = description; - this.usageDisplay = usageDisplay; - this.usageType = usageType; - this.rawUsage = rawUsage; - this.usageId = usageId; - this.type = type; - this.networkId = networkId; - this.startDate = startDate; - this.endDate = endDate; - } - - public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, - int usageType, Double rawUsage, Long vmId, String vmName, Long offeringId, Long templateId, - Long usageId, Date startDate, Date endDate, String type) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.description = description; - this.usageDisplay = usageDisplay; - this.usageType = usageType; - this.rawUsage = rawUsage; - this.vmInstanceId = vmId; - this.vmName = vmName; - this.offeringId = offeringId; - this.templateId = templateId; - this.usageId = usageId; - this.type = type; - this.startDate = startDate; - this.endDate = endDate; - } +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="cloud_usage") +public class UsageVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id = null; + + @Column(name="zone_id") + private Long zoneId = null; + + @Column(name="account_id") + private Long accountId = null; + + @Column(name="domain_id") + private Long domainId = null; + + @Column(name="description") + private String description = null; + + @Column(name="usage_display") + private String usageDisplay = null; + + @Column(name="usage_type") + private int usageType; + + @Column(name="raw_usage") + private Double rawUsage = null; + + @Column(name="vm_instance_id") + private Long vmInstanceId; + + @Column(name="vm_name") + private String vmName = null; + + @Column(name="offering_id") + private Long offeringId = null; + + @Column(name="template_id") + private Long templateId = null; + + @Column(name="usage_id") + private Long usageId = null; + + @Column(name="type") + private String type = null; + + @Column(name="size") + private Long size = null; + + @Column(name="network_id") + private Long networkId = null; + + + @Column(name="start_date") + @Temporal(value=TemporalType.TIMESTAMP) + private Date startDate = null; + + @Column(name="end_date") + @Temporal(value=TemporalType.TIMESTAMP) + private Date endDate = null; + + public UsageVO() { + } + + public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, + int usageType, Double rawUsage, Long vmId, String vmName, Long offeringId, Long templateId, + Long usageId, Long size, Date startDate, Date endDate) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.description = description; + this.usageDisplay = usageDisplay; + this.usageType = usageType; + this.rawUsage = rawUsage; + this.vmInstanceId = vmId; + this.vmName = vmName; + this.offeringId = offeringId; + this.templateId = templateId; + this.usageId = usageId; + this.size = size; + this.startDate = startDate; + this.endDate = endDate; + } + + public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, + int usageType, Double rawUsage, Long usageId, String type, Long networkId, Date startDate, Date endDate) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.description = description; + this.usageDisplay = usageDisplay; + this.usageType = usageType; + this.rawUsage = rawUsage; + this.usageId = usageId; + this.type = type; + this.networkId = networkId; + this.startDate = startDate; + this.endDate = endDate; + } + + public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, + int usageType, Double rawUsage, Long vmId, String vmName, Long offeringId, Long templateId, + Long usageId, Date startDate, Date endDate, String type) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.description = description; + this.usageDisplay = usageDisplay; + this.usageType = usageType; + this.rawUsage = rawUsage; + this.vmInstanceId = vmId; + this.vmName = vmName; + this.offeringId = offeringId; + this.templateId = templateId; + this.usageId = usageId; + this.type = type; + this.startDate = startDate; + this.endDate = endDate; + } //IPAddress Usage public UsageVO(Long zoneId, Long accountId, Long domainId, String description, String usageDisplay, @@ -160,76 +160,76 @@ public class UsageVO { this.startDate = startDate; this.endDate = endDate; } - - public Long getId() { - return id; - } - - public Long getZoneId() { - return zoneId; - } - - public Long getAccountId() { - return accountId; - } - - public Long getDomainId() { - return domainId; - } - - public String getDescription() { - return description; - } - - public String getUsageDisplay() { - return usageDisplay; - } - - public int getUsageType() { - return usageType; - } - - public Double getRawUsage() { - return rawUsage; - } - - public Long getVmInstanceId() { - return vmInstanceId; - } - - public String getVmName() { - return vmName; - } - - public Long getOfferingId() { - return offeringId; - } - - public Long getTemplateId() { - return templateId; - } - - public Long getUsageId() { - return usageId; - } - - public String getType() { - return type; - } - - public Long getNetworkId() { - return networkId; - } - - public Long getSize() { - return size; - } - - public Date getStartDate() { - return startDate; - } - - public Date getEndDate() { - return endDate; - } -} + + public Long getId() { + return id; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getAccountId() { + return accountId; + } + + public Long getDomainId() { + return domainId; + } + + public String getDescription() { + return description; + } + + public String getUsageDisplay() { + return usageDisplay; + } + + public int getUsageType() { + return usageType; + } + + public Double getRawUsage() { + return rawUsage; + } + + public Long getVmInstanceId() { + return vmInstanceId; + } + + public String getVmName() { + return vmName; + } + + public Long getOfferingId() { + return offeringId; + } + + public Long getTemplateId() { + return templateId; + } + + public Long getUsageId() { + return usageId; + } + + public String getType() { + return type; + } + + public Long getNetworkId() { + return networkId; + } + + public Long getSize() { + return size; + } + + public Date getStartDate() { + return startDate; + } + + public Date getEndDate() { + return endDate; + } +} diff --git a/server/src/com/cloud/usage/UsageVPNUserVO.java b/server/src/com/cloud/usage/UsageVPNUserVO.java index 2c8ccff8bad..dbc5a6a9b1b 100644 --- a/server/src/com/cloud/usage/UsageVPNUserVO.java +++ b/server/src/com/cloud/usage/UsageVPNUserVO.java @@ -10,77 +10,77 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_vpn_user") -public class UsageVPNUserVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="user_id") - private long userId; - - @Column(name="user_name") - private String username; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; - - protected UsageVPNUserVO() { - } - - public UsageVPNUserVO(long zoneId, long accountId, long domainId, long userId, String username, Date created, Date deleted) { - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.userId = userId; - this.username = username; +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_vpn_user") +public class UsageVPNUserVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="user_id") + private long userId; + + @Column(name="user_name") + private String username; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; + + protected UsageVPNUserVO() { + } + + public UsageVPNUserVO(long zoneId, long accountId, long domainId, long userId, String username, Date created, Date deleted) { + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.userId = userId; + this.username = username; this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; } public long getUserId() { @@ -97,5 +97,5 @@ public class UsageVPNUserVO { public void setUsername(String username) { this.username = username; - } -} + } +} diff --git a/server/src/com/cloud/usage/UsageVolumeVO.java b/server/src/com/cloud/usage/UsageVolumeVO.java index c3a0df4c4e4..2e56e3862e0 100644 --- a/server/src/com/cloud/usage/UsageVolumeVO.java +++ b/server/src/com/cloud/usage/UsageVolumeVO.java @@ -10,100 +10,100 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="usage_volume") -public class UsageVolumeVO { - - @Column(name="zone_id") - private long zoneId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="id") - private long id; - - @Column(name="disk_offering_id") - private Long diskOfferingId; - - @Column(name="template_id") - private Long templateId; - - @Column(name="size") - private long size; - - @Column(name="created") - @Temporal(value=TemporalType.TIMESTAMP) - private Date created = null; - - @Column(name="deleted") - @Temporal(value=TemporalType.TIMESTAMP) - private Date deleted = null; - - protected UsageVolumeVO() { - } - - public UsageVolumeVO(long id, long zoneId, long accountId, long domainId, Long diskOfferingId, Long templateId, long size, Date created, Date deleted) { - this.id = id; - this.zoneId = zoneId; - this.accountId = accountId; - this.domainId = domainId; - this.diskOfferingId = diskOfferingId; - this.templateId = templateId; - this.size = size; - this.created = created; - this.deleted = deleted; - } - - public long getZoneId() { - return zoneId; - } - - public long getAccountId() { - return accountId; - } - - public long getDomainId() { - return domainId; - } - - public long getId() { - return id; - } - - public Long getDiskOfferingId() { - return diskOfferingId; - } - - public Long getTemplateId() { - return templateId; - } - - public long getSize() { - return size; - } - - public Date getCreated() { - return created; - } - - public Date getDeleted() { - return deleted; - } - public void setDeleted(Date deleted) { - this.deleted = deleted; - } -} +package com.cloud.usage; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="usage_volume") +public class UsageVolumeVO { + + @Column(name="zone_id") + private long zoneId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="id") + private long id; + + @Column(name="disk_offering_id") + private Long diskOfferingId; + + @Column(name="template_id") + private Long templateId; + + @Column(name="size") + private long size; + + @Column(name="created") + @Temporal(value=TemporalType.TIMESTAMP) + private Date created = null; + + @Column(name="deleted") + @Temporal(value=TemporalType.TIMESTAMP) + private Date deleted = null; + + protected UsageVolumeVO() { + } + + public UsageVolumeVO(long id, long zoneId, long accountId, long domainId, Long diskOfferingId, Long templateId, long size, Date created, Date deleted) { + this.id = id; + this.zoneId = zoneId; + this.accountId = accountId; + this.domainId = domainId; + this.diskOfferingId = diskOfferingId; + this.templateId = templateId; + this.size = size; + this.created = created; + this.deleted = deleted; + } + + public long getZoneId() { + return zoneId; + } + + public long getAccountId() { + return accountId; + } + + public long getDomainId() { + return domainId; + } + + public long getId() { + return id; + } + + public Long getDiskOfferingId() { + return diskOfferingId; + } + + public Long getTemplateId() { + return templateId; + } + + public long getSize() { + return size; + } + + public Date getCreated() { + return created; + } + + public Date getDeleted() { + return deleted; + } + public void setDeleted(Date deleted) { + this.deleted = deleted; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageDao.java b/server/src/com/cloud/usage/dao/UsageDao.java index 6ce882c3c5e..89faad145ce 100644 --- a/server/src/com/cloud/usage/dao/UsageDao.java +++ b/server/src/com/cloud/usage/dao/UsageDao.java @@ -10,28 +10,28 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.event.UsageEventVO; -import com.cloud.exception.UsageServerException; -import com.cloud.usage.UsageVO; -import com.cloud.user.AccountVO; -import com.cloud.user.UserStatisticsVO; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericDao; -import com.cloud.utils.db.SearchCriteria; - -public interface UsageDao extends GenericDao { - void deleteRecordsForAccount(Long accountId); - List searchAllRecords(SearchCriteria sc, Filter filter); - void saveAccounts(List accounts) throws UsageServerException; - void updateAccounts(List accounts) throws UsageServerException; - void saveUserStats(List userStats) throws UsageServerException; - void updateUserStats(List userStats) throws UsageServerException; - Long getLastAccountId() throws UsageServerException; +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.event.UsageEventVO; +import com.cloud.exception.UsageServerException; +import com.cloud.usage.UsageVO; +import com.cloud.user.AccountVO; +import com.cloud.user.UserStatisticsVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.SearchCriteria; + +public interface UsageDao extends GenericDao { + void deleteRecordsForAccount(Long accountId); + List searchAllRecords(SearchCriteria sc, Filter filter); + void saveAccounts(List accounts) throws UsageServerException; + void updateAccounts(List accounts) throws UsageServerException; + void saveUserStats(List userStats) throws UsageServerException; + void updateUserStats(List userStats) throws UsageServerException; + Long getLastAccountId() throws UsageServerException; Long getLastUserStatsId() throws UsageServerException; - List listPublicTemplatesByAccount(long accountId); -} + List listPublicTemplatesByAccount(long accountId); +} diff --git a/server/src/com/cloud/usage/dao/UsageDaoImpl.java b/server/src/com/cloud/usage/dao/UsageDaoImpl.java index 9d96a216e3c..4af6712233a 100644 --- a/server/src/com/cloud/usage/dao/UsageDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageDaoImpl.java @@ -10,257 +10,257 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.exception.UsageServerException; -import com.cloud.usage.UsageVO; -import com.cloud.user.AccountVO; -import com.cloud.user.UserStatisticsVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageDao.class}) -public class UsageDaoImpl extends GenericDaoBase implements UsageDao { - public static final Logger s_logger = Logger.getLogger(UsageDaoImpl.class.getName()); - private static final String DELETE_ALL = "DELETE FROM cloud_usage"; - private static final String DELETE_ALL_BY_ACCOUNTID = "DELETE FROM cloud_usage WHERE account_id = ?"; - private static final String INSERT_ACCOUNT = "INSERT INTO cloud_usage.account (id, account_name, type, domain_id, removed, cleanup_needed) VALUES (?,?,?,?,?,?)"; +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.exception.UsageServerException; +import com.cloud.usage.UsageVO; +import com.cloud.user.AccountVO; +import com.cloud.user.UserStatisticsVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageDao.class}) +public class UsageDaoImpl extends GenericDaoBase implements UsageDao { + public static final Logger s_logger = Logger.getLogger(UsageDaoImpl.class.getName()); + private static final String DELETE_ALL = "DELETE FROM cloud_usage"; + private static final String DELETE_ALL_BY_ACCOUNTID = "DELETE FROM cloud_usage WHERE account_id = ?"; + private static final String INSERT_ACCOUNT = "INSERT INTO cloud_usage.account (id, account_name, type, domain_id, removed, cleanup_needed) VALUES (?,?,?,?,?,?)"; private static final String INSERT_USER_STATS = "INSERT INTO cloud_usage.user_statistics (id, data_center_id, account_id, public_ip_address, device_id, device_type, network_id, net_bytes_received," + - " net_bytes_sent, current_bytes_received, current_bytes_sent, agg_bytes_received, agg_bytes_sent) VALUES (?,?,?,?,?,?,?,?,?,?, ?, ?, ?)"; - - private static final String UPDATE_ACCOUNT = "UPDATE cloud_usage.account SET account_name=?, removed=? WHERE id=?"; - private static final String UPDATE_USER_STATS = "UPDATE cloud_usage.user_statistics SET net_bytes_received=?, net_bytes_sent=?, current_bytes_received=?, current_bytes_sent=?, agg_bytes_received=?, agg_bytes_sent=? WHERE id=?"; - - private static final String GET_LAST_ACCOUNT = "SELECT id FROM cloud_usage.account ORDER BY id DESC LIMIT 1"; - private static final String GET_LAST_USER_STATS = "SELECT id FROM cloud_usage.user_statistics ORDER BY id DESC LIMIT 1"; - private static final String GET_PUBLIC_TEMPLATES_BY_ACCOUNTID = "SELECT id FROM cloud.vm_template WHERE account_id = ? AND public = '1' AND removed IS NULL"; - - protected final static TimeZone s_gmtTimeZone = TimeZone.getTimeZone("GMT"); - - public UsageDaoImpl () {} - - public void deleteRecordsForAccount(Long accountId) { - String sql = ((accountId == null) ? DELETE_ALL : DELETE_ALL_BY_ACCOUNTID); - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - pstmt = txn.prepareAutoCloseStatement(sql); - if (accountId != null) { - pstmt.setLong(1, accountId.longValue()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error retrieving usage vm instances for account id: " + accountId); - } finally { - txn.close(); - } - } - - @Override - public List searchAllRecords(SearchCriteria sc, Filter filter) { - return listIncludingRemovedBy(sc, filter); - } - - @Override - public void saveAccounts(List accounts) throws UsageServerException { - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - String sql = INSERT_ACCOUNT; - PreparedStatement pstmt = null; - pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection - for (AccountVO acct : accounts) { - pstmt.setLong(1, acct.getId()); - pstmt.setString(2, acct.getAccountName()); - pstmt.setShort(3, acct.getType()); - pstmt.setLong(4, acct.getDomainId()); - - Date removed = acct.getRemoved(); - if (removed == null) { - pstmt.setString(5, null); - } else { - pstmt.setString(5, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), acct.getRemoved())); - } - - pstmt.setBoolean(6, acct.getNeedsCleanup()); - - pstmt.addBatch(); - } - pstmt.executeBatch(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error saving account to cloud_usage db", ex); - throw new UsageServerException(ex.getMessage()); - } - } - - @Override - public void updateAccounts(List accounts) throws UsageServerException { - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - String sql = UPDATE_ACCOUNT; - PreparedStatement pstmt = null; - pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection - for (AccountVO acct : accounts) { - pstmt.setString(1, acct.getAccountName()); - - Date removed = acct.getRemoved(); - if (removed == null) { - pstmt.setString(2, null); - } else { - pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), acct.getRemoved())); - } - - pstmt.setLong(3, acct.getId()); - pstmt.addBatch(); - } - pstmt.executeBatch(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error saving account to cloud_usage db", ex); - throw new UsageServerException(ex.getMessage()); - } - } - - @Override - public void saveUserStats(List userStats) throws UsageServerException { - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - String sql = INSERT_USER_STATS; - PreparedStatement pstmt = null; - pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection - for (UserStatisticsVO userStat : userStats) { - pstmt.setLong(1, userStat.getId()); - pstmt.setLong(2, userStat.getDataCenterId()); - pstmt.setLong(3, userStat.getAccountId()); - pstmt.setString(4, userStat.getPublicIpAddress()); - if(userStat.getDeviceId() != null){ - pstmt.setLong(5, userStat.getDeviceId()); - } else { - pstmt.setNull(5, Types.BIGINT); - } - pstmt.setString(6, userStat.getDeviceType()); - if(userStat.getNetworkId() != null){ - pstmt.setLong(7, userStat.getNetworkId()); - } else { - pstmt.setNull(7, Types.BIGINT); - } - pstmt.setLong(8, userStat.getNetBytesReceived()); - pstmt.setLong(9, userStat.getNetBytesSent()); - pstmt.setLong(10, userStat.getCurrentBytesReceived()); + " net_bytes_sent, current_bytes_received, current_bytes_sent, agg_bytes_received, agg_bytes_sent) VALUES (?,?,?,?,?,?,?,?,?,?, ?, ?, ?)"; + + private static final String UPDATE_ACCOUNT = "UPDATE cloud_usage.account SET account_name=?, removed=? WHERE id=?"; + private static final String UPDATE_USER_STATS = "UPDATE cloud_usage.user_statistics SET net_bytes_received=?, net_bytes_sent=?, current_bytes_received=?, current_bytes_sent=?, agg_bytes_received=?, agg_bytes_sent=? WHERE id=?"; + + private static final String GET_LAST_ACCOUNT = "SELECT id FROM cloud_usage.account ORDER BY id DESC LIMIT 1"; + private static final String GET_LAST_USER_STATS = "SELECT id FROM cloud_usage.user_statistics ORDER BY id DESC LIMIT 1"; + private static final String GET_PUBLIC_TEMPLATES_BY_ACCOUNTID = "SELECT id FROM cloud.vm_template WHERE account_id = ? AND public = '1' AND removed IS NULL"; + + protected final static TimeZone s_gmtTimeZone = TimeZone.getTimeZone("GMT"); + + public UsageDaoImpl () {} + + public void deleteRecordsForAccount(Long accountId) { + String sql = ((accountId == null) ? DELETE_ALL : DELETE_ALL_BY_ACCOUNTID); + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + pstmt = txn.prepareAutoCloseStatement(sql); + if (accountId != null) { + pstmt.setLong(1, accountId.longValue()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error retrieving usage vm instances for account id: " + accountId); + } finally { + txn.close(); + } + } + + @Override + public List searchAllRecords(SearchCriteria sc, Filter filter) { + return listIncludingRemovedBy(sc, filter); + } + + @Override + public void saveAccounts(List accounts) throws UsageServerException { + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + String sql = INSERT_ACCOUNT; + PreparedStatement pstmt = null; + pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection + for (AccountVO acct : accounts) { + pstmt.setLong(1, acct.getId()); + pstmt.setString(2, acct.getAccountName()); + pstmt.setShort(3, acct.getType()); + pstmt.setLong(4, acct.getDomainId()); + + Date removed = acct.getRemoved(); + if (removed == null) { + pstmt.setString(5, null); + } else { + pstmt.setString(5, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), acct.getRemoved())); + } + + pstmt.setBoolean(6, acct.getNeedsCleanup()); + + pstmt.addBatch(); + } + pstmt.executeBatch(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error saving account to cloud_usage db", ex); + throw new UsageServerException(ex.getMessage()); + } + } + + @Override + public void updateAccounts(List accounts) throws UsageServerException { + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + String sql = UPDATE_ACCOUNT; + PreparedStatement pstmt = null; + pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection + for (AccountVO acct : accounts) { + pstmt.setString(1, acct.getAccountName()); + + Date removed = acct.getRemoved(); + if (removed == null) { + pstmt.setString(2, null); + } else { + pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), acct.getRemoved())); + } + + pstmt.setLong(3, acct.getId()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error saving account to cloud_usage db", ex); + throw new UsageServerException(ex.getMessage()); + } + } + + @Override + public void saveUserStats(List userStats) throws UsageServerException { + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + String sql = INSERT_USER_STATS; + PreparedStatement pstmt = null; + pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection + for (UserStatisticsVO userStat : userStats) { + pstmt.setLong(1, userStat.getId()); + pstmt.setLong(2, userStat.getDataCenterId()); + pstmt.setLong(3, userStat.getAccountId()); + pstmt.setString(4, userStat.getPublicIpAddress()); + if(userStat.getDeviceId() != null){ + pstmt.setLong(5, userStat.getDeviceId()); + } else { + pstmt.setNull(5, Types.BIGINT); + } + pstmt.setString(6, userStat.getDeviceType()); + if(userStat.getNetworkId() != null){ + pstmt.setLong(7, userStat.getNetworkId()); + } else { + pstmt.setNull(7, Types.BIGINT); + } + pstmt.setLong(8, userStat.getNetBytesReceived()); + pstmt.setLong(9, userStat.getNetBytesSent()); + pstmt.setLong(10, userStat.getCurrentBytesReceived()); pstmt.setLong(11, userStat.getCurrentBytesSent()); pstmt.setLong(12, userStat.getAggBytesReceived()); - pstmt.setLong(13, userStat.getAggBytesSent()); - pstmt.addBatch(); - } - pstmt.executeBatch(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error saving user stats to cloud_usage db", ex); - throw new UsageServerException(ex.getMessage()); - } - } - - @Override - public void updateUserStats(List userStats) throws UsageServerException { - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - String sql = UPDATE_USER_STATS; - PreparedStatement pstmt = null; - pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection - for (UserStatisticsVO userStat : userStats) { - pstmt.setLong(1, userStat.getNetBytesReceived()); - pstmt.setLong(2, userStat.getNetBytesSent()); - pstmt.setLong(3, userStat.getCurrentBytesReceived()); + pstmt.setLong(13, userStat.getAggBytesSent()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error saving user stats to cloud_usage db", ex); + throw new UsageServerException(ex.getMessage()); + } + } + + @Override + public void updateUserStats(List userStats) throws UsageServerException { + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + String sql = UPDATE_USER_STATS; + PreparedStatement pstmt = null; + pstmt = txn.prepareAutoCloseStatement(sql); // in reality I just want CLOUD_USAGE dataSource connection + for (UserStatisticsVO userStat : userStats) { + pstmt.setLong(1, userStat.getNetBytesReceived()); + pstmt.setLong(2, userStat.getNetBytesSent()); + pstmt.setLong(3, userStat.getCurrentBytesReceived()); pstmt.setLong(4, userStat.getCurrentBytesSent()); pstmt.setLong(5, userStat.getAggBytesReceived()); - pstmt.setLong(6, userStat.getAggBytesSent()); - pstmt.setLong(7, userStat.getId()); - pstmt.addBatch(); - } - pstmt.executeBatch(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error saving user stats to cloud_usage db", ex); - throw new UsageServerException(ex.getMessage()); - } - } - - @Override - public Long getLastAccountId() { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - String sql = GET_LAST_ACCOUNT; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - return Long.valueOf(rs.getLong(1)); - } - } catch (Exception ex) { - s_logger.error("error getting last account id", ex); - } - return null; - } - - @Override - public Long getLastUserStatsId() { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - String sql = GET_LAST_USER_STATS; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - return Long.valueOf(rs.getLong(1)); - } - } catch (Exception ex) { - s_logger.error("error getting last user stats id", ex); - } - return null; - } - - @Override - public List listPublicTemplatesByAccount(long accountId) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - String sql = GET_PUBLIC_TEMPLATES_BY_ACCOUNTID; - List templateList = new ArrayList(); - try { - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - templateList.add(Long.valueOf(rs.getLong(1))); - } - } catch (Exception ex) { - s_logger.error("error listing public templates", ex); - } - return templateList; - } -} + pstmt.setLong(6, userStat.getAggBytesSent()); + pstmt.setLong(7, userStat.getId()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error saving user stats to cloud_usage db", ex); + throw new UsageServerException(ex.getMessage()); + } + } + + @Override + public Long getLastAccountId() { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + String sql = GET_LAST_ACCOUNT; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { + return Long.valueOf(rs.getLong(1)); + } + } catch (Exception ex) { + s_logger.error("error getting last account id", ex); + } + return null; + } + + @Override + public Long getLastUserStatsId() { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + String sql = GET_LAST_USER_STATS; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { + return Long.valueOf(rs.getLong(1)); + } + } catch (Exception ex) { + s_logger.error("error getting last user stats id", ex); + } + return null; + } + + @Override + public List listPublicTemplatesByAccount(long accountId) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + String sql = GET_PUBLIC_TEMPLATES_BY_ACCOUNTID; + List templateList = new ArrayList(); + try { + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { + templateList.add(Long.valueOf(rs.getLong(1))); + } + } catch (Exception ex) { + s_logger.error("error listing public templates", ex); + } + return templateList; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageIPAddressDao.java b/server/src/com/cloud/usage/dao/UsageIPAddressDao.java index 3173aa8b5b3..07c53a3918a 100644 --- a/server/src/com/cloud/usage/dao/UsageIPAddressDao.java +++ b/server/src/com/cloud/usage/dao/UsageIPAddressDao.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageIPAddressVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageIPAddressDao extends GenericDao { - public void update(UsageIPAddressVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageIPAddressVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageIPAddressDao extends GenericDao { + public void update(UsageIPAddressVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate); +} diff --git a/server/src/com/cloud/usage/dao/UsageIPAddressDaoImpl.java b/server/src/com/cloud/usage/dao/UsageIPAddressDaoImpl.java index 364544aed76..7ce2ae40ccd 100644 --- a/server/src/com/cloud/usage/dao/UsageIPAddressDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageIPAddressDaoImpl.java @@ -10,130 +10,130 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageIPAddressVO; -import com.cloud.user.Account; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageIPAddressDao.class}) -public class UsageIPAddressDaoImpl extends GenericDaoBase implements UsageIPAddressDao { - public static final Logger s_logger = Logger.getLogger(UsageIPAddressDaoImpl.class.getName()); - - protected static final String UPDATE_RELEASED = "UPDATE usage_ip_address SET released = ? WHERE account_id = ? AND public_ip_address = ? and released IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, account_id, domain_id, zone_id, public_ip_address, is_source_nat, is_system, assigned, released " + - "FROM usage_ip_address " + - "WHERE account_id = ? AND ((released IS NULL AND assigned <= ?) OR (assigned BETWEEN ? AND ?) OR " + - " (released BETWEEN ? AND ?) OR ((assigned <= ?) AND (released >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, account_id, domain_id, zone_id, public_ip_address, is_source_nat, is_system, assigned, released " + - "FROM usage_ip_address " + - "WHERE domain_id = ? AND ((released IS NULL AND assigned <= ?) OR (assigned BETWEEN ? AND ?) OR " + - " (released BETWEEN ? AND ?) OR ((assigned <= ?) AND (released >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, account_id, domain_id, zone_id, public_ip_address, is_source_nat, is_system, assigned, released " + - "FROM usage_ip_address " + - "WHERE (released IS NULL AND assigned <= ?) OR (assigned BETWEEN ? AND ?) OR " + - " (released BETWEEN ? AND ?) OR ((assigned <= ?) AND (released >= ?))"; - - public UsageIPAddressDaoImpl() {} - - public void update(UsageIPAddressVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getReleased() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_RELEASED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getReleased())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setString(3, usage.getAddress()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating usageIPAddressVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //account_id, domain_id, zone_id, address, assigned, released - Long id = Long.valueOf(rs.getLong(1)); - Long acctId = Long.valueOf(rs.getLong(2)); - Long dId = Long.valueOf(rs.getLong(3)); - Long zId = Long.valueOf(rs.getLong(4)); - String addr = rs.getString(5); +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageIPAddressVO; +import com.cloud.user.Account; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageIPAddressDao.class}) +public class UsageIPAddressDaoImpl extends GenericDaoBase implements UsageIPAddressDao { + public static final Logger s_logger = Logger.getLogger(UsageIPAddressDaoImpl.class.getName()); + + protected static final String UPDATE_RELEASED = "UPDATE usage_ip_address SET released = ? WHERE account_id = ? AND public_ip_address = ? and released IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, account_id, domain_id, zone_id, public_ip_address, is_source_nat, is_system, assigned, released " + + "FROM usage_ip_address " + + "WHERE account_id = ? AND ((released IS NULL AND assigned <= ?) OR (assigned BETWEEN ? AND ?) OR " + + " (released BETWEEN ? AND ?) OR ((assigned <= ?) AND (released >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, account_id, domain_id, zone_id, public_ip_address, is_source_nat, is_system, assigned, released " + + "FROM usage_ip_address " + + "WHERE domain_id = ? AND ((released IS NULL AND assigned <= ?) OR (assigned BETWEEN ? AND ?) OR " + + " (released BETWEEN ? AND ?) OR ((assigned <= ?) AND (released >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, account_id, domain_id, zone_id, public_ip_address, is_source_nat, is_system, assigned, released " + + "FROM usage_ip_address " + + "WHERE (released IS NULL AND assigned <= ?) OR (assigned BETWEEN ? AND ?) OR " + + " (released BETWEEN ? AND ?) OR ((assigned <= ?) AND (released >= ?))"; + + public UsageIPAddressDaoImpl() {} + + public void update(UsageIPAddressVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getReleased() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_RELEASED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getReleased())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setString(3, usage.getAddress()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating usageIPAddressVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //account_id, domain_id, zone_id, address, assigned, released + Long id = Long.valueOf(rs.getLong(1)); + Long acctId = Long.valueOf(rs.getLong(2)); + Long dId = Long.valueOf(rs.getLong(3)); + Long zId = Long.valueOf(rs.getLong(4)); + String addr = rs.getString(5); Boolean isSourceNat = Boolean.valueOf(rs.getBoolean(6)); - Boolean isSystem = Boolean.valueOf(rs.getBoolean(7)); - Date assignedDate = null; - Date releasedDate = null; - String assignedTS = rs.getString(8); - String releasedTS = rs.getString(9); - - if (assignedTS != null) { - assignedDate = DateUtil.parseDateString(s_gmtTimeZone, assignedTS); - } - if (releasedTS != null) { - releasedDate = DateUtil.parseDateString(s_gmtTimeZone, releasedTS); - } - - usageRecords.add(new UsageIPAddressVO(id, acctId, dId, zId, addr, isSourceNat, isSystem, assignedDate, releasedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} + Boolean isSystem = Boolean.valueOf(rs.getBoolean(7)); + Date assignedDate = null; + Date releasedDate = null; + String assignedTS = rs.getString(8); + String releasedTS = rs.getString(9); + + if (assignedTS != null) { + assignedDate = DateUtil.parseDateString(s_gmtTimeZone, assignedTS); + } + if (releasedTS != null) { + releasedDate = DateUtil.parseDateString(s_gmtTimeZone, releasedTS); + } + + usageRecords.add(new UsageIPAddressVO(id, acctId, dId, zId, addr, isSourceNat, isSystem, assignedDate, releasedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageJobDao.java b/server/src/com/cloud/usage/dao/UsageJobDao.java index bec5f827652..059af71e9a0 100644 --- a/server/src/com/cloud/usage/dao/UsageJobDao.java +++ b/server/src/com/cloud/usage/dao/UsageJobDao.java @@ -10,21 +10,21 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; - -import com.cloud.exception.UsageServerException; -import com.cloud.usage.UsageJobVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageJobDao extends GenericDao { - Long checkHeartbeat(String hostname, int pid, int aggregationDuration); - void createNewJob(String hostname, int pid, int jobType); - UsageJobVO getLastJob(); - UsageJobVO getNextImmediateJob(); - long getLastJobSuccessDateMillis(); - Date getLastHeartbeat(); - UsageJobVO isOwner(String hostname, int pid); - void updateJobSuccess(Long jobId, long startMillis, long endMillis, long execTime, boolean success) throws UsageServerException; -} +package com.cloud.usage.dao; + +import java.util.Date; + +import com.cloud.exception.UsageServerException; +import com.cloud.usage.UsageJobVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageJobDao extends GenericDao { + Long checkHeartbeat(String hostname, int pid, int aggregationDuration); + void createNewJob(String hostname, int pid, int jobType); + UsageJobVO getLastJob(); + UsageJobVO getNextImmediateJob(); + long getLastJobSuccessDateMillis(); + Date getLastHeartbeat(); + UsageJobVO isOwner(String hostname, int pid); + void updateJobSuccess(Long jobId, long startMillis, long endMillis, long execTime, boolean success) throws UsageServerException; +} diff --git a/server/src/com/cloud/usage/dao/UsageJobDaoImpl.java b/server/src/com/cloud/usage/dao/UsageJobDaoImpl.java index 4fc9b103b44..8c716abe5dc 100644 --- a/server/src/com/cloud/usage/dao/UsageJobDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageJobDaoImpl.java @@ -10,185 +10,185 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Date; -import java.util.List; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.exception.UsageServerException; -import com.cloud.usage.UsageJobVO; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageJobDao.class}) -public class UsageJobDaoImpl extends GenericDaoBase implements UsageJobDao { - private static final Logger s_logger = Logger.getLogger(UsageJobDaoImpl.class.getName()); - - private static final String GET_LAST_JOB_SUCCESS_DATE_MILLIS = "SELECT end_millis FROM cloud_usage.usage_job WHERE end_millis > 0 and success = 1 ORDER BY end_millis DESC LIMIT 1"; - - @Override - public long getLastJobSuccessDateMillis() { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - String sql = GET_LAST_JOB_SUCCESS_DATE_MILLIS; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - return rs.getLong(1); - } - } catch (Exception ex) { - s_logger.error("error getting last usage job success date", ex); - } finally { - txn.close(); - } - return 0L; - } - - @Override - public void updateJobSuccess(Long jobId, long startMillis, long endMillis, long execTime, boolean success) throws UsageServerException { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - try { - txn.start(); - - UsageJobVO job = lockRow(jobId, Boolean.TRUE); - UsageJobVO jobForUpdate = createForUpdate(); - jobForUpdate.setStartMillis(startMillis); - jobForUpdate.setEndMillis(endMillis); - jobForUpdate.setExecTime(execTime); - jobForUpdate.setStartDate(new Date(startMillis)); - jobForUpdate.setEndDate(new Date(endMillis)); - jobForUpdate.setSuccess(success); - update(job.getId(), jobForUpdate); - - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error updating job success date", ex); - throw new UsageServerException(ex.getMessage()); - } finally { - txn.close(); - } - } - - @Override - public Long checkHeartbeat(String hostname, int pid, int aggregationDuration) { - UsageJobVO job = getNextRecurringJob(); - if (job == null) { - return null; - } - - if (job.getHost().equals(hostname) && (job.getPid() != null) && (job.getPid().intValue() == pid)) { - return job.getId(); - } - - Date lastHeartbeat = job.getHeartbeat(); - if (lastHeartbeat == null) { - return null; - } - - long sinceLastHeartbeat = System.currentTimeMillis() - lastHeartbeat.getTime(); - - // TODO: Make this check a little smarter..but in the mean time we want the mgmt - // server to monitor the usage server, we need to make sure other usage - // servers take over as the usage job owner more aggressively. For now - // this is hardcoded to 5 minutes. - if (sinceLastHeartbeat > (5 * 60 * 1000)) { - return job.getId(); - } - return null; - } - - @Override - public UsageJobVO isOwner(String hostname, int pid) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - try { - if ((hostname == null) || (pid <= 0)) { - return null; - } - - UsageJobVO job = getLastJob(); - if (job == null) { - return null; - } - - if (hostname.equals(job.getHost()) && (job.getPid() != null) && (pid == job.getPid().intValue())) { - return job; - } - } finally { - txn.close(); - } - return null; - } - - @Override - public void createNewJob(String hostname, int pid, int jobType) { - UsageJobVO newJob = new UsageJobVO(); - newJob.setHost(hostname); - newJob.setPid(pid); - newJob.setHeartbeat(new Date()); - newJob.setJobType(jobType); - persist(newJob); - } - - @Override - public UsageJobVO getLastJob() { - Filter filter = new Filter(UsageJobVO.class, "id", false, Long.valueOf(0), Long.valueOf(1)); - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); - List jobs = search(sc, filter); - - if ((jobs == null) || jobs.isEmpty()) { - return null; - } - return jobs.get(0); - } - - private UsageJobVO getNextRecurringJob() { - Filter filter = new Filter(UsageJobVO.class, "id", false, Long.valueOf(0), Long.valueOf(1)); - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); - sc.addAnd("jobType", SearchCriteria.Op.EQ, Integer.valueOf(UsageJobVO.JOB_TYPE_RECURRING)); - List jobs = search(sc, filter); - - if ((jobs == null) || jobs.isEmpty()) { - return null; - } - return jobs.get(0); - } - - @Override - public UsageJobVO getNextImmediateJob() { - Filter filter = new Filter(UsageJobVO.class, "id", false, Long.valueOf(0), Long.valueOf(1)); - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); - sc.addAnd("jobType", SearchCriteria.Op.EQ, Integer.valueOf(UsageJobVO.JOB_TYPE_SINGLE)); - sc.addAnd("scheduled", SearchCriteria.Op.EQ, Integer.valueOf(0)); - List jobs = search(sc, filter); - - if ((jobs == null) || jobs.isEmpty()) { - return null; - } - return jobs.get(0); - } - - @Override - public Date getLastHeartbeat() { - Filter filter = new Filter(UsageJobVO.class, "heartbeat", false, Long.valueOf(0), Long.valueOf(1)); - SearchCriteria sc = createSearchCriteria(); - List jobs = search(sc, filter); - - if ((jobs == null) || jobs.isEmpty()) { - return null; - } - return jobs.get(0).getHeartbeat(); - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Date; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.exception.UsageServerException; +import com.cloud.usage.UsageJobVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageJobDao.class}) +public class UsageJobDaoImpl extends GenericDaoBase implements UsageJobDao { + private static final Logger s_logger = Logger.getLogger(UsageJobDaoImpl.class.getName()); + + private static final String GET_LAST_JOB_SUCCESS_DATE_MILLIS = "SELECT end_millis FROM cloud_usage.usage_job WHERE end_millis > 0 and success = 1 ORDER BY end_millis DESC LIMIT 1"; + + @Override + public long getLastJobSuccessDateMillis() { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + String sql = GET_LAST_JOB_SUCCESS_DATE_MILLIS; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { + return rs.getLong(1); + } + } catch (Exception ex) { + s_logger.error("error getting last usage job success date", ex); + } finally { + txn.close(); + } + return 0L; + } + + @Override + public void updateJobSuccess(Long jobId, long startMillis, long endMillis, long execTime, boolean success) throws UsageServerException { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + try { + txn.start(); + + UsageJobVO job = lockRow(jobId, Boolean.TRUE); + UsageJobVO jobForUpdate = createForUpdate(); + jobForUpdate.setStartMillis(startMillis); + jobForUpdate.setEndMillis(endMillis); + jobForUpdate.setExecTime(execTime); + jobForUpdate.setStartDate(new Date(startMillis)); + jobForUpdate.setEndDate(new Date(endMillis)); + jobForUpdate.setSuccess(success); + update(job.getId(), jobForUpdate); + + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error updating job success date", ex); + throw new UsageServerException(ex.getMessage()); + } finally { + txn.close(); + } + } + + @Override + public Long checkHeartbeat(String hostname, int pid, int aggregationDuration) { + UsageJobVO job = getNextRecurringJob(); + if (job == null) { + return null; + } + + if (job.getHost().equals(hostname) && (job.getPid() != null) && (job.getPid().intValue() == pid)) { + return job.getId(); + } + + Date lastHeartbeat = job.getHeartbeat(); + if (lastHeartbeat == null) { + return null; + } + + long sinceLastHeartbeat = System.currentTimeMillis() - lastHeartbeat.getTime(); + + // TODO: Make this check a little smarter..but in the mean time we want the mgmt + // server to monitor the usage server, we need to make sure other usage + // servers take over as the usage job owner more aggressively. For now + // this is hardcoded to 5 minutes. + if (sinceLastHeartbeat > (5 * 60 * 1000)) { + return job.getId(); + } + return null; + } + + @Override + public UsageJobVO isOwner(String hostname, int pid) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + try { + if ((hostname == null) || (pid <= 0)) { + return null; + } + + UsageJobVO job = getLastJob(); + if (job == null) { + return null; + } + + if (hostname.equals(job.getHost()) && (job.getPid() != null) && (pid == job.getPid().intValue())) { + return job; + } + } finally { + txn.close(); + } + return null; + } + + @Override + public void createNewJob(String hostname, int pid, int jobType) { + UsageJobVO newJob = new UsageJobVO(); + newJob.setHost(hostname); + newJob.setPid(pid); + newJob.setHeartbeat(new Date()); + newJob.setJobType(jobType); + persist(newJob); + } + + @Override + public UsageJobVO getLastJob() { + Filter filter = new Filter(UsageJobVO.class, "id", false, Long.valueOf(0), Long.valueOf(1)); + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); + List jobs = search(sc, filter); + + if ((jobs == null) || jobs.isEmpty()) { + return null; + } + return jobs.get(0); + } + + private UsageJobVO getNextRecurringJob() { + Filter filter = new Filter(UsageJobVO.class, "id", false, Long.valueOf(0), Long.valueOf(1)); + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); + sc.addAnd("jobType", SearchCriteria.Op.EQ, Integer.valueOf(UsageJobVO.JOB_TYPE_RECURRING)); + List jobs = search(sc, filter); + + if ((jobs == null) || jobs.isEmpty()) { + return null; + } + return jobs.get(0); + } + + @Override + public UsageJobVO getNextImmediateJob() { + Filter filter = new Filter(UsageJobVO.class, "id", false, Long.valueOf(0), Long.valueOf(1)); + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); + sc.addAnd("jobType", SearchCriteria.Op.EQ, Integer.valueOf(UsageJobVO.JOB_TYPE_SINGLE)); + sc.addAnd("scheduled", SearchCriteria.Op.EQ, Integer.valueOf(0)); + List jobs = search(sc, filter); + + if ((jobs == null) || jobs.isEmpty()) { + return null; + } + return jobs.get(0); + } + + @Override + public Date getLastHeartbeat() { + Filter filter = new Filter(UsageJobVO.class, "heartbeat", false, Long.valueOf(0), Long.valueOf(1)); + SearchCriteria sc = createSearchCriteria(); + List jobs = search(sc, filter); + + if ((jobs == null) || jobs.isEmpty()) { + return null; + } + return jobs.get(0).getHeartbeat(); + } +} diff --git a/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDao.java b/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDao.java index 5609a2f5eee..5d16e629885 100644 --- a/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDao.java +++ b/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageLoadBalancerPolicyVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageLoadBalancerPolicyDao extends GenericDao { - public void removeBy(long userId, long id); - public void update(UsageLoadBalancerPolicyVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageLoadBalancerPolicyVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageLoadBalancerPolicyDao extends GenericDao { + public void removeBy(long userId, long id); + public void update(UsageLoadBalancerPolicyVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); +} diff --git a/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java b/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java index 9e87717f84a..c6283c705f6 100644 --- a/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java @@ -10,154 +10,154 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageLoadBalancerPolicyVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageLoadBalancerPolicyDao.class}) -public class UsageLoadBalancerPolicyDaoImpl extends GenericDaoBase implements UsageLoadBalancerPolicyDao { - public static final Logger s_logger = Logger.getLogger(UsageLoadBalancerPolicyDaoImpl.class.getName()); - - protected static final String REMOVE_BY_USERID_LBID = "DELETE FROM usage_load_balancer_policy WHERE account_id = ? AND id = ?"; - protected static final String UPDATE_DELETED = "UPDATE usage_load_balancer_policy SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, created, deleted " + - "FROM usage_load_balancer_policy " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, created, deleted " + - "FROM usage_load_balancer_policy " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, created, deleted " + - "FROM usage_load_balancer_policy " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - public UsageLoadBalancerPolicyDaoImpl() {} - - public void removeBy(long accountId, long lbId) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = REMOVE_BY_USERID_LBID; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - pstmt.setLong(2, lbId); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error removing UsageLoadBalancerPolicyVO", e); - } finally { - txn.close(); - } - } - - public void update(UsageLoadBalancerPolicyVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getId()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsageLoadBalancerPolicyVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //id, zone_id, account_id, domain_id, created, deleted - Long lbId = Long.valueOf(rs.getLong(1)); - Long zoneId = Long.valueOf(rs.getLong(2)); - Long acctId = Long.valueOf(rs.getLong(3)); - Long dId = Long.valueOf(rs.getLong(4)); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(5); - String deletedTS = rs.getString(6); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsageLoadBalancerPolicyVO(lbId, zoneId, acctId, dId, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageLoadBalancerPolicyVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageLoadBalancerPolicyDao.class}) +public class UsageLoadBalancerPolicyDaoImpl extends GenericDaoBase implements UsageLoadBalancerPolicyDao { + public static final Logger s_logger = Logger.getLogger(UsageLoadBalancerPolicyDaoImpl.class.getName()); + + protected static final String REMOVE_BY_USERID_LBID = "DELETE FROM usage_load_balancer_policy WHERE account_id = ? AND id = ?"; + protected static final String UPDATE_DELETED = "UPDATE usage_load_balancer_policy SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, created, deleted " + + "FROM usage_load_balancer_policy " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, created, deleted " + + "FROM usage_load_balancer_policy " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, created, deleted " + + "FROM usage_load_balancer_policy " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + public UsageLoadBalancerPolicyDaoImpl() {} + + public void removeBy(long accountId, long lbId) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = REMOVE_BY_USERID_LBID; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + pstmt.setLong(2, lbId); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error removing UsageLoadBalancerPolicyVO", e); + } finally { + txn.close(); + } + } + + public void update(UsageLoadBalancerPolicyVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getId()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsageLoadBalancerPolicyVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //id, zone_id, account_id, domain_id, created, deleted + Long lbId = Long.valueOf(rs.getLong(1)); + Long zoneId = Long.valueOf(rs.getLong(2)); + Long acctId = Long.valueOf(rs.getLong(3)); + Long dId = Long.valueOf(rs.getLong(4)); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(5); + String deletedTS = rs.getString(6); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsageLoadBalancerPolicyVO(lbId, zoneId, acctId, dId, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageNetworkDao.java b/server/src/com/cloud/usage/dao/UsageNetworkDao.java index a1d45769691..dbeea8e9443 100644 --- a/server/src/com/cloud/usage/dao/UsageNetworkDao.java +++ b/server/src/com/cloud/usage/dao/UsageNetworkDao.java @@ -10,14 +10,14 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Map; - -import com.cloud.usage.UsageNetworkVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageNetworkDao extends GenericDao { - Map getRecentNetworkStats(); - void deleteOldStats(long maxEventTime); -} +package com.cloud.usage.dao; + +import java.util.Map; + +import com.cloud.usage.UsageNetworkVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageNetworkDao extends GenericDao { + Map getRecentNetworkStats(); + void deleteOldStats(long maxEventTime); +} diff --git a/server/src/com/cloud/usage/dao/UsageNetworkDaoImpl.java b/server/src/com/cloud/usage/dao/UsageNetworkDaoImpl.java index b567792d230..5cc5a996f58 100644 --- a/server/src/com/cloud/usage/dao/UsageNetworkDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageNetworkDaoImpl.java @@ -10,83 +10,83 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.HashMap; -import java.util.Map; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageNetworkVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageNetworkDao.class}) -public class UsageNetworkDaoImpl extends GenericDaoBase implements UsageNetworkDao { - private static final Logger s_logger = Logger.getLogger(UsageVMInstanceDaoImpl.class.getName()); - private static final String SELECT_LATEST_STATS = "SELECT u.account_id, u.zone_id, u.host_id, u.host_type, u.network_id, u.bytes_sent, u.bytes_received, u.agg_bytes_received, u.agg_bytes_sent, u.event_time_millis " + - "FROM cloud_usage.usage_network u INNER JOIN (SELECT netusage.account_id as acct_id, netusage.zone_id as z_id, max(netusage.event_time_millis) as max_date " + - "FROM cloud_usage.usage_network netusage " + - "GROUP BY netusage.account_id, netusage.zone_id " + - ") joinnet on u.account_id = joinnet.acct_id and u.zone_id = joinnet.z_id and u.event_time_millis = joinnet.max_date"; - private static final String DELETE_OLD_STATS = "DELETE FROM cloud_usage.usage_network WHERE event_time_millis < ?"; - - public UsageNetworkDaoImpl() { - } - - @Override - public Map getRecentNetworkStats() { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - String sql = SELECT_LATEST_STATS; - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - Map returnMap = new HashMap(); - while (rs.next()) { - long accountId = rs.getLong(1); - long zoneId = rs.getLong(2); - Long hostId = rs.getLong(3); - String hostType = rs.getString(4); - Long networkId = rs.getLong(5); - long bytesSent = rs.getLong(6); - long bytesReceived = rs.getLong(7); - long aggBytesReceived = rs.getLong(8); - long aggBytesSent = rs.getLong(9); - long eventTimeMillis = rs.getLong(10); - if(hostId != 0){ - returnMap.put(zoneId + "-" + accountId+ "-Host-" + hostId, new UsageNetworkVO(accountId, zoneId, hostId, hostType, networkId, bytesSent, bytesReceived, aggBytesReceived, aggBytesSent, eventTimeMillis)); - } else { - returnMap.put(zoneId + "-" + accountId, new UsageNetworkVO(accountId, zoneId, hostId, hostType, networkId, bytesSent, bytesReceived, aggBytesReceived, aggBytesSent, eventTimeMillis)); - } - } - return returnMap; - } catch (Exception ex) { - s_logger.error("error getting recent usage network stats", ex); - } finally { - txn.close(); - } - return null; - } - - @Override - public void deleteOldStats(long maxEventTime) { - Transaction txn = Transaction.currentTxn(); - String sql = DELETE_OLD_STATS; - PreparedStatement pstmt = null; - try { - txn.start(); - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, maxEventTime); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error deleting old usage network stats", ex); - } - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageNetworkVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageNetworkDao.class}) +public class UsageNetworkDaoImpl extends GenericDaoBase implements UsageNetworkDao { + private static final Logger s_logger = Logger.getLogger(UsageVMInstanceDaoImpl.class.getName()); + private static final String SELECT_LATEST_STATS = "SELECT u.account_id, u.zone_id, u.host_id, u.host_type, u.network_id, u.bytes_sent, u.bytes_received, u.agg_bytes_received, u.agg_bytes_sent, u.event_time_millis " + + "FROM cloud_usage.usage_network u INNER JOIN (SELECT netusage.account_id as acct_id, netusage.zone_id as z_id, max(netusage.event_time_millis) as max_date " + + "FROM cloud_usage.usage_network netusage " + + "GROUP BY netusage.account_id, netusage.zone_id " + + ") joinnet on u.account_id = joinnet.acct_id and u.zone_id = joinnet.z_id and u.event_time_millis = joinnet.max_date"; + private static final String DELETE_OLD_STATS = "DELETE FROM cloud_usage.usage_network WHERE event_time_millis < ?"; + + public UsageNetworkDaoImpl() { + } + + @Override + public Map getRecentNetworkStats() { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + String sql = SELECT_LATEST_STATS; + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + ResultSet rs = pstmt.executeQuery(); + Map returnMap = new HashMap(); + while (rs.next()) { + long accountId = rs.getLong(1); + long zoneId = rs.getLong(2); + Long hostId = rs.getLong(3); + String hostType = rs.getString(4); + Long networkId = rs.getLong(5); + long bytesSent = rs.getLong(6); + long bytesReceived = rs.getLong(7); + long aggBytesReceived = rs.getLong(8); + long aggBytesSent = rs.getLong(9); + long eventTimeMillis = rs.getLong(10); + if(hostId != 0){ + returnMap.put(zoneId + "-" + accountId+ "-Host-" + hostId, new UsageNetworkVO(accountId, zoneId, hostId, hostType, networkId, bytesSent, bytesReceived, aggBytesReceived, aggBytesSent, eventTimeMillis)); + } else { + returnMap.put(zoneId + "-" + accountId, new UsageNetworkVO(accountId, zoneId, hostId, hostType, networkId, bytesSent, bytesReceived, aggBytesReceived, aggBytesSent, eventTimeMillis)); + } + } + return returnMap; + } catch (Exception ex) { + s_logger.error("error getting recent usage network stats", ex); + } finally { + txn.close(); + } + return null; + } + + @Override + public void deleteOldStats(long maxEventTime) { + Transaction txn = Transaction.currentTxn(); + String sql = DELETE_OLD_STATS; + PreparedStatement pstmt = null; + try { + txn.start(); + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, maxEventTime); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error deleting old usage network stats", ex); + } + } +} diff --git a/server/src/com/cloud/usage/dao/UsageNetworkOfferingDao.java b/server/src/com/cloud/usage/dao/UsageNetworkOfferingDao.java index 3f6f9cdcda6..6c4138df065 100644 --- a/server/src/com/cloud/usage/dao/UsageNetworkOfferingDao.java +++ b/server/src/com/cloud/usage/dao/UsageNetworkOfferingDao.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageNetworkOfferingVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageNetworkOfferingDao extends GenericDao { - public void update(UsageNetworkOfferingVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageNetworkOfferingVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageNetworkOfferingDao extends GenericDao { + public void update(UsageNetworkOfferingVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); +} diff --git a/server/src/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java b/server/src/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java index 340414ba03f..9c08d5ab344 100644 --- a/server/src/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java @@ -10,137 +10,137 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageNetworkOfferingVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageNetworkOfferingDao.class}) -public class UsageNetworkOfferingDaoImpl extends GenericDaoBase implements UsageNetworkOfferingDao { - public static final Logger s_logger = Logger.getLogger(UsageNetworkOfferingDaoImpl.class.getName()); - - protected static final String UPDATE_DELETED = "UPDATE usage_network_offering SET deleted = ? WHERE account_id = ? AND vm_instance_id = ? AND network_offering_id = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted " + - "FROM usage_network_offering " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted " + - "FROM usage_network_offering " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted " + - "FROM usage_network_offering " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - public UsageNetworkOfferingDaoImpl() {} - - public void update(UsageNetworkOfferingVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getVmInstanceId()); - pstmt.setLong(4, usage.getNetworkOfferingId()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsageNetworkOfferingVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //zoneId, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted - Long zoneId = Long.valueOf(rs.getLong(1)); - Long acctId = Long.valueOf(rs.getLong(2)); - Long dId = Long.valueOf(rs.getLong(3)); - long vmId = Long.valueOf(rs.getLong(4)); - long noId = Long.valueOf(rs.getLong(5)); - boolean isDefault = Boolean.valueOf(rs.getBoolean(6)); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(7); - String deletedTS = rs.getString(8); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsageNetworkOfferingVO(zoneId, acctId, dId, vmId, noId, isDefault, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageNetworkOfferingVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageNetworkOfferingDao.class}) +public class UsageNetworkOfferingDaoImpl extends GenericDaoBase implements UsageNetworkOfferingDao { + public static final Logger s_logger = Logger.getLogger(UsageNetworkOfferingDaoImpl.class.getName()); + + protected static final String UPDATE_DELETED = "UPDATE usage_network_offering SET deleted = ? WHERE account_id = ? AND vm_instance_id = ? AND network_offering_id = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted " + + "FROM usage_network_offering " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted " + + "FROM usage_network_offering " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted " + + "FROM usage_network_offering " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + public UsageNetworkOfferingDaoImpl() {} + + public void update(UsageNetworkOfferingVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getVmInstanceId()); + pstmt.setLong(4, usage.getNetworkOfferingId()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsageNetworkOfferingVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //zoneId, account_id, domain_id, vm_instance_id, network_offering_id, is_default, created, deleted + Long zoneId = Long.valueOf(rs.getLong(1)); + Long acctId = Long.valueOf(rs.getLong(2)); + Long dId = Long.valueOf(rs.getLong(3)); + long vmId = Long.valueOf(rs.getLong(4)); + long noId = Long.valueOf(rs.getLong(5)); + boolean isDefault = Boolean.valueOf(rs.getBoolean(6)); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(7); + String deletedTS = rs.getString(8); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsageNetworkOfferingVO(zoneId, acctId, dId, vmId, noId, isDefault, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDao.java b/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDao.java index 2a23c493b9e..170905288d5 100644 --- a/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDao.java +++ b/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsagePortForwardingRuleVO; -import com.cloud.utils.db.GenericDao; - -public interface UsagePortForwardingRuleDao extends GenericDao { - public void removeBy(long userId, long id); - public void update(UsagePortForwardingRuleVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsagePortForwardingRuleVO; +import com.cloud.utils.db.GenericDao; + +public interface UsagePortForwardingRuleDao extends GenericDao { + public void removeBy(long userId, long id); + public void update(UsagePortForwardingRuleVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); +} diff --git a/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java b/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java index 6a6a06581a5..004ccd4f517 100644 --- a/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java @@ -10,154 +10,154 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsagePortForwardingRuleVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsagePortForwardingRuleDao.class}) -public class UsagePortForwardingRuleDaoImpl extends GenericDaoBase implements UsagePortForwardingRuleDao { - public static final Logger s_logger = Logger.getLogger(UsagePortForwardingRuleDaoImpl.class.getName()); - - protected static final String REMOVE_BY_USERID_PFID = "DELETE FROM usage_port_forwarding WHERE account_id = ? AND id = ?"; - protected static final String UPDATE_DELETED = "UPDATE usage_port_forwarding SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, created, deleted " + - "FROM usage_port_forwarding " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, created, deleted " + - "FROM usage_port_forwarding " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, created, deleted " + - "FROM usage_port_forwarding " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - public UsagePortForwardingRuleDaoImpl() {} - - public void removeBy(long accountId, long pfId) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = REMOVE_BY_USERID_PFID; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - pstmt.setLong(2, pfId); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error removing UsagePortForwardingRuleVO", e); - } finally { - txn.close(); - } - } - - public void update(UsagePortForwardingRuleVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getId()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsagePortForwardingRuleVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //id, zone_id, account_id, domain_id, created, deleted - Long pfId = Long.valueOf(rs.getLong(1)); - Long zoneId = Long.valueOf(rs.getLong(2)); - Long acctId = Long.valueOf(rs.getLong(3)); - Long dId = Long.valueOf(rs.getLong(4)); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(5); - String deletedTS = rs.getString(6); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsagePortForwardingRuleVO(pfId, zoneId, acctId, dId, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsagePortForwardingRuleVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsagePortForwardingRuleDao.class}) +public class UsagePortForwardingRuleDaoImpl extends GenericDaoBase implements UsagePortForwardingRuleDao { + public static final Logger s_logger = Logger.getLogger(UsagePortForwardingRuleDaoImpl.class.getName()); + + protected static final String REMOVE_BY_USERID_PFID = "DELETE FROM usage_port_forwarding WHERE account_id = ? AND id = ?"; + protected static final String UPDATE_DELETED = "UPDATE usage_port_forwarding SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, created, deleted " + + "FROM usage_port_forwarding " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, created, deleted " + + "FROM usage_port_forwarding " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, created, deleted " + + "FROM usage_port_forwarding " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + public UsagePortForwardingRuleDaoImpl() {} + + public void removeBy(long accountId, long pfId) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = REMOVE_BY_USERID_PFID; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + pstmt.setLong(2, pfId); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error removing UsagePortForwardingRuleVO", e); + } finally { + txn.close(); + } + } + + public void update(UsagePortForwardingRuleVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getId()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsagePortForwardingRuleVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //id, zone_id, account_id, domain_id, created, deleted + Long pfId = Long.valueOf(rs.getLong(1)); + Long zoneId = Long.valueOf(rs.getLong(2)); + Long acctId = Long.valueOf(rs.getLong(3)); + Long dId = Long.valueOf(rs.getLong(4)); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(5); + String deletedTS = rs.getString(6); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsagePortForwardingRuleVO(pfId, zoneId, acctId, dId, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageSecurityGroupDao.java b/server/src/com/cloud/usage/dao/UsageSecurityGroupDao.java index 18b15ff54d5..bec37c6ba2d 100644 --- a/server/src/com/cloud/usage/dao/UsageSecurityGroupDao.java +++ b/server/src/com/cloud/usage/dao/UsageSecurityGroupDao.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - +package com.cloud.usage.dao; + import java.util.Date; import java.util.List; import com.cloud.usage.UsageSecurityGroupVO; import com.cloud.utils.db.GenericDao; - -public interface UsageSecurityGroupDao extends GenericDao { - public void update(UsageSecurityGroupVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); -} + +public interface UsageSecurityGroupDao extends GenericDao { + public void update(UsageSecurityGroupVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); +} diff --git a/server/src/com/cloud/usage/dao/UsageSecurityGroupDaoImpl.java b/server/src/com/cloud/usage/dao/UsageSecurityGroupDaoImpl.java index 59aaf72513a..2afd4f87de6 100644 --- a/server/src/com/cloud/usage/dao/UsageSecurityGroupDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageSecurityGroupDaoImpl.java @@ -10,136 +10,136 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageSecurityGroupVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageSecurityGroupDao.class}) -public class UsageSecurityGroupDaoImpl extends GenericDaoBase implements UsageSecurityGroupDao { - public static final Logger s_logger = Logger.getLogger(UsageSecurityGroupDaoImpl.class.getName()); - - protected static final String UPDATE_DELETED = "UPDATE usage_security_group SET deleted = ? WHERE account_id = ? AND vm_instance_id = ? AND security_group_id = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, vm_instance_id, security_group_id, created, deleted " + - "FROM usage_security_group " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, vm_instance_id, security_group_id, created, deleted " + - "FROM usage_security_group " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, vm_instance_id, security_group_id, created, deleted " + - "FROM usage_security_group " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - public UsageSecurityGroupDaoImpl() {} - - public void update(UsageSecurityGroupVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getVmInstanceId()); - pstmt.setLong(4, usage.getSecurityGroupId()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsageSecurityGroupVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //zoneId, account_id, domain_id, vm_instance_id, security_group_id, created, deleted - Long zoneId = Long.valueOf(rs.getLong(1)); - Long acctId = Long.valueOf(rs.getLong(2)); - Long dId = Long.valueOf(rs.getLong(3)); - long vmId = Long.valueOf(rs.getLong(4)); - long sgId = Long.valueOf(rs.getLong(5)); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(6); - String deletedTS = rs.getString(7); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsageSecurityGroupVO(zoneId, acctId, dId, vmId, sgId, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageSecurityGroupVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageSecurityGroupDao.class}) +public class UsageSecurityGroupDaoImpl extends GenericDaoBase implements UsageSecurityGroupDao { + public static final Logger s_logger = Logger.getLogger(UsageSecurityGroupDaoImpl.class.getName()); + + protected static final String UPDATE_DELETED = "UPDATE usage_security_group SET deleted = ? WHERE account_id = ? AND vm_instance_id = ? AND security_group_id = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, vm_instance_id, security_group_id, created, deleted " + + "FROM usage_security_group " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, vm_instance_id, security_group_id, created, deleted " + + "FROM usage_security_group " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, vm_instance_id, security_group_id, created, deleted " + + "FROM usage_security_group " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + public UsageSecurityGroupDaoImpl() {} + + public void update(UsageSecurityGroupVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getVmInstanceId()); + pstmt.setLong(4, usage.getSecurityGroupId()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsageSecurityGroupVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //zoneId, account_id, domain_id, vm_instance_id, security_group_id, created, deleted + Long zoneId = Long.valueOf(rs.getLong(1)); + Long acctId = Long.valueOf(rs.getLong(2)); + Long dId = Long.valueOf(rs.getLong(3)); + long vmId = Long.valueOf(rs.getLong(4)); + long sgId = Long.valueOf(rs.getLong(5)); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(6); + String deletedTS = rs.getString(7); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsageSecurityGroupVO(zoneId, acctId, dId, vmId, sgId, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageStorageDao.java b/server/src/com/cloud/usage/dao/UsageStorageDao.java index 61d64364088..a627afe9ea4 100644 --- a/server/src/com/cloud/usage/dao/UsageStorageDao.java +++ b/server/src/com/cloud/usage/dao/UsageStorageDao.java @@ -10,18 +10,18 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageStorageVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageStorageDao extends GenericDao { - public void removeBy(long userId, long id, int storage_type); - public void update(UsageStorageVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); - List listById(long accountId, long id, int type); - List listByIdAndZone(long accountId, long id, int type, long dcId); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageStorageVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageStorageDao extends GenericDao { + public void removeBy(long userId, long id, int storage_type); + public void update(UsageStorageVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); + List listById(long accountId, long id, int type); + List listByIdAndZone(long accountId, long id, int type, long dcId); +} diff --git a/server/src/com/cloud/usage/dao/UsageStorageDaoImpl.java b/server/src/com/cloud/usage/dao/UsageStorageDaoImpl.java index e1d8f7416f8..e537b609671 100644 --- a/server/src/com/cloud/usage/dao/UsageStorageDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageStorageDaoImpl.java @@ -10,196 +10,196 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageStorageVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageStorageDao.class}) -public class UsageStorageDaoImpl extends GenericDaoBase implements UsageStorageDao { - public static final Logger s_logger = Logger.getLogger(UsageStorageDaoImpl.class.getName()); - - protected static final String REMOVE_BY_USERID_STORAGEID = "DELETE FROM usage_storage WHERE account_id = ? AND id = ? AND storage_type = ?"; - protected static final String UPDATE_DELETED = "UPDATE usage_storage SET deleted = ? WHERE account_id = ? AND id = ? AND storage_type = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " + - "FROM usage_storage " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " + - "FROM usage_storage " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " + - "FROM usage_storage " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - private final SearchBuilder IdSearch; - private final SearchBuilder IdZoneSearch; - - public UsageStorageDaoImpl() { - IdSearch = createSearchBuilder(); - IdSearch.and("accountId", IdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - IdSearch.and("id", IdSearch.entity().getId(), SearchCriteria.Op.EQ); - IdSearch.and("type", IdSearch.entity().getStorageType(), SearchCriteria.Op.EQ); - IdSearch.done(); - - IdZoneSearch = createSearchBuilder(); - IdZoneSearch.and("accountId", IdZoneSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - IdZoneSearch.and("id", IdZoneSearch.entity().getId(), SearchCriteria.Op.EQ); - IdZoneSearch.and("type", IdZoneSearch.entity().getStorageType(), SearchCriteria.Op.EQ); - IdZoneSearch.and("dcId", IdZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); - IdZoneSearch.done(); - } - - @Override - public List listById(long accountId, long id, int type) { - SearchCriteria sc = IdSearch.create(); - sc.setParameters("accountId", accountId); - sc.setParameters("id", id); - sc.setParameters("type", type); - return listBy(sc, null); - } - - @Override - public List listByIdAndZone(long accountId, long id, int type, long dcId) { - SearchCriteria sc = IdZoneSearch.create(); - sc.setParameters("accountId", accountId); - sc.setParameters("id", id); - sc.setParameters("type", type); - sc.setParameters("dcId", dcId); - return listBy(sc, null); - } - - public void removeBy(long accountId, long volId, int storage_type) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = REMOVE_BY_USERID_STORAGEID; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - pstmt.setLong(2, volId); - pstmt.setInt(3, storage_type); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error removing usageStorageVO", e); - } finally { - txn.close(); - } - } - - public void update(UsageStorageVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getId()); - pstmt.setInt(4, usage.getStorageType()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsageStorageVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //id, zone_id, account_id, domain_id, storage_type, size, created, deleted - Long id = Long.valueOf(rs.getLong(1)); - Long zoneId = Long.valueOf(rs.getLong(2)); - Long acctId = Long.valueOf(rs.getLong(3)); - Long dId = Long.valueOf(rs.getLong(4)); +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageStorageVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageStorageDao.class}) +public class UsageStorageDaoImpl extends GenericDaoBase implements UsageStorageDao { + public static final Logger s_logger = Logger.getLogger(UsageStorageDaoImpl.class.getName()); + + protected static final String REMOVE_BY_USERID_STORAGEID = "DELETE FROM usage_storage WHERE account_id = ? AND id = ? AND storage_type = ?"; + protected static final String UPDATE_DELETED = "UPDATE usage_storage SET deleted = ? WHERE account_id = ? AND id = ? AND storage_type = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " + + "FROM usage_storage " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " + + "FROM usage_storage " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " + + "FROM usage_storage " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + private final SearchBuilder IdSearch; + private final SearchBuilder IdZoneSearch; + + public UsageStorageDaoImpl() { + IdSearch = createSearchBuilder(); + IdSearch.and("accountId", IdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + IdSearch.and("id", IdSearch.entity().getId(), SearchCriteria.Op.EQ); + IdSearch.and("type", IdSearch.entity().getStorageType(), SearchCriteria.Op.EQ); + IdSearch.done(); + + IdZoneSearch = createSearchBuilder(); + IdZoneSearch.and("accountId", IdZoneSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + IdZoneSearch.and("id", IdZoneSearch.entity().getId(), SearchCriteria.Op.EQ); + IdZoneSearch.and("type", IdZoneSearch.entity().getStorageType(), SearchCriteria.Op.EQ); + IdZoneSearch.and("dcId", IdZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + IdZoneSearch.done(); + } + + @Override + public List listById(long accountId, long id, int type) { + SearchCriteria sc = IdSearch.create(); + sc.setParameters("accountId", accountId); + sc.setParameters("id", id); + sc.setParameters("type", type); + return listBy(sc, null); + } + + @Override + public List listByIdAndZone(long accountId, long id, int type, long dcId) { + SearchCriteria sc = IdZoneSearch.create(); + sc.setParameters("accountId", accountId); + sc.setParameters("id", id); + sc.setParameters("type", type); + sc.setParameters("dcId", dcId); + return listBy(sc, null); + } + + public void removeBy(long accountId, long volId, int storage_type) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = REMOVE_BY_USERID_STORAGEID; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + pstmt.setLong(2, volId); + pstmt.setInt(3, storage_type); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error removing usageStorageVO", e); + } finally { + txn.close(); + } + } + + public void update(UsageStorageVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getId()); + pstmt.setInt(4, usage.getStorageType()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsageStorageVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //id, zone_id, account_id, domain_id, storage_type, size, created, deleted + Long id = Long.valueOf(rs.getLong(1)); + Long zoneId = Long.valueOf(rs.getLong(2)); + Long acctId = Long.valueOf(rs.getLong(3)); + Long dId = Long.valueOf(rs.getLong(4)); Integer type = Integer.valueOf(rs.getInt(5)); - Long sourceId = Long.valueOf(rs.getLong(6)); - Long size = Long.valueOf(rs.getLong(7)); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(8); - String deletedTS = rs.getString(9); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsageStorageVO(id, zoneId, acctId, dId, type, sourceId, size, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} + Long sourceId = Long.valueOf(rs.getLong(6)); + Long size = Long.valueOf(rs.getLong(7)); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(8); + String deletedTS = rs.getString(9); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsageStorageVO(id, zoneId, acctId, dId, type, sourceId, size, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageVMInstanceDao.java b/server/src/com/cloud/usage/dao/UsageVMInstanceDao.java index 041f4091a94..aeb769744a0 100644 --- a/server/src/com/cloud/usage/dao/UsageVMInstanceDao.java +++ b/server/src/com/cloud/usage/dao/UsageVMInstanceDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageVMInstanceVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageVMInstanceDao extends GenericDao { - public void update(UsageVMInstanceVO instance); - public void delete(UsageVMInstanceVO instance); - public List getUsageRecords(long userId, Date startDate, Date endDate); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageVMInstanceVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageVMInstanceDao extends GenericDao { + public void update(UsageVMInstanceVO instance); + public void delete(UsageVMInstanceVO instance); + public List getUsageRecords(long userId, Date startDate, Date endDate); +} diff --git a/server/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java b/server/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java index d825d528011..46eb0df3cfc 100644 --- a/server/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java @@ -10,122 +10,122 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageVMInstanceVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageVMInstanceDao.class}) -public class UsageVMInstanceDaoImpl extends GenericDaoBase implements UsageVMInstanceDao { - public static final Logger s_logger = Logger.getLogger(UsageVMInstanceDaoImpl.class.getName()); - - protected static final String UPDATE_USAGE_INSTANCE_SQL = - "UPDATE usage_vm_instance SET end_date = ? " - + "WHERE account_id = ? and vm_instance_id = ? and usage_type = ? and end_date IS NULL"; - protected static final String DELETE_USAGE_INSTANCE_SQL = - "DELETE FROM usage_vm_instance WHERE account_id = ? and vm_instance_id = ? and usage_type = ?"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT usage_type, zone_id, account_id, vm_instance_id, vm_name, service_offering_id, template_id, hypervisor_type, start_date, end_date " + - "FROM usage_vm_instance " + - "WHERE account_id = ? AND ((end_date IS NULL) OR (start_date BETWEEN ? AND ?) OR " + - " (end_date BETWEEN ? AND ?) OR ((start_date <= ?) AND (end_date >= ?)))"; - - public UsageVMInstanceDaoImpl() {} - - public void update(UsageVMInstanceVO instance) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = UPDATE_USAGE_INSTANCE_SQL; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), instance.getEndDate())); - pstmt.setLong(2, instance.getAccountId()); - pstmt.setLong(3, instance.getVmInstanceId()); - pstmt.setInt(4, instance.getUsageType()); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - s_logger.warn(e); - } finally { - txn.close(); - } - } - - public void delete(UsageVMInstanceVO instance) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = DELETE_USAGE_INSTANCE_SQL; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, instance.getAccountId()); - pstmt.setLong(2, instance.getVmInstanceId()); - pstmt.setInt(3, instance.getUsageType()); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("error deleting usage vm instance with vmId: " + instance.getVmInstanceId() + ", for account with id: " + instance.getAccountId()); - } finally { - txn.close(); - } - } - - public List getUsageRecords(long accountId, Date startDate, Date endDate) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - List usageInstances = new ArrayList(); - try { - String sql = GET_USAGE_RECORDS_BY_ACCOUNT; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(4, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(5, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(6, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(7, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - int r_usageType = rs.getInt(1); - long r_zoneId = rs.getLong(2); - long r_accountId = rs.getLong(3); - long r_vmId = rs.getLong(4); - String r_vmName = rs.getString(5); - long r_soId = rs.getLong(6); - long r_tId = rs.getLong(7); - String hypervisorType = rs.getString(8); - String r_startDate = rs.getString(9); - String r_endDate = rs.getString(10); - Date instanceStartDate = null; - Date instanceEndDate = null; - if (r_startDate != null) { - instanceStartDate = DateUtil.parseDateString(s_gmtTimeZone, r_startDate); - } - if (r_endDate != null) { - instanceEndDate = DateUtil.parseDateString(s_gmtTimeZone, r_endDate); - } - UsageVMInstanceVO usageInstance = new UsageVMInstanceVO(r_usageType, r_zoneId, r_accountId, r_vmId, r_vmName, r_soId, r_tId, hypervisorType, instanceStartDate, instanceEndDate); - usageInstances.add(usageInstance); - } - } catch (Exception ex) { - s_logger.error("error retrieving usage vm instances for account id: " + accountId, ex); - } finally { - txn.close(); - } - return usageInstances; - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageVMInstanceVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageVMInstanceDao.class}) +public class UsageVMInstanceDaoImpl extends GenericDaoBase implements UsageVMInstanceDao { + public static final Logger s_logger = Logger.getLogger(UsageVMInstanceDaoImpl.class.getName()); + + protected static final String UPDATE_USAGE_INSTANCE_SQL = + "UPDATE usage_vm_instance SET end_date = ? " + + "WHERE account_id = ? and vm_instance_id = ? and usage_type = ? and end_date IS NULL"; + protected static final String DELETE_USAGE_INSTANCE_SQL = + "DELETE FROM usage_vm_instance WHERE account_id = ? and vm_instance_id = ? and usage_type = ?"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT usage_type, zone_id, account_id, vm_instance_id, vm_name, service_offering_id, template_id, hypervisor_type, start_date, end_date " + + "FROM usage_vm_instance " + + "WHERE account_id = ? AND ((end_date IS NULL) OR (start_date BETWEEN ? AND ?) OR " + + " (end_date BETWEEN ? AND ?) OR ((start_date <= ?) AND (end_date >= ?)))"; + + public UsageVMInstanceDaoImpl() {} + + public void update(UsageVMInstanceVO instance) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = UPDATE_USAGE_INSTANCE_SQL; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), instance.getEndDate())); + pstmt.setLong(2, instance.getAccountId()); + pstmt.setLong(3, instance.getVmInstanceId()); + pstmt.setInt(4, instance.getUsageType()); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + s_logger.warn(e); + } finally { + txn.close(); + } + } + + public void delete(UsageVMInstanceVO instance) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = DELETE_USAGE_INSTANCE_SQL; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, instance.getAccountId()); + pstmt.setLong(2, instance.getVmInstanceId()); + pstmt.setInt(3, instance.getUsageType()); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error deleting usage vm instance with vmId: " + instance.getVmInstanceId() + ", for account with id: " + instance.getAccountId()); + } finally { + txn.close(); + } + } + + public List getUsageRecords(long accountId, Date startDate, Date endDate) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + List usageInstances = new ArrayList(); + try { + String sql = GET_USAGE_RECORDS_BY_ACCOUNT; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(4, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(5, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(6, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(7, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + int r_usageType = rs.getInt(1); + long r_zoneId = rs.getLong(2); + long r_accountId = rs.getLong(3); + long r_vmId = rs.getLong(4); + String r_vmName = rs.getString(5); + long r_soId = rs.getLong(6); + long r_tId = rs.getLong(7); + String hypervisorType = rs.getString(8); + String r_startDate = rs.getString(9); + String r_endDate = rs.getString(10); + Date instanceStartDate = null; + Date instanceEndDate = null; + if (r_startDate != null) { + instanceStartDate = DateUtil.parseDateString(s_gmtTimeZone, r_startDate); + } + if (r_endDate != null) { + instanceEndDate = DateUtil.parseDateString(s_gmtTimeZone, r_endDate); + } + UsageVMInstanceVO usageInstance = new UsageVMInstanceVO(r_usageType, r_zoneId, r_accountId, r_vmId, r_vmName, r_soId, r_tId, hypervisorType, instanceStartDate, instanceEndDate); + usageInstances.add(usageInstance); + } + } catch (Exception ex) { + s_logger.error("error retrieving usage vm instances for account id: " + accountId, ex); + } finally { + txn.close(); + } + return usageInstances; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageVPNUserDao.java b/server/src/com/cloud/usage/dao/UsageVPNUserDao.java index 9d75e4a3788..139a5838806 100644 --- a/server/src/com/cloud/usage/dao/UsageVPNUserDao.java +++ b/server/src/com/cloud/usage/dao/UsageVPNUserDao.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageVPNUserVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageVPNUserDao extends GenericDao { - public void update(UsageVPNUserVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageVPNUserVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageVPNUserDao extends GenericDao { + public void update(UsageVPNUserVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); +} diff --git a/server/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java b/server/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java index 34e372db911..06797e72557 100644 --- a/server/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java @@ -10,135 +10,135 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageVPNUserVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageVPNUserDao.class}) -public class UsageVPNUserDaoImpl extends GenericDaoBase implements UsageVPNUserDao { - public static final Logger s_logger = Logger.getLogger(UsageVPNUserDaoImpl.class.getName()); - - protected static final String UPDATE_DELETED = "UPDATE usage_vpn_user SET deleted = ? WHERE account_id = ? AND user_id = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + - "FROM usage_vpn_user " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + - "FROM usage_vpn_user " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + - "FROM usage_vpn_user " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - public UsageVPNUserDaoImpl() {} - - public void update(UsageVPNUserVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageVPNUserVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageVPNUserDao.class}) +public class UsageVPNUserDaoImpl extends GenericDaoBase implements UsageVPNUserDao { + public static final Logger s_logger = Logger.getLogger(UsageVPNUserDaoImpl.class.getName()); + + protected static final String UPDATE_DELETED = "UPDATE usage_vpn_user SET deleted = ? WHERE account_id = ? AND user_id = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + + "FROM usage_vpn_user " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + + "FROM usage_vpn_user " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + + "FROM usage_vpn_user " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + public UsageVPNUserDaoImpl() {} + + public void update(UsageVPNUserVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getUserId()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsageVPNUserVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //zoneId, account_id, domain_id, user_id, user_name, created, deleted - Long zoneId = Long.valueOf(rs.getLong(1)); - Long acctId = Long.valueOf(rs.getLong(2)); - Long dId = Long.valueOf(rs.getLong(3)); - long userId = Long.valueOf(rs.getLong(4)); - String userName = rs.getString(5); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(6); - String deletedTS = rs.getString(7); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsageVPNUserVO(zoneId, acctId, dId, userId, userName, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getUserId()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsageVPNUserVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //zoneId, account_id, domain_id, user_id, user_name, created, deleted + Long zoneId = Long.valueOf(rs.getLong(1)); + Long acctId = Long.valueOf(rs.getLong(2)); + Long dId = Long.valueOf(rs.getLong(3)); + long userId = Long.valueOf(rs.getLong(4)); + String userName = rs.getString(5); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(6); + String deletedTS = rs.getString(7); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsageVPNUserVO(zoneId, acctId, dId, userId, userName, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/usage/dao/UsageVolumeDao.java b/server/src/com/cloud/usage/dao/UsageVolumeDao.java index 67e8d07ac90..30d7cc1151b 100644 --- a/server/src/com/cloud/usage/dao/UsageVolumeDao.java +++ b/server/src/com/cloud/usage/dao/UsageVolumeDao.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.util.Date; -import java.util.List; - -import com.cloud.usage.UsageVolumeVO; -import com.cloud.utils.db.GenericDao; - -public interface UsageVolumeDao extends GenericDao { - public void removeBy(long userId, long id); - public void update(UsageVolumeVO usage); - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); -} +package com.cloud.usage.dao; + +import java.util.Date; +import java.util.List; + +import com.cloud.usage.UsageVolumeVO; +import com.cloud.utils.db.GenericDao; + +public interface UsageVolumeDao extends GenericDao { + public void removeBy(long userId, long id); + public void update(UsageVolumeVO usage); + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page); +} diff --git a/server/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java b/server/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java index 2e73c319cdd..cec38fb31e8 100644 --- a/server/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java +++ b/server/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java @@ -10,163 +10,163 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.usage.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.usage.UsageVolumeVO; -import com.cloud.utils.DateUtil; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={UsageVolumeDao.class}) -public class UsageVolumeDaoImpl extends GenericDaoBase implements UsageVolumeDao { - public static final Logger s_logger = Logger.getLogger(UsageVolumeDaoImpl.class.getName()); - - protected static final String REMOVE_BY_USERID_VOLID = "DELETE FROM usage_volume WHERE account_id = ? AND id = ?"; - protected static final String UPDATE_DELETED = "UPDATE usage_volume SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL"; - protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " + - "FROM usage_volume " + - "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " + - "FROM usage_volume " + - "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; - protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " + - "FROM usage_volume " + - "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + - " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; - - public UsageVolumeDaoImpl() {} - - public void removeBy(long accountId, long volId) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - String sql = REMOVE_BY_USERID_VOLID; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, accountId); - pstmt.setLong(2, volId); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error removing usageVolumeVO", e); - } finally { - txn.close(); - } - } - - public void update(UsageVolumeVO usage) { - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - try { - txn.start(); - if (usage.getDeleted() != null) { - pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); - pstmt.setLong(2, usage.getAccountId()); - pstmt.setLong(3, usage.getId()); - } - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error updating UsageVolumeVO", e); - } finally { - txn.close(); - } - } - - @Override - public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { - List usageRecords = new ArrayList(); - - Long param1 = null; - String sql = null; - if (accountId != null) { - sql = GET_USAGE_RECORDS_BY_ACCOUNT; - param1 = accountId; - } else if (domainId != null) { - sql = GET_USAGE_RECORDS_BY_DOMAIN; - param1 = domainId; - } else { - sql = GET_ALL_USAGE_RECORDS; - } - - if (limit) { - int startIndex = 0; - if (page > 0) { - startIndex = 500 * (page-1); - } - sql += " LIMIT " + startIndex + ",500"; - } - - Transaction txn = Transaction.open(Transaction.USAGE_DB); - PreparedStatement pstmt = null; - - try { - int i = 1; - pstmt = txn.prepareAutoCloseStatement(sql); - if (param1 != null) { - pstmt.setLong(i++, param1); - } - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); - pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //id, zoneId, account_id, domain_id, disk_offering_id, template_id created, deleted - Long vId = Long.valueOf(rs.getLong(1)); - Long zoneId = Long.valueOf(rs.getLong(2)); - Long acctId = Long.valueOf(rs.getLong(3)); - Long dId = Long.valueOf(rs.getLong(4)); - Long doId = Long.valueOf(rs.getLong(5)); - if(doId == 0){ - doId = null; - } - Long tId = Long.valueOf(rs.getLong(6)); - if(tId == 0){ - tId = null; - } - long size = Long.valueOf(rs.getLong(7)); - Date createdDate = null; - Date deletedDate = null; - String createdTS = rs.getString(8); - String deletedTS = rs.getString(9); - - - if (createdTS != null) { - createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); - } - if (deletedTS != null) { - deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); - } - - usageRecords.add(new UsageVolumeVO(vId, zoneId, acctId, dId, doId, tId, size, createdDate, deletedDate)); - } - } catch (Exception e) { - txn.rollback(); - s_logger.warn("Error getting usage records", e); - } finally { - txn.close(); - } - - return usageRecords; - } -} +package com.cloud.usage.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.usage.UsageVolumeVO; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={UsageVolumeDao.class}) +public class UsageVolumeDaoImpl extends GenericDaoBase implements UsageVolumeDao { + public static final Logger s_logger = Logger.getLogger(UsageVolumeDaoImpl.class.getName()); + + protected static final String REMOVE_BY_USERID_VOLID = "DELETE FROM usage_volume WHERE account_id = ? AND id = ?"; + protected static final String UPDATE_DELETED = "UPDATE usage_volume SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL"; + protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " + + "FROM usage_volume " + + "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " + + "FROM usage_volume " + + "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))"; + protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " + + "FROM usage_volume " + + "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " + + " (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))"; + + public UsageVolumeDaoImpl() {} + + public void removeBy(long accountId, long volId) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + String sql = REMOVE_BY_USERID_VOLID; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, accountId); + pstmt.setLong(2, volId); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error removing usageVolumeVO", e); + } finally { + txn.close(); + } + } + + public void update(UsageVolumeVO usage) { + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + try { + txn.start(); + if (usage.getDeleted() != null) { + pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); + pstmt.setLong(2, usage.getAccountId()); + pstmt.setLong(3, usage.getId()); + } + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error updating UsageVolumeVO", e); + } finally { + txn.close(); + } + } + + @Override + public List getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) { + List usageRecords = new ArrayList(); + + Long param1 = null; + String sql = null; + if (accountId != null) { + sql = GET_USAGE_RECORDS_BY_ACCOUNT; + param1 = accountId; + } else if (domainId != null) { + sql = GET_USAGE_RECORDS_BY_DOMAIN; + param1 = domainId; + } else { + sql = GET_ALL_USAGE_RECORDS; + } + + if (limit) { + int startIndex = 0; + if (page > 0) { + startIndex = 500 * (page-1); + } + sql += " LIMIT " + startIndex + ",500"; + } + + Transaction txn = Transaction.open(Transaction.USAGE_DB); + PreparedStatement pstmt = null; + + try { + int i = 1; + pstmt = txn.prepareAutoCloseStatement(sql); + if (param1 != null) { + pstmt.setLong(i++, param1); + } + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate)); + pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate)); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + //id, zoneId, account_id, domain_id, disk_offering_id, template_id created, deleted + Long vId = Long.valueOf(rs.getLong(1)); + Long zoneId = Long.valueOf(rs.getLong(2)); + Long acctId = Long.valueOf(rs.getLong(3)); + Long dId = Long.valueOf(rs.getLong(4)); + Long doId = Long.valueOf(rs.getLong(5)); + if(doId == 0){ + doId = null; + } + Long tId = Long.valueOf(rs.getLong(6)); + if(tId == 0){ + tId = null; + } + long size = Long.valueOf(rs.getLong(7)); + Date createdDate = null; + Date deletedDate = null; + String createdTS = rs.getString(8); + String deletedTS = rs.getString(9); + + + if (createdTS != null) { + createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS); + } + if (deletedTS != null) { + deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS); + } + + usageRecords.add(new UsageVolumeVO(vId, zoneId, acctId, dId, doId, tId, size, createdDate, deletedDate)); + } + } catch (Exception e) { + txn.rollback(); + s_logger.warn("Error getting usage records", e); + } finally { + txn.close(); + } + + return usageRecords; + } +} diff --git a/server/src/com/cloud/user/AccountDetailVO.java b/server/src/com/cloud/user/AccountDetailVO.java index 2838902cfbd..afe50f8a9df 100755 --- a/server/src/com/cloud/user/AccountDetailVO.java +++ b/server/src/com/cloud/user/AccountDetailVO.java @@ -10,58 +10,58 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="account_details") -public class AccountDetailVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="account_id") - private long accountId; - - @Column(name="name") - private String name; - - @Column(name="value", encryptable=true) - private String value; - - protected AccountDetailVO() { - } - - public AccountDetailVO(long accountId, String name, String value) { - this.accountId = accountId; - this.name = name; - this.value = value; - } - - public long getAccountId() { - return accountId; - } - - public String getName() { - return name; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public long getId() { - return id; - } -} +package com.cloud.user; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="account_details") +public class AccountDetailVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="account_id") + private long accountId; + + @Column(name="name") + private String name; + + @Column(name="value", encryptable=true) + private String value; + + protected AccountDetailVO() { + } + + public AccountDetailVO(long accountId, String name, String value) { + this.accountId = accountId; + this.name = name; + this.value = value; + } + + public long getAccountId() { + return accountId; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public long getId() { + return id; + } +} diff --git a/server/src/com/cloud/user/AccountDetailsDao.java b/server/src/com/cloud/user/AccountDetailsDao.java index f1771cb6bcb..ebd4ffef0ae 100755 --- a/server/src/com/cloud/user/AccountDetailsDao.java +++ b/server/src/com/cloud/user/AccountDetailsDao.java @@ -10,24 +10,24 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - -import java.util.Map; -import com.cloud.utils.db.GenericDao; - - -public interface AccountDetailsDao extends GenericDao { - Map findDetails(long accountId); - - void persist(long accountId, Map details); - - AccountDetailVO findDetail(long accountId, String name); - - void deleteDetails(long accountId); - - /* - * For these existing entries, they will get updated. For these new entries, - * they will get created - */ - void update(long accountId, Map details); -} +package com.cloud.user; + +import java.util.Map; +import com.cloud.utils.db.GenericDao; + + +public interface AccountDetailsDao extends GenericDao { + Map findDetails(long accountId); + + void persist(long accountId, Map details); + + AccountDetailVO findDetail(long accountId, String name); + + void deleteDetails(long accountId); + + /* + * For these existing entries, they will get updated. For these new entries, + * they will get created + */ + void update(long accountId, Map details); +} diff --git a/server/src/com/cloud/user/AccountDetailsDaoImpl.java b/server/src/com/cloud/user/AccountDetailsDaoImpl.java index 12b48f2dfd2..25eec333be4 100755 --- a/server/src/com/cloud/user/AccountDetailsDaoImpl.java +++ b/server/src/com/cloud/user/AccountDetailsDaoImpl.java @@ -10,80 +10,80 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; - -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteriaService; - -@Local(value={AccountDetailsDao.class}) -public class AccountDetailsDaoImpl extends GenericDaoBase implements AccountDetailsDao { - protected final SearchBuilder accountSearch; - - protected AccountDetailsDaoImpl() { - accountSearch = createSearchBuilder(); - accountSearch.and("accountId", accountSearch.entity().getAccountId(), Op.EQ); - accountSearch.done(); - } - - @Override - public Map findDetails(long accountId) { - SearchCriteriaService sc = SearchCriteria2.create(AccountDetailVO.class); - sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); - List results = sc.list(); - Map details = new HashMap(results.size()); - for (AccountDetailVO r : results) { - details.put(r.getName(), r.getValue()); - } - return details; - } - - @Override - public void persist(long accountId, Map details) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - SearchCriteria sc = accountSearch.create(); - sc.setParameters("accountId", accountId); - expunge(sc); - for (Map.Entry detail : details.entrySet()) { - AccountDetailVO vo = new AccountDetailVO(accountId, detail.getKey(), detail.getValue()); - persist(vo); - } - txn.commit(); - } - - @Override - public AccountDetailVO findDetail(long accountId, String name) { - SearchCriteriaService sc = SearchCriteria2.create(AccountDetailVO.class); - sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); - sc.addAnd(sc.getEntity().getName(), Op.EQ, name); - return sc.find(); - } - - @Override - public void deleteDetails(long accountId) { - SearchCriteria sc = accountSearch.create(); - sc.setParameters("accountId", accountId); - List results = search(sc, null); - for (AccountDetailVO result : results) { - remove(result.getId()); - } - } - - @Override - public void update(long accountId, Map details) { - Map oldDetails = findDetails(accountId); - oldDetails.putAll(details); - persist(accountId, oldDetails); - } -} +package com.cloud.user; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteriaService; + +@Local(value={AccountDetailsDao.class}) +public class AccountDetailsDaoImpl extends GenericDaoBase implements AccountDetailsDao { + protected final SearchBuilder accountSearch; + + protected AccountDetailsDaoImpl() { + accountSearch = createSearchBuilder(); + accountSearch.and("accountId", accountSearch.entity().getAccountId(), Op.EQ); + accountSearch.done(); + } + + @Override + public Map findDetails(long accountId) { + SearchCriteriaService sc = SearchCriteria2.create(AccountDetailVO.class); + sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); + List results = sc.list(); + Map details = new HashMap(results.size()); + for (AccountDetailVO r : results) { + details.put(r.getName(), r.getValue()); + } + return details; + } + + @Override + public void persist(long accountId, Map details) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + SearchCriteria sc = accountSearch.create(); + sc.setParameters("accountId", accountId); + expunge(sc); + for (Map.Entry detail : details.entrySet()) { + AccountDetailVO vo = new AccountDetailVO(accountId, detail.getKey(), detail.getValue()); + persist(vo); + } + txn.commit(); + } + + @Override + public AccountDetailVO findDetail(long accountId, String name) { + SearchCriteriaService sc = SearchCriteria2.create(AccountDetailVO.class); + sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); + sc.addAnd(sc.getEntity().getName(), Op.EQ, name); + return sc.find(); + } + + @Override + public void deleteDetails(long accountId) { + SearchCriteria sc = accountSearch.create(); + sc.setParameters("accountId", accountId); + List results = search(sc, null); + for (AccountDetailVO result : results) { + remove(result.getId()); + } + } + + @Override + public void update(long accountId, Map details) { + Map oldDetails = findDetails(accountId); + oldDetails.putAll(details); + persist(accountId, oldDetails); + } +} diff --git a/server/src/com/cloud/user/dao/AccountDao.java b/server/src/com/cloud/user/dao/AccountDao.java index 3a2ba315883..05d53cc4a3d 100644 --- a/server/src/com/cloud/user/dao/AccountDao.java +++ b/server/src/com/cloud/user/dao/AccountDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import java.util.Date; import java.util.List; @@ -21,13 +21,13 @@ import com.cloud.user.User; import com.cloud.utils.Pair; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; - -public interface AccountDao extends GenericDao { - Pair findUserAccountByApiKey(String apiKey); - List findAccountsLike(String accountName); - List findActiveAccounts(Long maxAccountId, Filter filter); - List findRecentlyDeletedAccounts(Long maxAccountId, Date earliestRemovedDate, Filter filter); - List findNewAccounts(Long minAccountId, Filter filter); + +public interface AccountDao extends GenericDao { + Pair findUserAccountByApiKey(String apiKey); + List findAccountsLike(String accountName); + List findActiveAccounts(Long maxAccountId, Filter filter); + List findRecentlyDeletedAccounts(Long maxAccountId, Date earliestRemovedDate, Filter filter); + List findNewAccounts(Long minAccountId, Filter filter); List findCleanupsForRemovedAccounts(Long domainId); List findActiveAccountsForDomain(Long domain); void markForCleanup(long accountId); @@ -44,5 +44,5 @@ public interface AccountDao extends GenericDao { //returns only non-removed account Account findActiveAccount(String accountName, Long domainId); - Account findActiveNonProjectAccount(String accountName, Long domainId); -} + Account findActiveNonProjectAccount(String accountName, Long domainId); +} diff --git a/server/src/com/cloud/user/dao/AccountDaoImpl.java b/server/src/com/cloud/user/dao/AccountDaoImpl.java index 688d3bdaad7..c820e2204a4 100755 --- a/server/src/com/cloud/user/dao/AccountDaoImpl.java +++ b/server/src/com/cloud/user/dao/AccountDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; @@ -33,44 +33,44 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value={AccountDao.class}) -public class AccountDaoImpl extends GenericDaoBase implements AccountDao { + +@Local(value={AccountDao.class}) +public class AccountDaoImpl extends GenericDaoBase implements AccountDao { private static final Logger s_logger = Logger.getLogger(AccountDaoImpl.class); - private final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, " + - "a.id, a.account_name, a.type, a.domain_id, a.state " + - "FROM `cloud`.`user` u, `cloud`.`account` a " + - "WHERE u.account_id = a.id AND u.api_key = ? and u.removed IS NULL"; - - protected final SearchBuilder AllFieldsSearch; - protected final SearchBuilder AccountTypeSearch; - protected final SearchBuilder DomainAccountsSearch; + private final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, " + + "a.id, a.account_name, a.type, a.domain_id, a.state " + + "FROM `cloud`.`user` u, `cloud`.`account` a " + + "WHERE u.account_id = a.id AND u.api_key = ? and u.removed IS NULL"; + + protected final SearchBuilder AllFieldsSearch; + protected final SearchBuilder AccountTypeSearch; + protected final SearchBuilder DomainAccountsSearch; protected final SearchBuilder CleanupForRemovedAccountsSearch; protected final SearchBuilder CleanupForDisabledAccountsSearch; - protected final SearchBuilder NonProjectAccountSearch; - - protected AccountDaoImpl() { - AllFieldsSearch = createSearchBuilder(); + protected final SearchBuilder NonProjectAccountSearch; + + protected AccountDaoImpl() { + AllFieldsSearch = createSearchBuilder(); AllFieldsSearch.and("accountName", AllFieldsSearch.entity().getAccountName(), SearchCriteria.Op.EQ); AllFieldsSearch.and("domainId", AllFieldsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), SearchCriteria.Op.EQ); AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), SearchCriteria.Op.EQ); - AllFieldsSearch.done(); - - AccountTypeSearch = createSearchBuilder(); - AccountTypeSearch.and("domainId", AccountTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); - AccountTypeSearch.and("type", AccountTypeSearch.entity().getType(), SearchCriteria.Op.EQ); - AccountTypeSearch.done(); + AllFieldsSearch.done(); + + AccountTypeSearch = createSearchBuilder(); + AccountTypeSearch.and("domainId", AccountTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + AccountTypeSearch.and("type", AccountTypeSearch.entity().getType(), SearchCriteria.Op.EQ); + AccountTypeSearch.done(); DomainAccountsSearch = createSearchBuilder(); DomainAccountsSearch.and("domainId", DomainAccountsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); DomainAccountsSearch.and("removed", DomainAccountsSearch.entity().getRemoved(), SearchCriteria.Op.NULL); DomainAccountsSearch.done(); - - CleanupForRemovedAccountsSearch = createSearchBuilder(); - CleanupForRemovedAccountsSearch.and("cleanup", CleanupForRemovedAccountsSearch.entity().getNeedsCleanup(), SearchCriteria.Op.EQ); + + CleanupForRemovedAccountsSearch = createSearchBuilder(); + CleanupForRemovedAccountsSearch.and("cleanup", CleanupForRemovedAccountsSearch.entity().getNeedsCleanup(), SearchCriteria.Op.EQ); CleanupForRemovedAccountsSearch.and("removed", CleanupForRemovedAccountsSearch.entity().getRemoved(), SearchCriteria.Op.NNULL); - CleanupForRemovedAccountsSearch.and("domainid", CleanupForRemovedAccountsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + CleanupForRemovedAccountsSearch.and("domainid", CleanupForRemovedAccountsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); CleanupForRemovedAccountsSearch.done(); CleanupForDisabledAccountsSearch = createSearchBuilder(); @@ -84,19 +84,19 @@ public class AccountDaoImpl extends GenericDaoBase implements A NonProjectAccountSearch.and("domainId", NonProjectAccountSearch.entity().getDomainId(), SearchCriteria.Op.EQ); NonProjectAccountSearch.and("state", NonProjectAccountSearch.entity().getState(), SearchCriteria.Op.EQ); NonProjectAccountSearch.and("type", NonProjectAccountSearch.entity().getType(), SearchCriteria.Op.NEQ); - NonProjectAccountSearch.done(); - } - - @Override - public List findCleanupsForRemovedAccounts(Long domainId) { - SearchCriteria sc = CleanupForRemovedAccountsSearch.create(); + NonProjectAccountSearch.done(); + } + + @Override + public List findCleanupsForRemovedAccounts(Long domainId) { + SearchCriteria sc = CleanupForRemovedAccountsSearch.create(); sc.setParameters("cleanup", true); if (domainId != null) { sc.setParameters("domainid", domainId); - } - - return searchIncludingRemoved(sc, null, null, false); + } + + return searchIncludingRemoved(sc, null, null, false); } @Override @@ -106,53 +106,53 @@ public class AccountDaoImpl extends GenericDaoBase implements A sc.setParameters("state", State.disabled); return listBy(sc); - } - + } + @Override - public Pair findUserAccountByApiKey(String apiKey) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - Pair userAcctPair = null; - try { - String sql = FIND_USER_ACCOUNT_BY_API_KEY; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setString(1, apiKey); - ResultSet rs = pstmt.executeQuery(); - // TODO: make sure we don't have more than 1 result? ApiKey had better be unique - if (rs.next()) { - User u = new UserVO(rs.getLong(1)); - u.setUsername(rs.getString(2)); - u.setAccountId(rs.getLong(3)); + public Pair findUserAccountByApiKey(String apiKey) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + Pair userAcctPair = null; + try { + String sql = FIND_USER_ACCOUNT_BY_API_KEY; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setString(1, apiKey); + ResultSet rs = pstmt.executeQuery(); + // TODO: make sure we don't have more than 1 result? ApiKey had better be unique + if (rs.next()) { + User u = new UserVO(rs.getLong(1)); + u.setUsername(rs.getString(2)); + u.setAccountId(rs.getLong(3)); u.setSecretKey(DBEncryptionUtil.decrypt(rs.getString(4))); - u.setState(State.valueOf(rs.getString(5))); - - AccountVO a = new AccountVO(rs.getLong(6)); - a.setAccountName(rs.getString(7)); - a.setType(rs.getShort(8)); + u.setState(State.valueOf(rs.getString(5))); + + AccountVO a = new AccountVO(rs.getLong(6)); + a.setAccountName(rs.getString(7)); + a.setType(rs.getShort(8)); a.setDomainId(rs.getLong(9)); - a.setState(State.valueOf(rs.getString(10))); - - userAcctPair = new Pair(u, a); - } - } catch (Exception e) { - s_logger.warn("Exception finding user/acct by api key: " + apiKey, e); - } - return userAcctPair; - } - - @Override - public List findAccountsLike(String accountName) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("accountName", SearchCriteria.Op.LIKE, "%"+accountName+"%"); - return listBy(sc); - } - - @Override - public Account findEnabledAccount(String accountName, Long domainId) { - SearchCriteria sc = AllFieldsSearch.create("accountName", accountName); + a.setState(State.valueOf(rs.getString(10))); + + userAcctPair = new Pair(u, a); + } + } catch (Exception e) { + s_logger.warn("Exception finding user/acct by api key: " + apiKey, e); + } + return userAcctPair; + } + + @Override + public List findAccountsLike(String accountName) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("accountName", SearchCriteria.Op.LIKE, "%"+accountName+"%"); + return listBy(sc); + } + + @Override + public Account findEnabledAccount(String accountName, Long domainId) { + SearchCriteria sc = AllFieldsSearch.create("accountName", accountName); sc.setParameters("domainId",domainId); - sc.setParameters("state", State.enabled); - return findOneBy(sc); + sc.setParameters("state", State.enabled); + return findOneBy(sc); } @Override @@ -162,7 +162,7 @@ public class AccountDaoImpl extends GenericDaoBase implements A sc.setParameters("state", State.enabled); sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT); return findOneBy(sc); - } + } @Override public Account findActiveAccount(String accountName, Long domainId) { @@ -178,12 +178,12 @@ public class AccountDaoImpl extends GenericDaoBase implements A sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT); return findOneBy(sc); } - - @Override - public Account findAccountIncludingRemoved(String accountName, Long domainId) { - SearchCriteria sc = AllFieldsSearch.create("accountName", accountName); - sc.setParameters("domainId", domainId); - return findOneIncludingRemovedBy(sc); + + @Override + public Account findAccountIncludingRemoved(String accountName, Long domainId) { + SearchCriteria sc = AllFieldsSearch.create("accountName", accountName); + sc.setParameters("domainId", domainId); + return findOneIncludingRemovedBy(sc); } @Override @@ -199,45 +199,45 @@ public class AccountDaoImpl extends GenericDaoBase implements A SearchCriteria sc = AllFieldsSearch.create("accountName", accountName); sc.setParameters("domainId", domainId); return listIncludingRemovedBy(sc, filter); - } - + } + @Override - public List findActiveAccounts(Long maxAccountId, Filter filter) { + public List findActiveAccounts(Long maxAccountId, Filter filter) { if (maxAccountId == null) { return null; - } - - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("id", SearchCriteria.Op.LTEQ, maxAccountId); - - return listBy(sc, filter); - } - + } + + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("id", SearchCriteria.Op.LTEQ, maxAccountId); + + return listBy(sc, filter); + } + @Override - public List findRecentlyDeletedAccounts(Long maxAccountId, Date earliestRemovedDate, Filter filter) { + public List findRecentlyDeletedAccounts(Long maxAccountId, Date earliestRemovedDate, Filter filter) { if (earliestRemovedDate == null) { return null; - } - SearchCriteria sc = createSearchCriteria(); - if (maxAccountId != null) { - sc.addAnd("id", SearchCriteria.Op.LTEQ, maxAccountId); - } - sc.addAnd("removed", SearchCriteria.Op.NNULL); - sc.addAnd("removed", SearchCriteria.Op.GTEQ, earliestRemovedDate); - - return listIncludingRemovedBy(sc, filter); - } - + } + SearchCriteria sc = createSearchCriteria(); + if (maxAccountId != null) { + sc.addAnd("id", SearchCriteria.Op.LTEQ, maxAccountId); + } + sc.addAnd("removed", SearchCriteria.Op.NNULL); + sc.addAnd("removed", SearchCriteria.Op.GTEQ, earliestRemovedDate); + + return listIncludingRemovedBy(sc, filter); + } + @Override - public List findNewAccounts(Long minAccountId, Filter filter) { + public List findNewAccounts(Long minAccountId, Filter filter) { if (minAccountId == null) { return null; - } - - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("id", SearchCriteria.Op.GT, minAccountId); - - return listIncludingRemovedBy(sc, filter); + } + + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("id", SearchCriteria.Op.GT, minAccountId); + + return listIncludingRemovedBy(sc, filter); } @Override @@ -256,5 +256,5 @@ public class AccountDaoImpl extends GenericDaoBase implements A s_logger.warn("Failed to mark account id=" + accountId + " for cleanup"); } } - } -} + } +} diff --git a/server/src/com/cloud/user/dao/UserAccountDao.java b/server/src/com/cloud/user/dao/UserAccountDao.java index b60b906d88a..8eb8eef3695 100644 --- a/server/src/com/cloud/user/dao/UserAccountDao.java +++ b/server/src/com/cloud/user/dao/UserAccountDao.java @@ -10,13 +10,13 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import com.cloud.user.UserAccount; import com.cloud.user.UserAccountVO; import com.cloud.utils.db.GenericDao; - -public interface UserAccountDao extends GenericDao { - UserAccount getUserAccount(String username, Long domainId); - boolean validateUsernameInDomain(String username, Long domainId); -} + +public interface UserAccountDao extends GenericDao { + UserAccount getUserAccount(String username, Long domainId); + boolean validateUsernameInDomain(String username, Long domainId); +} diff --git a/server/src/com/cloud/user/dao/UserAccountDaoImpl.java b/server/src/com/cloud/user/dao/UserAccountDaoImpl.java index e90a521306e..396ac2bc473 100644 --- a/server/src/com/cloud/user/dao/UserAccountDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserAccountDaoImpl.java @@ -10,35 +10,35 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import javax.ejb.Local; import com.cloud.user.UserAccount; import com.cloud.user.UserAccountVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria; - -@Local(value={UserAccountDao.class}) -public class UserAccountDaoImpl extends GenericDaoBase implements UserAccountDao { - @Override - public UserAccount getUserAccount(String username, Long domainId) { - if ((username == null) || (domainId == null)) { - return null; - } - - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("username", SearchCriteria.Op.EQ, username); - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); - return findOneBy(sc); - } - - @Override - public boolean validateUsernameInDomain(String username, Long domainId) { - UserAccount userAcct = getUserAccount(username, domainId); - if (userAcct == null) { - return true; - } - return false; - } -} + +@Local(value={UserAccountDao.class}) +public class UserAccountDaoImpl extends GenericDaoBase implements UserAccountDao { + @Override + public UserAccount getUserAccount(String username, Long domainId) { + if ((username == null) || (domainId == null)) { + return null; + } + + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("username", SearchCriteria.Op.EQ, username); + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); + return findOneBy(sc); + } + + @Override + public boolean validateUsernameInDomain(String username, Long domainId) { + UserAccount userAcct = getUserAccount(username, domainId); + if (userAcct == null) { + return true; + } + return false; + } +} diff --git a/server/src/com/cloud/user/dao/UserDao.java b/server/src/com/cloud/user/dao/UserDao.java index 3e4903a8273..772be86ceaf 100644 --- a/server/src/com/cloud/user/dao/UserDao.java +++ b/server/src/com/cloud/user/dao/UserDao.java @@ -10,30 +10,30 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import java.util.List; import com.cloud.user.UserVO; import com.cloud.utils.db.GenericDao; - - -/* - * Data Access Object for user table - */ -public interface UserDao extends GenericDao{ - UserVO getUser(String username, String password); - UserVO getUser(String username); - UserVO getUser(long userId); - List findUsersLike(String username); - - List listByAccount(long accountId); - - /** - * Finds a user based on the secret key provided. - * @param secretKey - * @return - */ + + +/* + * Data Access Object for user table + */ +public interface UserDao extends GenericDao{ + UserVO getUser(String username, String password); + UserVO getUser(String username); + UserVO getUser(long userId); + List findUsersLike(String username); + + List listByAccount(long accountId); + + /** + * Finds a user based on the secret key provided. + * @param secretKey + * @return + */ UserVO findUserBySecretKey(String secretKey); /** @@ -44,5 +44,5 @@ public interface UserDao extends GenericDao{ UserVO findUserByRegistrationToken(String registrationToken); List findUsersByName(String username); - -} + +} diff --git a/server/src/com/cloud/user/dao/UserDaoImpl.java b/server/src/com/cloud/user/dao/UserDaoImpl.java index 4539cb46e4b..2c244618767 100644 --- a/server/src/com/cloud/user/dao/UserDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import java.util.List; import javax.ejb.Local; @@ -20,94 +20,94 @@ import com.cloud.user.UserVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -/** - * - * @author Will Chan - * - */ -@Local(value={UserDao.class}) -public class UserDaoImpl extends GenericDaoBase implements UserDao { - protected SearchBuilder UsernamePasswordSearch; - protected SearchBuilder UsernameSearch; - protected SearchBuilder UsernameLikeSearch; - protected SearchBuilder UserIdSearch; - protected SearchBuilder AccountIdSearch; + +/** + * + * @author Will Chan + * + */ +@Local(value={UserDao.class}) +public class UserDaoImpl extends GenericDaoBase implements UserDao { + protected SearchBuilder UsernamePasswordSearch; + protected SearchBuilder UsernameSearch; + protected SearchBuilder UsernameLikeSearch; + protected SearchBuilder UserIdSearch; + protected SearchBuilder AccountIdSearch; protected SearchBuilder SecretKeySearch; - protected SearchBuilder RegistrationTokenSearch; - - protected UserDaoImpl () { - UsernameSearch = createSearchBuilder(); - UsernameSearch.and("username", UsernameSearch.entity().getUsername(), SearchCriteria.Op.EQ); - UsernameSearch.done(); - - UsernameLikeSearch = createSearchBuilder(); - UsernameLikeSearch.and("username", UsernameLikeSearch.entity().getUsername(), SearchCriteria.Op.LIKE); - UsernameLikeSearch.done(); - - AccountIdSearch = createSearchBuilder(); - AccountIdSearch.and("account", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountIdSearch.done(); - - UsernamePasswordSearch = createSearchBuilder(); - UsernamePasswordSearch.and("username", UsernamePasswordSearch.entity().getUsername(), SearchCriteria.Op.EQ); - UsernamePasswordSearch.and("password", UsernamePasswordSearch.entity().getPassword(), SearchCriteria.Op.EQ); - UsernamePasswordSearch.done(); - - UserIdSearch = createSearchBuilder(); - UserIdSearch.and("id", UserIdSearch.entity().getId(), SearchCriteria.Op.EQ); - UserIdSearch.done(); - - SecretKeySearch = createSearchBuilder(); - SecretKeySearch.and("secretKey", SecretKeySearch.entity().getSecretKey(), SearchCriteria.Op.EQ); + protected SearchBuilder RegistrationTokenSearch; + + protected UserDaoImpl () { + UsernameSearch = createSearchBuilder(); + UsernameSearch.and("username", UsernameSearch.entity().getUsername(), SearchCriteria.Op.EQ); + UsernameSearch.done(); + + UsernameLikeSearch = createSearchBuilder(); + UsernameLikeSearch.and("username", UsernameLikeSearch.entity().getUsername(), SearchCriteria.Op.LIKE); + UsernameLikeSearch.done(); + + AccountIdSearch = createSearchBuilder(); + AccountIdSearch.and("account", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountIdSearch.done(); + + UsernamePasswordSearch = createSearchBuilder(); + UsernamePasswordSearch.and("username", UsernamePasswordSearch.entity().getUsername(), SearchCriteria.Op.EQ); + UsernamePasswordSearch.and("password", UsernamePasswordSearch.entity().getPassword(), SearchCriteria.Op.EQ); + UsernamePasswordSearch.done(); + + UserIdSearch = createSearchBuilder(); + UserIdSearch.and("id", UserIdSearch.entity().getId(), SearchCriteria.Op.EQ); + UserIdSearch.done(); + + SecretKeySearch = createSearchBuilder(); + SecretKeySearch.and("secretKey", SecretKeySearch.entity().getSecretKey(), SearchCriteria.Op.EQ); SecretKeySearch.done(); RegistrationTokenSearch = createSearchBuilder(); RegistrationTokenSearch.and("registrationToken", RegistrationTokenSearch.entity().getRegistrationToken(), SearchCriteria.Op.EQ); - RegistrationTokenSearch.done(); - } - - @Override - public UserVO getUser(String username, String password) { - SearchCriteria sc = UsernamePasswordSearch.create(); - sc.setParameters("username", username); - sc.setParameters("password", password); - return findOneBy(sc); - } - + RegistrationTokenSearch.done(); + } + @Override - public List listByAccount(long accountId) { - SearchCriteria sc = AccountIdSearch.create(); - sc.setParameters("account", accountId); - return listBy(sc, null); - } - - @Override - public UserVO getUser(String username) { - SearchCriteria sc = UsernameSearch.create(); - sc.setParameters("username", username); - return findOneBy(sc); - } - - @Override - public UserVO getUser(long userId) { - SearchCriteria sc = UserIdSearch.create(); - sc.setParameters("id", userId); - return findOneBy(sc); - } - - @Override - public List findUsersLike(String username) { - SearchCriteria sc = UsernameLikeSearch.create(); - sc.setParameters("username", "%" + username + "%"); - return listBy(sc); - } - - @Override - public UserVO findUserBySecretKey(String secretKey) { - SearchCriteria sc = SecretKeySearch.create(); - sc.setParameters("secretKey", secretKey); - return findOneBy(sc); + public UserVO getUser(String username, String password) { + SearchCriteria sc = UsernamePasswordSearch.create(); + sc.setParameters("username", username); + sc.setParameters("password", password); + return findOneBy(sc); + } + + @Override + public List listByAccount(long accountId) { + SearchCriteria sc = AccountIdSearch.create(); + sc.setParameters("account", accountId); + return listBy(sc, null); + } + + @Override + public UserVO getUser(String username) { + SearchCriteria sc = UsernameSearch.create(); + sc.setParameters("username", username); + return findOneBy(sc); + } + + @Override + public UserVO getUser(long userId) { + SearchCriteria sc = UserIdSearch.create(); + sc.setParameters("id", userId); + return findOneBy(sc); + } + + @Override + public List findUsersLike(String username) { + SearchCriteria sc = UsernameLikeSearch.create(); + sc.setParameters("username", "%" + username + "%"); + return listBy(sc); + } + + @Override + public UserVO findUserBySecretKey(String secretKey) { + SearchCriteria sc = SecretKeySearch.create(); + sc.setParameters("secretKey", secretKey); + return findOneBy(sc); } @Override @@ -122,5 +122,5 @@ public class UserDaoImpl extends GenericDaoBase implements UserDao SearchCriteria sc = UsernameSearch.create(); sc.setParameters("username", username); return listBy(sc); - } -} + } +} diff --git a/server/src/com/cloud/user/dao/UserStatisticsDao.java b/server/src/com/cloud/user/dao/UserStatisticsDao.java index 0bff8bab983..be538f33dc1 100644 --- a/server/src/com/cloud/user/dao/UserStatisticsDao.java +++ b/server/src/com/cloud/user/dao/UserStatisticsDao.java @@ -10,22 +10,22 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - -import java.util.Date; -import java.util.List; - +package com.cloud.user.dao; + +import java.util.Date; +import java.util.List; + import com.cloud.user.UserStatisticsVO; import com.cloud.utils.db.GenericDao; - -public interface UserStatisticsDao extends GenericDao { - UserStatisticsVO findBy(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType); - - UserStatisticsVO lock(long accountId, long dcId, long networkId, String publicIp, Long hostId, String deviceType); - - List listBy(long accountId); - + +public interface UserStatisticsDao extends GenericDao { + UserStatisticsVO findBy(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType); + + UserStatisticsVO lock(long accountId, long dcId, long networkId, String publicIp, Long hostId, String deviceType); + + List listBy(long accountId); + List listActiveAndRecentlyDeleted(Date minRemovedDate, int startIndex, int limit); - List listUpdatedStats(); -} + List listUpdatedStats(); +} diff --git a/server/src/com/cloud/user/dao/UserStatisticsDaoImpl.java b/server/src/com/cloud/user/dao/UserStatisticsDaoImpl.java index 917c351e276..8acc555fd99 100644 --- a/server/src/com/cloud/user/dao/UserStatisticsDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserStatisticsDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; @@ -29,85 +29,85 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; - -@Local(value={UserStatisticsDao.class}) -public class UserStatisticsDaoImpl extends GenericDaoBase implements UserStatisticsDao { + +@Local(value={UserStatisticsDao.class}) +public class UserStatisticsDaoImpl extends GenericDaoBase implements UserStatisticsDao { private static final Logger s_logger = Logger.getLogger(UserStatisticsDaoImpl.class); - private static final String ACTIVE_AND_RECENTLY_DELETED_SEARCH = "SELECT us.id, us.data_center_id, us.account_id, us.public_ip_address, us.device_id, us.device_type, us.network_id, us.agg_bytes_received, us.agg_bytes_sent " + - "FROM user_statistics us, account a " + - "WHERE us.account_id = a.id AND (a.removed IS NULL OR a.removed >= ?) " + + private static final String ACTIVE_AND_RECENTLY_DELETED_SEARCH = "SELECT us.id, us.data_center_id, us.account_id, us.public_ip_address, us.device_id, us.device_type, us.network_id, us.agg_bytes_received, us.agg_bytes_sent " + + "FROM user_statistics us, account a " + + "WHERE us.account_id = a.id AND (a.removed IS NULL OR a.removed >= ?) " + "ORDER BY us.id"; private static final String UPDATED_STATS_SEARCH = "SELECT id, current_bytes_received, current_bytes_sent, net_bytes_received, net_bytes_sent, agg_bytes_received, agg_bytes_sent from user_statistics " + - "where (agg_bytes_received < net_bytes_received + current_bytes_received) OR (agg_bytes_sent < net_bytes_sent + current_bytes_sent)"; - private final SearchBuilder AllFieldsSearch; + "where (agg_bytes_received < net_bytes_received + current_bytes_received) OR (agg_bytes_sent < net_bytes_sent + current_bytes_sent)"; + private final SearchBuilder AllFieldsSearch; private final SearchBuilder AccountSearch; - - - public UserStatisticsDaoImpl() { - AccountSearch = createSearchBuilder(); - AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountSearch.done(); - - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + + + public UserStatisticsDaoImpl() { + AccountSearch = createSearchBuilder(); + AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountSearch.done(); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("dc", AllFieldsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("network", AllFieldsSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("ip", AllFieldsSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); AllFieldsSearch.and("device", AllFieldsSearch.entity().getDeviceId(), SearchCriteria.Op.EQ); - AllFieldsSearch.and("deviceType", AllFieldsSearch.entity().getDeviceType(), SearchCriteria.Op.EQ); - AllFieldsSearch.done(); - } - - @Override - public UserStatisticsVO findBy(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("account", accountId); + AllFieldsSearch.and("deviceType", AllFieldsSearch.entity().getDeviceType(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public UserStatisticsVO findBy(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("account", accountId); sc.setParameters("dc", dcId); sc.setParameters("network", networkId); sc.setParameters("ip", publicIp); sc.setParameters("device", deviceId); - sc.setParameters("deviceType", deviceType); - return findOneBy(sc); - } - - @Override - public UserStatisticsVO lock(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("account", accountId); + sc.setParameters("deviceType", deviceType); + return findOneBy(sc); + } + + @Override + public UserStatisticsVO lock(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("account", accountId); sc.setParameters("dc", dcId); sc.setParameters("network", networkId); sc.setParameters("ip", publicIp); sc.setParameters("device", deviceId); - sc.setParameters("deviceType", deviceType); - return lockOneRandomRow(sc, true); - } - - @Override - public List listBy(long accountId) { - SearchCriteria sc = AccountSearch.create(); - sc.setParameters("account", accountId); - return search(sc, null); - } - - @Override - public List listActiveAndRecentlyDeleted(Date minRemovedDate, int startIndex, int limit) { - List userStats = new ArrayList(); - if (minRemovedDate == null) return userStats; - - Transaction txn = Transaction.currentTxn(); - try { - String sql = ACTIVE_AND_RECENTLY_DELETED_SEARCH + " LIMIT " + startIndex + "," + limit; - PreparedStatement pstmt = null; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), minRemovedDate)); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - userStats.add(toEntityBean(rs, false)); - } - } catch (Exception ex) { - s_logger.error("error saving user stats to cloud_usage db", ex); - } - return userStats; + sc.setParameters("deviceType", deviceType); + return lockOneRandomRow(sc, true); + } + + @Override + public List listBy(long accountId) { + SearchCriteria sc = AccountSearch.create(); + sc.setParameters("account", accountId); + return search(sc, null); + } + + @Override + public List listActiveAndRecentlyDeleted(Date minRemovedDate, int startIndex, int limit) { + List userStats = new ArrayList(); + if (minRemovedDate == null) return userStats; + + Transaction txn = Transaction.currentTxn(); + try { + String sql = ACTIVE_AND_RECENTLY_DELETED_SEARCH + " LIMIT " + startIndex + "," + limit; + PreparedStatement pstmt = null; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), minRemovedDate)); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + userStats.add(toEntityBean(rs, false)); + } + } catch (Exception ex) { + s_logger.error("error saving user stats to cloud_usage db", ex); + } + return userStats; } @Override @@ -128,4 +128,4 @@ public class UserStatisticsDaoImpl extends GenericDaoBase { -} + +public interface UserStatsLogDao extends GenericDao { +} diff --git a/server/src/com/cloud/user/dao/UserStatsLogDaoImpl.java b/server/src/com/cloud/user/dao/UserStatsLogDaoImpl.java index 447a0602f18..bb42dddc7b9 100644 --- a/server/src/com/cloud/user/dao/UserStatsLogDaoImpl.java +++ b/server/src/com/cloud/user/dao/UserStatsLogDaoImpl.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user.dao; - +package com.cloud.user.dao; + import javax.ejb.Local; import com.cloud.user.UserStatsLogVO; import com.cloud.utils.db.GenericDaoBase; -@Local(value={UserStatsLogDao.class}) +@Local(value={UserStatsLogDao.class}) public class UserStatsLogDaoImpl extends GenericDaoBase implements UserStatsLogDao { public UserStatsLogDaoImpl(){ - } -} + } +} diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDao.java b/server/src/com/cloud/uuididentity/dao/IdentityDao.java index 3d1b7da341f..f5acf71f90e 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDao.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDao.java @@ -10,14 +10,14 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.uuididentity.dao; - -import com.cloud.api.IdentityMapper; -import com.cloud.utils.db.GenericDao; - -public interface IdentityDao extends GenericDao { - Long getIdentityId(IdentityMapper mapper, String identityString); - Long getIdentityId(String tableName, String identityString); - String getIdentityUuid(String tableName, String identityString); - void initializeDefaultUuid(String tableName); -} +package com.cloud.uuididentity.dao; + +import com.cloud.api.IdentityMapper; +import com.cloud.utils.db.GenericDao; + +public interface IdentityDao extends GenericDao { + Long getIdentityId(IdentityMapper mapper, String identityString); + Long getIdentityId(String tableName, String identityString); + String getIdentityUuid(String tableName, String identityString); + void initializeDefaultUuid(String tableName); +} diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java index e0c0ccc4da5..abe20118b18 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java @@ -10,183 +10,183 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.uuididentity.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.api.IdentityMapper; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.Transaction; - -@Local(value={IdentityDao.class}) -public class IdentityDaoImpl extends GenericDaoBase implements IdentityDao { - private static final Logger s_logger = Logger.getLogger(IdentityDaoImpl.class); - - public IdentityDaoImpl() { - } - - @DB - public Long getIdentityId(IdentityMapper mapper, String identityString) { - assert(mapper.entityTableName() != null); - return getIdentityId(mapper.entityTableName(), identityString); - } - - @DB - public Long getIdentityId(String tableName, String identityString) { - assert(tableName != null); - assert(identityString != null); - - PreparedStatement pstmt = null; - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - try { - pstmt = txn.prepareAutoCloseStatement( - String.format("SELECT id FROM `%s` WHERE id=? OR uuid=?", tableName) - - // TODO : after graceful period, use following line turn on more secure check - // String.format("SELECT id FROM %s WHERE (id=? AND uuid IS NULL) OR uuid=?", mapper.entityTableName()) - ); - - long id = 0; - try { - // TODO : use regular expression to determine - id = Long.parseLong(identityString); - } catch(NumberFormatException e) { - // this could happen when it is a uuid string, so catch and ignore it - } - - pstmt.setLong(1, id); - pstmt.setString(2, identityString); - - ResultSet rs = pstmt.executeQuery(); - if(rs.next()) { - return rs.getLong(1); - } else { - if(id == -1L) - return id; - - throw new InvalidParameterValueException("Object " + tableName + "(uuid: " + identityString + ") does not exist."); - } - } catch (SQLException e) { - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - return null; - } - - @DB - public String getIdentityUuid(String tableName, String identityString) { - assert(tableName != null); - assert(identityString != null); - - PreparedStatement pstmt = null; - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - try { - pstmt = txn.prepareAutoCloseStatement( - String.format("SELECT uuid FROM `%s` WHERE id=? OR uuid=?", tableName) - // String.format("SELECT uuid FROM %s WHERE (id=? AND uuid IS NULL) OR uuid=?", tableName) - ); - - long id = 0; - try { - // TODO : use regular expression to determine - id = Long.parseLong(identityString); - } catch(NumberFormatException e) { - // this could happen when it is a uuid string, so catch and ignore it - } - - pstmt.setLong(1, id); - pstmt.setString(2, identityString); - - ResultSet rs = pstmt.executeQuery(); - if(rs.next()) { - String uuid = rs.getString(1); - if(uuid != null && !uuid.isEmpty()) - return uuid; - return identityString; - } - } catch (SQLException e) { - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - - return identityString; - } - - @DB - public void initializeDefaultUuid(String tableName) { - assert(tableName != null); - List l = getNullUuidRecords(tableName); - - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - try { - txn.start(); - for(Long id : l) { - setInitialUuid(tableName, id); - } - txn.commit(); - } catch (SQLException e) { - txn.rollback(); - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - } - - @DB - List getNullUuidRecords(String tableName) { - List l = new ArrayList(); - - PreparedStatement pstmt = null; - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - try { - pstmt = txn.prepareAutoCloseStatement( - String.format("SELECT id FROM `%s` WHERE uuid IS NULL", tableName) - ); - - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - l.add(rs.getLong(1)); - } - } catch (SQLException e) { - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - return l; - } - - @DB - void setInitialUuid(String tableName, long id) throws SQLException { - Transaction txn = Transaction.currentTxn(); - - PreparedStatement pstmtUpdate = null; - pstmtUpdate = txn.prepareAutoCloseStatement( - String.format("UPDATE `%s` SET uuid=? WHERE id=?", tableName) - ); - - pstmtUpdate.setString(1, UUID.randomUUID().toString()); - pstmtUpdate.setLong(2, id); - pstmtUpdate.executeUpdate(); - } -} +package com.cloud.uuididentity.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.IdentityMapper; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.Transaction; + +@Local(value={IdentityDao.class}) +public class IdentityDaoImpl extends GenericDaoBase implements IdentityDao { + private static final Logger s_logger = Logger.getLogger(IdentityDaoImpl.class); + + public IdentityDaoImpl() { + } + + @DB + public Long getIdentityId(IdentityMapper mapper, String identityString) { + assert(mapper.entityTableName() != null); + return getIdentityId(mapper.entityTableName(), identityString); + } + + @DB + public Long getIdentityId(String tableName, String identityString) { + assert(tableName != null); + assert(identityString != null); + + PreparedStatement pstmt = null; + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + try { + pstmt = txn.prepareAutoCloseStatement( + String.format("SELECT id FROM `%s` WHERE id=? OR uuid=?", tableName) + + // TODO : after graceful period, use following line turn on more secure check + // String.format("SELECT id FROM %s WHERE (id=? AND uuid IS NULL) OR uuid=?", mapper.entityTableName()) + ); + + long id = 0; + try { + // TODO : use regular expression to determine + id = Long.parseLong(identityString); + } catch(NumberFormatException e) { + // this could happen when it is a uuid string, so catch and ignore it + } + + pstmt.setLong(1, id); + pstmt.setString(2, identityString); + + ResultSet rs = pstmt.executeQuery(); + if(rs.next()) { + return rs.getLong(1); + } else { + if(id == -1L) + return id; + + throw new InvalidParameterValueException("Object " + tableName + "(uuid: " + identityString + ") does not exist."); + } + } catch (SQLException e) { + s_logger.error("Unexpected exception ", e); + } + } finally { + txn.close(); + } + return null; + } + + @DB + public String getIdentityUuid(String tableName, String identityString) { + assert(tableName != null); + assert(identityString != null); + + PreparedStatement pstmt = null; + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + try { + pstmt = txn.prepareAutoCloseStatement( + String.format("SELECT uuid FROM `%s` WHERE id=? OR uuid=?", tableName) + // String.format("SELECT uuid FROM %s WHERE (id=? AND uuid IS NULL) OR uuid=?", tableName) + ); + + long id = 0; + try { + // TODO : use regular expression to determine + id = Long.parseLong(identityString); + } catch(NumberFormatException e) { + // this could happen when it is a uuid string, so catch and ignore it + } + + pstmt.setLong(1, id); + pstmt.setString(2, identityString); + + ResultSet rs = pstmt.executeQuery(); + if(rs.next()) { + String uuid = rs.getString(1); + if(uuid != null && !uuid.isEmpty()) + return uuid; + return identityString; + } + } catch (SQLException e) { + s_logger.error("Unexpected exception ", e); + } + } finally { + txn.close(); + } + + return identityString; + } + + @DB + public void initializeDefaultUuid(String tableName) { + assert(tableName != null); + List l = getNullUuidRecords(tableName); + + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + try { + txn.start(); + for(Long id : l) { + setInitialUuid(tableName, id); + } + txn.commit(); + } catch (SQLException e) { + txn.rollback(); + s_logger.error("Unexpected exception ", e); + } + } finally { + txn.close(); + } + } + + @DB + List getNullUuidRecords(String tableName) { + List l = new ArrayList(); + + PreparedStatement pstmt = null; + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + try { + pstmt = txn.prepareAutoCloseStatement( + String.format("SELECT id FROM `%s` WHERE uuid IS NULL", tableName) + ); + + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + l.add(rs.getLong(1)); + } + } catch (SQLException e) { + s_logger.error("Unexpected exception ", e); + } + } finally { + txn.close(); + } + return l; + } + + @DB + void setInitialUuid(String tableName, long id) throws SQLException { + Transaction txn = Transaction.currentTxn(); + + PreparedStatement pstmtUpdate = null; + pstmtUpdate = txn.prepareAutoCloseStatement( + String.format("UPDATE `%s` SET uuid=? WHERE id=?", tableName) + ); + + pstmtUpdate.setString(1, UUID.randomUUID().toString()); + pstmtUpdate.setLong(2, id); + pstmtUpdate.executeUpdate(); + } +} diff --git a/server/src/com/cloud/uuididentity/dao/IdentityVO.java b/server/src/com/cloud/uuididentity/dao/IdentityVO.java index e15d10a62b0..45266664fd6 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityVO.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityVO.java @@ -10,12 +10,12 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.uuididentity.dao; - -import javax.persistence.Entity; - -/** - */ -@Entity -public class IdentityVO { -} +package com.cloud.uuididentity.dao; + +import javax.persistence.Entity; + +/** + */ +@Entity +public class IdentityVO { +} diff --git a/server/src/com/cloud/vm/dao/ConsoleProxyDao.java b/server/src/com/cloud/vm/dao/ConsoleProxyDao.java index 6bf1e6067d6..3a686b74e00 100644 --- a/server/src/com/cloud/vm/dao/ConsoleProxyDao.java +++ b/server/src/com/cloud/vm/dao/ConsoleProxyDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm.dao; - +package com.cloud.vm.dao; + import java.util.Date; import java.util.List; @@ -20,24 +20,24 @@ import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.VirtualMachine.State; - -public interface ConsoleProxyDao extends GenericDao { - - public void update(long id, int activeSession, Date updateTime, byte[] sessionDetails); - - public List getProxyListInStates(long dataCenterId, State... states); - public List getProxyListInStates(State... states); - + +public interface ConsoleProxyDao extends GenericDao { + + public void update(long id, int activeSession, Date updateTime, byte[] sessionDetails); + + public List getProxyListInStates(long dataCenterId, State... states); + public List getProxyListInStates(State... states); + public List listByHostId(long hostId); public List listByLastHostId(long hostId); - public List listUpByHostId(long hostId); - - public List getDatacenterProxyLoadMatrix(); - public List getDatacenterVMLoadMatrix(); - public List getDatacenterSessionLoadMatrix(); - public List> getDatacenterStoragePoolHostInfo(long dcId, boolean countAllPoolTypes); - public List> getProxyLoadMatrix(); - public int getProxyStaticLoad(long proxyVmId); - public int getProxyActiveLoad(long proxyVmId); - public List getRunningProxyListByMsid(long msid); -} + public List listUpByHostId(long hostId); + + public List getDatacenterProxyLoadMatrix(); + public List getDatacenterVMLoadMatrix(); + public List getDatacenterSessionLoadMatrix(); + public List> getDatacenterStoragePoolHostInfo(long dcId, boolean countAllPoolTypes); + public List> getProxyLoadMatrix(); + public int getProxyStaticLoad(long proxyVmId); + public int getProxyActiveLoad(long proxyVmId); + public List getRunningProxyListByMsid(long msid); +} diff --git a/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java b/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java index c66483758e4..a80c96ea854 100644 --- a/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java +++ b/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm.dao; - +package com.cloud.vm.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -33,65 +33,65 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.VirtualMachine.State; - -@Local(value={ConsoleProxyDao.class}) -public class ConsoleProxyDaoImpl extends GenericDaoBase implements ConsoleProxyDao { - private static final Logger s_logger = Logger.getLogger(ConsoleProxyDaoImpl.class); - - // - // query SQL for returnning console proxy assignment info as following - // proxy vm id, count of assignment - // - private static final String PROXY_ASSIGNMENT_MATRIX = - "SELECT c.id, count(runningVm.id) AS count " + - " FROM console_proxy AS c LEFT JOIN vm_instance AS i ON c.id=i.id LEFT JOIN" + - " (SELECT v.id AS id, v.proxy_id AS proxy_id FROM vm_instance AS v WHERE " + - " (v.state='Running' OR v.state='Creating' OR v.state='Starting' OR v.state='Migrating')) " + - " AS runningVm ON c.id = runningVm.proxy_id WHERE i.state='Running' " + - " GROUP BY c.id"; - - // - // query SQL for returnning running VM count at data center basis - // - private static final String DATACENTER_VM_MATRIX = - "SELECT d.id, d.name, count(v.id) AS count" + - " FROM data_center AS d LEFT JOIN vm_instance AS v ON v.data_center_id=d.id " + - " WHERE (v.state='Creating' OR v.state='Starting' OR v.state='Running' OR v.state='Migrating')" + - " GROUP BY d.id, d.name"; - - private static final String DATACENTER_ACTIVE_SESSION_MATRIX = - "SELECT d.id, d.name, sum(c.active_session) AS count" + - " FROM data_center AS d LEFT JOIN vm_instance AS v ON v.data_center_id=d.id " + - " LEFT JOIN console_proxy AS c ON v.id=c.id " + - " WHERE v.type='ConsoleProxy' AND (v.state='Creating' OR v.state='Starting' OR v.state='Running' OR v.state='Migrating')" + - " GROUP BY d.id, d.name"; - - // - // query SQL for returnning running console proxy count at data center basis - // - private static final String DATACENTER_PROXY_MATRIX = - "SELECT d.id, d.name, count(dcid) as count" + - " FROM data_center as d" + - " LEFT JOIN (" + - " SELECT v.data_center_id as dcid, c.active_session as active_session from vm_instance as v" + - " INNER JOIN console_proxy as c ON v.id=c.id AND v.type='ConsoleProxy' AND (v.state='Creating' OR v.state='Starting' OR v.state='Running' OR v.state='Migrating')" + - " ) as t ON d.id = t.dcid" + - " GROUP BY d.id, d.name"; - - private static final String GET_PROXY_LOAD = - "SELECT count(*) AS count" + - " FROM vm_instance AS v " + - " WHERE v.proxy_id=? AND (v.state='Running' OR v.state='Starting' OR v.state='Creating' OR v.state='Migrating')"; - - private static final String GET_PROXY_ACTIVE_LOAD = - "SELECT active_session AS count" + - " FROM console_proxy" + - " WHERE proxy_id=?"; - - private static final String STORAGE_POOL_HOST_INFO = - "SELECT p.data_center_id, count(ph.host_id) " + - " FROM storage_pool p, storage_pool_host_ref ph " + - " WHERE p.id = ph.pool_id AND p.data_center_id = ? " + + +@Local(value={ConsoleProxyDao.class}) +public class ConsoleProxyDaoImpl extends GenericDaoBase implements ConsoleProxyDao { + private static final Logger s_logger = Logger.getLogger(ConsoleProxyDaoImpl.class); + + // + // query SQL for returnning console proxy assignment info as following + // proxy vm id, count of assignment + // + private static final String PROXY_ASSIGNMENT_MATRIX = + "SELECT c.id, count(runningVm.id) AS count " + + " FROM console_proxy AS c LEFT JOIN vm_instance AS i ON c.id=i.id LEFT JOIN" + + " (SELECT v.id AS id, v.proxy_id AS proxy_id FROM vm_instance AS v WHERE " + + " (v.state='Running' OR v.state='Creating' OR v.state='Starting' OR v.state='Migrating')) " + + " AS runningVm ON c.id = runningVm.proxy_id WHERE i.state='Running' " + + " GROUP BY c.id"; + + // + // query SQL for returnning running VM count at data center basis + // + private static final String DATACENTER_VM_MATRIX = + "SELECT d.id, d.name, count(v.id) AS count" + + " FROM data_center AS d LEFT JOIN vm_instance AS v ON v.data_center_id=d.id " + + " WHERE (v.state='Creating' OR v.state='Starting' OR v.state='Running' OR v.state='Migrating')" + + " GROUP BY d.id, d.name"; + + private static final String DATACENTER_ACTIVE_SESSION_MATRIX = + "SELECT d.id, d.name, sum(c.active_session) AS count" + + " FROM data_center AS d LEFT JOIN vm_instance AS v ON v.data_center_id=d.id " + + " LEFT JOIN console_proxy AS c ON v.id=c.id " + + " WHERE v.type='ConsoleProxy' AND (v.state='Creating' OR v.state='Starting' OR v.state='Running' OR v.state='Migrating')" + + " GROUP BY d.id, d.name"; + + // + // query SQL for returnning running console proxy count at data center basis + // + private static final String DATACENTER_PROXY_MATRIX = + "SELECT d.id, d.name, count(dcid) as count" + + " FROM data_center as d" + + " LEFT JOIN (" + + " SELECT v.data_center_id as dcid, c.active_session as active_session from vm_instance as v" + + " INNER JOIN console_proxy as c ON v.id=c.id AND v.type='ConsoleProxy' AND (v.state='Creating' OR v.state='Starting' OR v.state='Running' OR v.state='Migrating')" + + " ) as t ON d.id = t.dcid" + + " GROUP BY d.id, d.name"; + + private static final String GET_PROXY_LOAD = + "SELECT count(*) AS count" + + " FROM vm_instance AS v " + + " WHERE v.proxy_id=? AND (v.state='Running' OR v.state='Starting' OR v.state='Creating' OR v.state='Migrating')"; + + private static final String GET_PROXY_ACTIVE_LOAD = + "SELECT active_session AS count" + + " FROM console_proxy" + + " WHERE proxy_id=?"; + + private static final String STORAGE_POOL_HOST_INFO = + "SELECT p.data_center_id, count(ph.host_id) " + + " FROM storage_pool p, storage_pool_host_ref ph " + + " WHERE p.id = ph.pool_id AND p.data_center_id = ? " + " GROUP by p.data_center_id"; private static final String SHARED_STORAGE_POOL_HOST_INFO = @@ -99,99 +99,99 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im " FROM storage_pool p, storage_pool_host_ref ph " + " WHERE p.pool_type <> 'LVM' AND p.id = ph.pool_id AND p.data_center_id = ? " + " GROUP by p.data_center_id"; - - protected SearchBuilder DataCenterStatusSearch; - protected SearchBuilder StateSearch; + + protected SearchBuilder DataCenterStatusSearch; + protected SearchBuilder StateSearch; protected SearchBuilder HostSearch; protected SearchBuilder LastHostSearch; - protected SearchBuilder HostUpSearch; - protected SearchBuilder StateChangeSearch; - - protected final Attribute _updateTimeAttr; - - public ConsoleProxyDaoImpl() { - DataCenterStatusSearch = createSearchBuilder(); - DataCenterStatusSearch.and("dc", DataCenterStatusSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - DataCenterStatusSearch.and("states", DataCenterStatusSearch.entity().getState(), SearchCriteria.Op.IN); - DataCenterStatusSearch.done(); - - StateSearch = createSearchBuilder(); - StateSearch.and("states", StateSearch.entity().getState(), SearchCriteria.Op.IN); - StateSearch.done(); - - HostSearch = createSearchBuilder(); - HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + protected SearchBuilder HostUpSearch; + protected SearchBuilder StateChangeSearch; + + protected final Attribute _updateTimeAttr; + + public ConsoleProxyDaoImpl() { + DataCenterStatusSearch = createSearchBuilder(); + DataCenterStatusSearch.and("dc", DataCenterStatusSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); + DataCenterStatusSearch.and("states", DataCenterStatusSearch.entity().getState(), SearchCriteria.Op.IN); + DataCenterStatusSearch.done(); + + StateSearch = createSearchBuilder(); + StateSearch.and("states", StateSearch.entity().getState(), SearchCriteria.Op.IN); + StateSearch.done(); + + HostSearch = createSearchBuilder(); + HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostSearch.done(); LastHostSearch = createSearchBuilder(); LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ); LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ); - LastHostSearch.done(); + LastHostSearch.done(); HostUpSearch = createSearchBuilder(); HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN); HostUpSearch.done(); - - StateChangeSearch = createSearchBuilder(); - StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); - StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); - StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ); - StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ); - StateChangeSearch.done(); - - _updateTimeAttr = _allAttributes.get("updateTime"); - assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; - } - - @Override - public void update(long id, int activeSession, Date updateTime, byte[] sessionDetails) { - ConsoleProxyVO ub = createForUpdate(); - ub.setActiveSession(activeSession); - ub.setLastUpdateTime(updateTime); - ub.setSessionDetails(sessionDetails); - - update(id, ub); - } - - @Override - public boolean remove(Long id) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - ConsoleProxyVO proxy = createForUpdate(); - proxy.setPublicIpAddress(null); - proxy.setPrivateIpAddress(null); - - UpdateBuilder ub = getUpdateBuilder(proxy); - ub.set(proxy, "state", State.Destroyed); - ub.set(proxy, "privateIpAddress", null); - update(id, ub, proxy); - - boolean result = super.remove(id); - txn.commit(); - return result; - } - - @Override - public List getProxyListInStates(long dataCenterId, State... states) { - SearchCriteria sc = DataCenterStatusSearch.create(); - sc.setParameters("states", (Object[])states); - sc.setParameters("dc", dataCenterId); - return listBy(sc); - } - - @Override - public List getProxyListInStates(State... states) { - SearchCriteria sc = StateSearch.create(); - sc.setParameters("states", (Object[])states); - return listBy(sc); - } - - @Override - public List listByHostId(long hostId) { - SearchCriteria sc = HostSearch.create(); - sc.setParameters("host", hostId); - return listBy(sc); + + StateChangeSearch = createSearchBuilder(); + StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); + StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); + StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ); + StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ); + StateChangeSearch.done(); + + _updateTimeAttr = _allAttributes.get("updateTime"); + assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; + } + + @Override + public void update(long id, int activeSession, Date updateTime, byte[] sessionDetails) { + ConsoleProxyVO ub = createForUpdate(); + ub.setActiveSession(activeSession); + ub.setLastUpdateTime(updateTime); + ub.setSessionDetails(sessionDetails); + + update(id, ub); + } + + @Override + public boolean remove(Long id) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + ConsoleProxyVO proxy = createForUpdate(); + proxy.setPublicIpAddress(null); + proxy.setPrivateIpAddress(null); + + UpdateBuilder ub = getUpdateBuilder(proxy); + ub.set(proxy, "state", State.Destroyed); + ub.set(proxy, "privateIpAddress", null); + update(id, ub, proxy); + + boolean result = super.remove(id); + txn.commit(); + return result; + } + + @Override + public List getProxyListInStates(long dataCenterId, State... states) { + SearchCriteria sc = DataCenterStatusSearch.create(); + sc.setParameters("states", (Object[])states); + sc.setParameters("dc", dataCenterId); + return listBy(sc); + } + + @Override + public List getProxyListInStates(State... states) { + SearchCriteria sc = StateSearch.create(); + sc.setParameters("states", (Object[])states); + return listBy(sc); + } + + @Override + public List listByHostId(long hostId) { + SearchCriteria sc = HostSearch.create(); + sc.setParameters("host", hostId); + return listBy(sc); } @Override @@ -200,141 +200,141 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im sc.setParameters("host", hostId); sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging}); return listBy(sc); - } - - @Override - public List getDatacenterProxyLoadMatrix() { - return getDatacenterLoadMatrix(DATACENTER_PROXY_MATRIX); - } - - @Override - public List getDatacenterVMLoadMatrix() { - return getDatacenterLoadMatrix(DATACENTER_VM_MATRIX); - } - - @Override - public List getDatacenterSessionLoadMatrix() { - return getDatacenterLoadMatrix(DATACENTER_ACTIVE_SESSION_MATRIX); - } - - @Override - public List> getProxyLoadMatrix() { - ArrayList> l = new ArrayList>(); - - Transaction txn = Transaction.currentTxn();; - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(PROXY_ASSIGNMENT_MATRIX); - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - l.add(new Pair(rs.getLong(1), rs.getInt(2))); - } - } catch (SQLException e) { - } catch (Throwable e) { - } - return l; - } - - @Override - public List> getDatacenterStoragePoolHostInfo(long dcId, boolean countAllPoolTypes) { - ArrayList> l = new ArrayList>(); - - Transaction txn = Transaction.currentTxn();; - PreparedStatement pstmt = null; + } + + @Override + public List getDatacenterProxyLoadMatrix() { + return getDatacenterLoadMatrix(DATACENTER_PROXY_MATRIX); + } + + @Override + public List getDatacenterVMLoadMatrix() { + return getDatacenterLoadMatrix(DATACENTER_VM_MATRIX); + } + + @Override + public List getDatacenterSessionLoadMatrix() { + return getDatacenterLoadMatrix(DATACENTER_ACTIVE_SESSION_MATRIX); + } + + @Override + public List> getProxyLoadMatrix() { + ArrayList> l = new ArrayList>(); + + Transaction txn = Transaction.currentTxn();; + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(PROXY_ASSIGNMENT_MATRIX); + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + l.add(new Pair(rs.getLong(1), rs.getInt(2))); + } + } catch (SQLException e) { + } catch (Throwable e) { + } + return l; + } + + @Override + public List> getDatacenterStoragePoolHostInfo(long dcId, boolean countAllPoolTypes) { + ArrayList> l = new ArrayList>(); + + Transaction txn = Transaction.currentTxn();; + PreparedStatement pstmt = null; try { if(countAllPoolTypes) { pstmt = txn.prepareAutoCloseStatement(STORAGE_POOL_HOST_INFO); } else { pstmt = txn.prepareAutoCloseStatement(SHARED_STORAGE_POOL_HOST_INFO); } - pstmt.setLong(1, dcId); - - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - l.add(new Pair(rs.getLong(1), rs.getInt(2))); - } - } catch (SQLException e) { - } catch (Throwable e) { - } - return l; - } - - @Override - public int getProxyStaticLoad(long proxyVmId) { - Transaction txn = Transaction.currentTxn();; - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(GET_PROXY_LOAD); - pstmt.setLong(1, proxyVmId); - - ResultSet rs = pstmt.executeQuery(); + pstmt.setLong(1, dcId); + + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + l.add(new Pair(rs.getLong(1), rs.getInt(2))); + } + } catch (SQLException e) { + } catch (Throwable e) { + } + return l; + } + + @Override + public int getProxyStaticLoad(long proxyVmId) { + Transaction txn = Transaction.currentTxn();; + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(GET_PROXY_LOAD); + pstmt.setLong(1, proxyVmId); + + ResultSet rs = pstmt.executeQuery(); if(rs != null && rs.first()) { return rs.getInt(1); - } - } catch (SQLException e) { - } catch (Throwable e) { - } - return 0; - } - - @Override - public int getProxyActiveLoad(long proxyVmId) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(GET_PROXY_ACTIVE_LOAD); - pstmt.setLong(1, proxyVmId); - - ResultSet rs = pstmt.executeQuery(); + } + } catch (SQLException e) { + } catch (Throwable e) { + } + return 0; + } + + @Override + public int getProxyActiveLoad(long proxyVmId) { + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(GET_PROXY_ACTIVE_LOAD); + pstmt.setLong(1, proxyVmId); + + ResultSet rs = pstmt.executeQuery(); if(rs != null && rs.first()) { return rs.getInt(1); - } - } catch (SQLException e) { - } catch (Throwable e) { - } - return 0; - } - - private List getDatacenterLoadMatrix(String sql) { - ArrayList l = new ArrayList(); - - Transaction txn = Transaction.currentTxn();; - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - ConsoleProxyLoadInfo info = new ConsoleProxyLoadInfo(); - info.setId(rs.getLong(1)); - info.setName(rs.getString(2)); - info.setCount(rs.getInt(3)); - l.add(info); - } - } catch (SQLException e) { - } catch (Throwable e) { - } - return l; - } - - @Override - public List getRunningProxyListByMsid(long msid) { - List l = new ArrayList(); - Transaction txn = Transaction.currentTxn();; - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement( - "SELECT c.id FROM console_proxy c, vm_instance v, host h " + - "WHERE c.id=v.id AND v.state='Running' AND v.host_id=h.id AND h.mgmt_server_id=?"); - - pstmt.setLong(1, msid); - ResultSet rs = pstmt.executeQuery(); - while(rs.next()) { - l.add(rs.getLong(1)); - } - } catch (SQLException e) { - } catch (Throwable e) { - } - return l; + } + } catch (SQLException e) { + } catch (Throwable e) { + } + return 0; + } + + private List getDatacenterLoadMatrix(String sql) { + ArrayList l = new ArrayList(); + + Transaction txn = Transaction.currentTxn();; + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql); + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + ConsoleProxyLoadInfo info = new ConsoleProxyLoadInfo(); + info.setId(rs.getLong(1)); + info.setName(rs.getString(2)); + info.setCount(rs.getInt(3)); + l.add(info); + } + } catch (SQLException e) { + } catch (Throwable e) { + } + return l; + } + + @Override + public List getRunningProxyListByMsid(long msid) { + List l = new ArrayList(); + Transaction txn = Transaction.currentTxn();; + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement( + "SELECT c.id FROM console_proxy c, vm_instance v, host h " + + "WHERE c.id=v.id AND v.state='Running' AND v.host_id=h.id AND h.mgmt_server_id=?"); + + pstmt.setLong(1, msid); + ResultSet rs = pstmt.executeQuery(); + while(rs.next()) { + l.add(rs.getLong(1)); + } + } catch (SQLException e) { + } catch (Throwable e) { + } + return l; } @Override @@ -343,5 +343,5 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im sc.setParameters("lastHost", hostId); sc.setParameters("state", State.Stopped); return listBy(sc); - } -} + } +} diff --git a/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java b/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java index 045cad5c0d8..e70819ccec2 100644 --- a/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java +++ b/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java @@ -10,29 +10,29 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm.dao; - +package com.cloud.vm.dao; + import java.util.List; import com.cloud.utils.db.GenericDao; import com.cloud.vm.SecondaryStorageVm; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.VirtualMachine.State; - -public interface SecondaryStorageVmDao extends GenericDao { - - public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, long dataCenterId, State... states); - public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, State... states); - + +public interface SecondaryStorageVmDao extends GenericDao { + + public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, long dataCenterId, State... states); + public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, State... states); + public List listByHostId(SecondaryStorageVm.Role role, long hostId); public List listByLastHostId(SecondaryStorageVm.Role role, long hostId); public List listUpByHostId(SecondaryStorageVm.Role role, long hostId); - public List listByZoneId(SecondaryStorageVm.Role role, long zoneId); - + public List listByZoneId(SecondaryStorageVm.Role role, long zoneId); + public List getRunningSecStorageVmListByMsid(SecondaryStorageVm.Role role, long msid); public List listRunningSecStorageOrderByLoad(SecondaryStorageVm.Role role, long zoneId); SecondaryStorageVmVO findByInstanceName(String instanceName); -} +} diff --git a/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java b/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java index 63db1322046..57ec897de7b 100644 --- a/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java +++ b/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm.dao; - +package com.cloud.vm.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,36 +31,36 @@ import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.SecondaryStorageVm; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.VirtualMachine.State; - -@Local(value={SecondaryStorageVmDao.class}) -public class SecondaryStorageVmDaoImpl extends GenericDaoBase implements SecondaryStorageVmDao { - private static final Logger s_logger = Logger.getLogger(SecondaryStorageVmDaoImpl.class); - - protected SearchBuilder DataCenterStatusSearch; - protected SearchBuilder StateSearch; + +@Local(value={SecondaryStorageVmDao.class}) +public class SecondaryStorageVmDaoImpl extends GenericDaoBase implements SecondaryStorageVmDao { + private static final Logger s_logger = Logger.getLogger(SecondaryStorageVmDaoImpl.class); + + protected SearchBuilder DataCenterStatusSearch; + protected SearchBuilder StateSearch; protected SearchBuilder HostSearch; protected SearchBuilder LastHostSearch; protected SearchBuilder HostUpSearch; - protected SearchBuilder ZoneSearch; + protected SearchBuilder ZoneSearch; protected SearchBuilder StateChangeSearch; - protected SearchBuilder InstanceSearch; - - protected final Attribute _updateTimeAttr; - - public SecondaryStorageVmDaoImpl() { - DataCenterStatusSearch = createSearchBuilder(); - DataCenterStatusSearch.and("dc", DataCenterStatusSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - DataCenterStatusSearch.and("states", DataCenterStatusSearch.entity().getState(), SearchCriteria.Op.IN); + protected SearchBuilder InstanceSearch; + + protected final Attribute _updateTimeAttr; + + public SecondaryStorageVmDaoImpl() { + DataCenterStatusSearch = createSearchBuilder(); + DataCenterStatusSearch.and("dc", DataCenterStatusSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); + DataCenterStatusSearch.and("states", DataCenterStatusSearch.entity().getState(), SearchCriteria.Op.IN); DataCenterStatusSearch.and("role", DataCenterStatusSearch.entity().getRole(), SearchCriteria.Op.EQ); - DataCenterStatusSearch.done(); - - StateSearch = createSearchBuilder(); - StateSearch.and("states", StateSearch.entity().getState(), SearchCriteria.Op.IN); + DataCenterStatusSearch.done(); + + StateSearch = createSearchBuilder(); + StateSearch.and("states", StateSearch.entity().getState(), SearchCriteria.Op.IN); StateSearch.and("role", StateSearch.entity().getRole(), SearchCriteria.Op.EQ); - StateSearch.done(); - - HostSearch = createSearchBuilder(); - HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + StateSearch.done(); + + HostSearch = createSearchBuilder(); + HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostSearch.and("role", HostSearch.entity().getRole(), SearchCriteria.Op.EQ); HostSearch.done(); @@ -83,69 +83,69 @@ public class SecondaryStorageVmDaoImpl extends GenericDaoBase getSecStorageVmListInStates(SecondaryStorageVm.Role role, long dataCenterId, State... states) { - SearchCriteria sc = DataCenterStatusSearch.create(); - sc.setParameters("states", (Object[])states); + StateChangeSearch.done(); + + _updateTimeAttr = _allAttributes.get("updateTime"); + assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; + } + + @Override + public boolean remove(Long id) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + SecondaryStorageVmVO proxy = createForUpdate(); + proxy.setPublicIpAddress(null); + proxy.setPrivateIpAddress(null); + + UpdateBuilder ub = getUpdateBuilder(proxy); + ub.set(proxy, "state", State.Destroyed); + ub.set(proxy, "privateIpAddress", null); + update(id, ub, proxy); + + boolean result = super.remove(id); + txn.commit(); + return result; + } + + @Override + public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, long dataCenterId, State... states) { + SearchCriteria sc = DataCenterStatusSearch.create(); + sc.setParameters("states", (Object[])states); sc.setParameters("dc", dataCenterId); if(role != null) { sc.setParameters("role", role); - } - return listBy(sc); - } - - @Override - public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, State... states) { - SearchCriteria sc = StateSearch.create(); + } + return listBy(sc); + } + + @Override + public List getSecStorageVmListInStates(SecondaryStorageVm.Role role, State... states) { + SearchCriteria sc = StateSearch.create(); sc.setParameters("states", (Object[])states); if(role != null) { sc.setParameters("role", role); } - - return listBy(sc); - } - - @Override - public List listByHostId(SecondaryStorageVm.Role role, long hostId) { - SearchCriteria sc = HostSearch.create(); - sc.setParameters("host", hostId); + + return listBy(sc); + } + + @Override + public List listByHostId(SecondaryStorageVm.Role role, long hostId) { + SearchCriteria sc = HostSearch.create(); + sc.setParameters("host", hostId); if(role != null) { sc.setParameters("role", role); } - return listBy(sc); - } + return listBy(sc); + } @Override public List listUpByHostId(SecondaryStorageVm.Role role, long hostId) { @@ -156,13 +156,13 @@ public class SecondaryStorageVmDaoImpl extends GenericDaoBase getRunningSecStorageVmListByMsid(SecondaryStorageVm.Role role, long msid) { - List l = new ArrayList(); - Transaction txn = Transaction.currentTxn();; - PreparedStatement pstmt = null; + } + + @Override + public List getRunningSecStorageVmListByMsid(SecondaryStorageVm.Role role, long msid) { + List l = new ArrayList(); + Transaction txn = Transaction.currentTxn();; + PreparedStatement pstmt = null; try { String sql; if(role == null) { @@ -172,24 +172,24 @@ public class SecondaryStorageVmDaoImpl extends GenericDaoBase implements UserVmDao { - public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class); - - protected final SearchBuilder AccountPodSearch; - protected final SearchBuilder AccountDataCenterSearch; - protected final SearchBuilder AccountSearch; - protected final SearchBuilder HostSearch; - protected final SearchBuilder LastHostSearch; - protected final SearchBuilder HostUpSearch; - protected final SearchBuilder HostRunningSearch; - protected final SearchBuilder StateChangeSearch; - protected final SearchBuilder AccountHostSearch; - - protected final SearchBuilder DestroySearch; - protected SearchBuilder AccountDataCenterVirtualSearch; - protected GenericSearchBuilder CountByAccountPod; - protected GenericSearchBuilder CountByAccount; - protected GenericSearchBuilder PodsHavingVmsForAccount; - - protected SearchBuilder UserVmSearch; - protected final Attribute _updateTimeAttr; - - private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " + - "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; - - private static String VM_DETAILS = "select vm_instance.id, " + - "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," + - "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " + - "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " + - "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + - "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + - "security_group.description, nics.id, nics.ip4_address, nics.default_nic, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " + - "networks.traffic_type, networks.guest_type, user_ip_address.id, user_ip_address.public_ip_address from vm_instance " + - "left join account on vm_instance.account_id=account.id " + - "left join domain on vm_instance.domain_id=domain.id " + - "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " + - "left join instance_group on instance_group_vm_map.group_id=instance_group.id " + - "left join data_center on vm_instance.data_center_id=data_center.id " + - "left join host on vm_instance.host_id=host.id " + - "left join vm_template on vm_instance.vm_template_id=vm_template.id " + - "left join user_vm on vm_instance.id=user_vm.id " + - "left join vm_template iso on iso.id=user_vm.iso_id " + - "left join service_offering on vm_instance.service_offering_id=service_offering.id " + - "left join disk_offering on vm_instance.service_offering_id=disk_offering.id " + - "left join volumes on vm_instance.id=volumes.instance_id " + - "left join storage_pool on volumes.pool_id=storage_pool.id " + - "left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " + - "left join security_group on security_group_vm_map.security_group_id=security_group.id " + - "left join nics on vm_instance.id=nics.instance_id " + - "left join networks on nics.network_id=networks.id " + - "left join user_ip_address on user_ip_address.vm_id=vm_instance.id " + - "where vm_instance.id in ("; - - private static final int VM_DETAILS_BATCH_SIZE=100; - - protected final UserVmDetailsDaoImpl _detailsDao = ComponentLocator.inject(UserVmDetailsDaoImpl.class); - protected final NicDaoImpl _nicDao = ComponentLocator.inject(NicDaoImpl.class); - - protected UserVmDaoImpl() { - AccountSearch = createSearchBuilder(); - AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountSearch.done(); - - HostSearch = createSearchBuilder(); - HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostSearch.done(); - - LastHostSearch = createSearchBuilder(); - LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ); - LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ); - LastHostSearch.done(); - - HostUpSearch = createSearchBuilder(); - HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN); - HostUpSearch.done(); - - HostRunningSearch = createSearchBuilder(); - HostRunningSearch.and("host", HostRunningSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostRunningSearch.and("state", HostRunningSearch.entity().getState(), SearchCriteria.Op.EQ); - HostRunningSearch.done(); - - AccountPodSearch = createSearchBuilder(); - AccountPodSearch.and("account", AccountPodSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountPodSearch.and("pod", AccountPodSearch.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); - AccountPodSearch.done(); - - AccountDataCenterSearch = createSearchBuilder(); - AccountDataCenterSearch.and("account", AccountDataCenterSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountDataCenterSearch.and("dc", AccountDataCenterSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - AccountDataCenterSearch.done(); - - StateChangeSearch = createSearchBuilder(); - StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); - StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); - StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ); - StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ); - StateChangeSearch.done(); - - DestroySearch = createSearchBuilder(); - DestroySearch.and("state", DestroySearch.entity().getState(), SearchCriteria.Op.IN); - DestroySearch.and("updateTime", DestroySearch.entity().getUpdateTime(), SearchCriteria.Op.LT); - DestroySearch.done(); - - AccountHostSearch = createSearchBuilder(); - AccountHostSearch.and("accountId", AccountHostSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountHostSearch.and("hostId", AccountHostSearch.entity().getHostId(), SearchCriteria.Op.EQ); - AccountHostSearch.done(); - - CountByAccountPod = createSearchBuilder(Long.class); - CountByAccountPod.select(null, Func.COUNT, null); - CountByAccountPod.and("account", CountByAccountPod.entity().getAccountId(), SearchCriteria.Op.EQ); - CountByAccountPod.and("pod", CountByAccountPod.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); - CountByAccountPod.done(); - - CountByAccount = createSearchBuilder(Long.class); - CountByAccount.select(null, Func.COUNT, null); - CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); - CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ); - CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); - CountByAccount.done(); - - - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); - - AccountDataCenterVirtualSearch = createSearchBuilder(); - AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); - AccountDataCenterVirtualSearch.done(); - - - _updateTimeAttr = _allAttributes.get("updateTime"); - assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; - } - - @Override - public List listByAccountAndPod(long accountId, long podId) { - SearchCriteria sc = AccountPodSearch.create(); - sc.setParameters("account", accountId); - sc.setParameters("pod", podId); - - return listIncludingRemovedBy(sc); - } - - @Override - public List listByAccountAndDataCenter(long accountId, long dcId) { - SearchCriteria sc = AccountDataCenterSearch.create(); - sc.setParameters("account", accountId); - sc.setParameters("dc", dcId); - - return listIncludingRemovedBy(sc); - } - - @Override - public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData) { - UserVmVO vo = createForUpdate(); - vo.setDisplayName(displayName); - vo.setHaEnabled(enable); - vo.setGuestOSId(osTypeId); - vo.setUserData(userData); - update(id, vo); - } - - @Override - public List findDestroyedVms(Date date) { - SearchCriteria sc = DestroySearch.create(); - sc.setParameters("state", State.Destroyed, State.Expunging, State.Error); - sc.setParameters("updateTime", date); - - return listBy(sc); - } - - @Override - public List listByAccountId(long id) { - SearchCriteria sc = AccountSearch.create(); - sc.setParameters("account", id); - return listBy(sc); - } - - @Override - public List listByHostId(Long id) { - SearchCriteria sc = HostSearch.create(); - sc.setParameters("host", id); - - return listBy(sc); - } - - @Override - public List listUpByHostId(Long hostId) { - SearchCriteria sc = HostUpSearch.create(); - sc.setParameters("host", hostId); - sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging}); - return listBy(sc); - } - - @Override - public List listRunningByHostId(long hostId) { - SearchCriteria sc = HostRunningSearch.create(); - sc.setParameters("host", hostId); - sc.setParameters("state", State.Running); - - return listBy(sc); - } - - @Override - public List listVirtualNetworkInstancesByAcctAndZone(long accountId, long dcId, long networkId) { - - SearchCriteria sc = AccountDataCenterVirtualSearch.create(); - sc.setParameters("account", accountId); - sc.setParameters("dc", dcId); - sc.setJoinParameters("nicSearch", "networkId", networkId); - - return listBy(sc); - } - - @Override - public List listByNetworkIdAndStates(long networkId, State... states) { - if (UserVmSearch == null) { - NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class); - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); - - UserVmSearch = createSearchBuilder(); - UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN); - UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); - UserVmSearch.done(); - } - - SearchCriteria sc = UserVmSearch.create(); - if (states != null && states.length != 0) { - sc.setParameters("states", (Object[]) states); - } - sc.setJoinParameters("nicSearch", "networkId", networkId); - - return listBy(sc); - } - - @Override - public List listByLastHostId(Long hostId) { - SearchCriteria sc = LastHostSearch.create(); - sc.setParameters("lastHost", hostId); - sc.setParameters("state", State.Stopped); - return listBy(sc); - } - - @Override - public List listByAccountIdAndHostId(long accountId, long hostId) { - SearchCriteria sc = AccountHostSearch.create(); - sc.setParameters("hostId", hostId); - sc.setParameters("accountId", accountId); - return listBy(sc); - } - - @Override - public void loadDetails(UserVmVO vm) { - Map details = _detailsDao.findDetails(vm.getId()); - vm.setDetails(details); - } - - @Override - public void saveDetails(UserVmVO vm) { - Map details = vm.getDetails(); - if (details == null) { - return; - } - _detailsDao.persist(vm.getId(), details); - } - - @Override - public List listPodIdsHavingVmsforAccount(long zoneId, long accountId){ - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - - try { - String sql = LIST_PODS_HAVING_VMS_FOR_ACCOUNT; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, zoneId); - pstmt.setLong(2, accountId); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - result.add(rs.getLong(1)); - } - return result; - } catch (SQLException e) { - throw new CloudRuntimeException("DB Exception on: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e); - } catch (Throwable e) { - throw new CloudRuntimeException("Caught: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e); - } - } - - @Override - public Hashtable listVmDetails(Hashtable userVmDataHash){ - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - - try { - int curr_index=0; - - List userVmDataList = new ArrayList(userVmDataHash.values()); - - if (userVmDataList.size() > VM_DETAILS_BATCH_SIZE){ - pstmt = txn.prepareStatement(VM_DETAILS + getQueryBatchAppender(VM_DETAILS_BATCH_SIZE)); - while ( (curr_index + VM_DETAILS_BATCH_SIZE) <= userVmDataList.size()){ - // set the vars value - for (int k=1,j=curr_index;j 0){ - userVmData.setGroupId(grp_id); - userVmData.setGroup(rs.getString("instance_group.name")); - } - - //"data_center.id, data_center.name, host.id, host.name, vm_template.id, vm_template.name, vm_template.display_text, vm_template.enable_password, - userVmData.setZoneId(rs.getLong("data_center.id")); - userVmData.setZoneName(rs.getString("data_center.name")); - - userVmData.setHostId(rs.getLong("host.id")); - userVmData.setHostName(rs.getString("host.name")); - - long template_id = rs.getLong("vm_template.id"); - if (template_id > 0){ - userVmData.setTemplateId(template_id); - userVmData.setTemplateName(rs.getString("vm_template.name")); - userVmData.setTemplateDisplayText(rs.getString("vm_template.display_text")); - userVmData.setPasswordEnabled(rs.getBoolean("vm_template.enable_password")); - } - else { - userVmData.setTemplateId(-1L); - userVmData.setTemplateName("ISO Boot"); - userVmData.setTemplateDisplayText("ISO Boot"); - userVmData.setPasswordEnabled(false); - } - - long iso_id = rs.getLong("iso.id"); - if (iso_id > 0){ - userVmData.setIsoId(iso_id); - userVmData.setIsoName(rs.getString("iso.name")); - } - - - //service_offering.id, disk_offering.name, " - //"service_offering.cpu, service_offering.speed, service_offering.ram_size, - userVmData.setServiceOfferingId(rs.getLong("service_offering.id")); - userVmData.setServiceOfferingName(rs.getString("disk_offering.name")); - userVmData.setCpuNumber(rs.getInt("service_offering.cpu")); - userVmData.setCpuSpeed(rs.getInt("service_offering.speed")); - userVmData.setMemory(rs.getInt("service_offering.ram_size")); - - // volumes.device_id, volumes.volume_type, - long vol_id = rs.getLong("volumes.id"); - if (vol_id > 0){ - userVmData.setRootDeviceId(rs.getLong("volumes.device_id")); - userVmData.setRootDeviceType(rs.getString("volumes.volume_type")); - // storage pool - long pool_id = rs.getLong("storage_pool.id"); - if (pool_id > 0){ - userVmData.setRootDeviceType(rs.getString("storage_pool.pool_type")); - } - else { - userVmData.setRootDeviceType("Not created"); - } - } - userVmData.setInitialized(); - } - - - Long securityGroupId = rs.getLong("security_group.id"); - if (securityGroupId != null && securityGroupId.longValue() != 0){ - SecurityGroupData resp = userVmData.newSecurityGroupData(); - resp.setId(rs.getLong("security_group.id")); - resp.setName(rs.getString("security_group.name")); - resp.setDescription(rs.getString("security_group.description")); - resp.setObjectName("securitygroup"); - userVmData.addSecurityGroup(resp); - } - - long nic_id = rs.getLong("nics.id"); - if (nic_id > 0){ - NicData nicResponse = userVmData.newNicData(); - nicResponse.setId(nic_id); - nicResponse.setIpaddress(rs.getString("nics.ip4_address")); - nicResponse.setGateway(rs.getString("nics.gateway")); - nicResponse.setNetmask(rs.getString("nics.netmask")); - nicResponse.setNetworkid(rs.getLong("nics.network_id")); - nicResponse.setMacAddress(rs.getString("nics.mac_address")); - - int account_type = rs.getInt("account.type"); - if (account_type == Account.ACCOUNT_TYPE_ADMIN) { - nicResponse.setBroadcastUri(rs.getString("nics.broadcast_uri")); - nicResponse.setIsolationUri(rs.getString("nics.isolation_uri")); - } - - - nicResponse.setTrafficType(rs.getString("networks.traffic_type")); - nicResponse.setType(rs.getString("networks.guest_type")); - nicResponse.setIsDefault(rs.getBoolean("nics.default_nic")); - nicResponse.setObjectName("nic"); - userVmData.addNic(nicResponse); - } - - long publicIpId = rs.getLong("user_ip_address.id"); - if (publicIpId > 0){ - userVmData.setPublicIpId(publicIpId); - userVmData.setPublicIp(rs.getString("user_ip_address.public_ip_address")); - } - - return userVmData; - } - - public String getQueryBatchAppender(int count){ - StringBuilder sb = new StringBuilder(); - for (int i=0;i sc = CountByAccount.create(); - sc.setParameters("account", accountId); - sc.setParameters("type", VirtualMachine.Type.User); - sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging}); - return customSearch(sc, null).get(0); - } - - -} +package com.cloud.vm.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.user.Account; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.db.Attribute; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.JoinBuilder; +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.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicVO; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.State; +import com.cloud.vm.dao.UserVmData.NicData; +import com.cloud.vm.dao.UserVmData.SecurityGroupData; + +@Local(value={UserVmDao.class}) +public class UserVmDaoImpl extends GenericDaoBase implements UserVmDao { + public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class); + + protected final SearchBuilder AccountPodSearch; + protected final SearchBuilder AccountDataCenterSearch; + protected final SearchBuilder AccountSearch; + protected final SearchBuilder HostSearch; + protected final SearchBuilder LastHostSearch; + protected final SearchBuilder HostUpSearch; + protected final SearchBuilder HostRunningSearch; + protected final SearchBuilder StateChangeSearch; + protected final SearchBuilder AccountHostSearch; + + protected final SearchBuilder DestroySearch; + protected SearchBuilder AccountDataCenterVirtualSearch; + protected GenericSearchBuilder CountByAccountPod; + protected GenericSearchBuilder CountByAccount; + protected GenericSearchBuilder PodsHavingVmsForAccount; + + protected SearchBuilder UserVmSearch; + protected final Attribute _updateTimeAttr; + + private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " + + "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; + + private static String VM_DETAILS = "select vm_instance.id, " + + "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," + + "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " + + "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " + + "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + + "security_group.description, nics.id, nics.ip4_address, nics.default_nic, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " + + "networks.traffic_type, networks.guest_type, user_ip_address.id, user_ip_address.public_ip_address from vm_instance " + + "left join account on vm_instance.account_id=account.id " + + "left join domain on vm_instance.domain_id=domain.id " + + "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " + + "left join instance_group on instance_group_vm_map.group_id=instance_group.id " + + "left join data_center on vm_instance.data_center_id=data_center.id " + + "left join host on vm_instance.host_id=host.id " + + "left join vm_template on vm_instance.vm_template_id=vm_template.id " + + "left join user_vm on vm_instance.id=user_vm.id " + + "left join vm_template iso on iso.id=user_vm.iso_id " + + "left join service_offering on vm_instance.service_offering_id=service_offering.id " + + "left join disk_offering on vm_instance.service_offering_id=disk_offering.id " + + "left join volumes on vm_instance.id=volumes.instance_id " + + "left join storage_pool on volumes.pool_id=storage_pool.id " + + "left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " + + "left join security_group on security_group_vm_map.security_group_id=security_group.id " + + "left join nics on vm_instance.id=nics.instance_id " + + "left join networks on nics.network_id=networks.id " + + "left join user_ip_address on user_ip_address.vm_id=vm_instance.id " + + "where vm_instance.id in ("; + + private static final int VM_DETAILS_BATCH_SIZE=100; + + protected final UserVmDetailsDaoImpl _detailsDao = ComponentLocator.inject(UserVmDetailsDaoImpl.class); + protected final NicDaoImpl _nicDao = ComponentLocator.inject(NicDaoImpl.class); + + protected UserVmDaoImpl() { + AccountSearch = createSearchBuilder(); + AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountSearch.done(); + + HostSearch = createSearchBuilder(); + HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostSearch.done(); + + LastHostSearch = createSearchBuilder(); + LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ); + LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ); + LastHostSearch.done(); + + HostUpSearch = createSearchBuilder(); + HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN); + HostUpSearch.done(); + + HostRunningSearch = createSearchBuilder(); + HostRunningSearch.and("host", HostRunningSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostRunningSearch.and("state", HostRunningSearch.entity().getState(), SearchCriteria.Op.EQ); + HostRunningSearch.done(); + + AccountPodSearch = createSearchBuilder(); + AccountPodSearch.and("account", AccountPodSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountPodSearch.and("pod", AccountPodSearch.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); + AccountPodSearch.done(); + + AccountDataCenterSearch = createSearchBuilder(); + AccountDataCenterSearch.and("account", AccountDataCenterSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountDataCenterSearch.and("dc", AccountDataCenterSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); + AccountDataCenterSearch.done(); + + StateChangeSearch = createSearchBuilder(); + StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); + StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); + StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ); + StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ); + StateChangeSearch.done(); + + DestroySearch = createSearchBuilder(); + DestroySearch.and("state", DestroySearch.entity().getState(), SearchCriteria.Op.IN); + DestroySearch.and("updateTime", DestroySearch.entity().getUpdateTime(), SearchCriteria.Op.LT); + DestroySearch.done(); + + AccountHostSearch = createSearchBuilder(); + AccountHostSearch.and("accountId", AccountHostSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountHostSearch.and("hostId", AccountHostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + AccountHostSearch.done(); + + CountByAccountPod = createSearchBuilder(Long.class); + CountByAccountPod.select(null, Func.COUNT, null); + CountByAccountPod.and("account", CountByAccountPod.entity().getAccountId(), SearchCriteria.Op.EQ); + CountByAccountPod.and("pod", CountByAccountPod.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); + CountByAccountPod.done(); + + CountByAccount = createSearchBuilder(Long.class); + CountByAccount.select(null, Func.COUNT, null); + CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); + CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ); + CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); + CountByAccount.done(); + + + SearchBuilder nicSearch = _nicDao.createSearchBuilder(); + nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); + nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); + + AccountDataCenterVirtualSearch = createSearchBuilder(); + AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); + AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + AccountDataCenterVirtualSearch.done(); + + + _updateTimeAttr = _allAttributes.get("updateTime"); + assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; + } + + @Override + public List listByAccountAndPod(long accountId, long podId) { + SearchCriteria sc = AccountPodSearch.create(); + sc.setParameters("account", accountId); + sc.setParameters("pod", podId); + + return listIncludingRemovedBy(sc); + } + + @Override + public List listByAccountAndDataCenter(long accountId, long dcId) { + SearchCriteria sc = AccountDataCenterSearch.create(); + sc.setParameters("account", accountId); + sc.setParameters("dc", dcId); + + return listIncludingRemovedBy(sc); + } + + @Override + public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData) { + UserVmVO vo = createForUpdate(); + vo.setDisplayName(displayName); + vo.setHaEnabled(enable); + vo.setGuestOSId(osTypeId); + vo.setUserData(userData); + update(id, vo); + } + + @Override + public List findDestroyedVms(Date date) { + SearchCriteria sc = DestroySearch.create(); + sc.setParameters("state", State.Destroyed, State.Expunging, State.Error); + sc.setParameters("updateTime", date); + + return listBy(sc); + } + + @Override + public List listByAccountId(long id) { + SearchCriteria sc = AccountSearch.create(); + sc.setParameters("account", id); + return listBy(sc); + } + + @Override + public List listByHostId(Long id) { + SearchCriteria sc = HostSearch.create(); + sc.setParameters("host", id); + + return listBy(sc); + } + + @Override + public List listUpByHostId(Long hostId) { + SearchCriteria sc = HostUpSearch.create(); + sc.setParameters("host", hostId); + sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging}); + return listBy(sc); + } + + @Override + public List listRunningByHostId(long hostId) { + SearchCriteria sc = HostRunningSearch.create(); + sc.setParameters("host", hostId); + sc.setParameters("state", State.Running); + + return listBy(sc); + } + + @Override + public List listVirtualNetworkInstancesByAcctAndZone(long accountId, long dcId, long networkId) { + + SearchCriteria sc = AccountDataCenterVirtualSearch.create(); + sc.setParameters("account", accountId); + sc.setParameters("dc", dcId); + sc.setJoinParameters("nicSearch", "networkId", networkId); + + return listBy(sc); + } + + @Override + public List listByNetworkIdAndStates(long networkId, State... states) { + if (UserVmSearch == null) { + NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class); + SearchBuilder nicSearch = _nicDao.createSearchBuilder(); + nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); + nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); + + UserVmSearch = createSearchBuilder(); + UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN); + UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + UserVmSearch.done(); + } + + SearchCriteria sc = UserVmSearch.create(); + if (states != null && states.length != 0) { + sc.setParameters("states", (Object[]) states); + } + sc.setJoinParameters("nicSearch", "networkId", networkId); + + return listBy(sc); + } + + @Override + public List listByLastHostId(Long hostId) { + SearchCriteria sc = LastHostSearch.create(); + sc.setParameters("lastHost", hostId); + sc.setParameters("state", State.Stopped); + return listBy(sc); + } + + @Override + public List listByAccountIdAndHostId(long accountId, long hostId) { + SearchCriteria sc = AccountHostSearch.create(); + sc.setParameters("hostId", hostId); + sc.setParameters("accountId", accountId); + return listBy(sc); + } + + @Override + public void loadDetails(UserVmVO vm) { + Map details = _detailsDao.findDetails(vm.getId()); + vm.setDetails(details); + } + + @Override + public void saveDetails(UserVmVO vm) { + Map details = vm.getDetails(); + if (details == null) { + return; + } + _detailsDao.persist(vm.getId(), details); + } + + @Override + public List listPodIdsHavingVmsforAccount(long zoneId, long accountId){ + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + + try { + String sql = LIST_PODS_HAVING_VMS_FOR_ACCOUNT; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, zoneId); + pstmt.setLong(2, accountId); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + result.add(rs.getLong(1)); + } + return result; + } catch (SQLException e) { + throw new CloudRuntimeException("DB Exception on: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e); + } catch (Throwable e) { + throw new CloudRuntimeException("Caught: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e); + } + } + + @Override + public Hashtable listVmDetails(Hashtable userVmDataHash){ + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + + try { + int curr_index=0; + + List userVmDataList = new ArrayList(userVmDataHash.values()); + + if (userVmDataList.size() > VM_DETAILS_BATCH_SIZE){ + pstmt = txn.prepareStatement(VM_DETAILS + getQueryBatchAppender(VM_DETAILS_BATCH_SIZE)); + while ( (curr_index + VM_DETAILS_BATCH_SIZE) <= userVmDataList.size()){ + // set the vars value + for (int k=1,j=curr_index;j 0){ + userVmData.setGroupId(grp_id); + userVmData.setGroup(rs.getString("instance_group.name")); + } + + //"data_center.id, data_center.name, host.id, host.name, vm_template.id, vm_template.name, vm_template.display_text, vm_template.enable_password, + userVmData.setZoneId(rs.getLong("data_center.id")); + userVmData.setZoneName(rs.getString("data_center.name")); + + userVmData.setHostId(rs.getLong("host.id")); + userVmData.setHostName(rs.getString("host.name")); + + long template_id = rs.getLong("vm_template.id"); + if (template_id > 0){ + userVmData.setTemplateId(template_id); + userVmData.setTemplateName(rs.getString("vm_template.name")); + userVmData.setTemplateDisplayText(rs.getString("vm_template.display_text")); + userVmData.setPasswordEnabled(rs.getBoolean("vm_template.enable_password")); + } + else { + userVmData.setTemplateId(-1L); + userVmData.setTemplateName("ISO Boot"); + userVmData.setTemplateDisplayText("ISO Boot"); + userVmData.setPasswordEnabled(false); + } + + long iso_id = rs.getLong("iso.id"); + if (iso_id > 0){ + userVmData.setIsoId(iso_id); + userVmData.setIsoName(rs.getString("iso.name")); + } + + + //service_offering.id, disk_offering.name, " + //"service_offering.cpu, service_offering.speed, service_offering.ram_size, + userVmData.setServiceOfferingId(rs.getLong("service_offering.id")); + userVmData.setServiceOfferingName(rs.getString("disk_offering.name")); + userVmData.setCpuNumber(rs.getInt("service_offering.cpu")); + userVmData.setCpuSpeed(rs.getInt("service_offering.speed")); + userVmData.setMemory(rs.getInt("service_offering.ram_size")); + + // volumes.device_id, volumes.volume_type, + long vol_id = rs.getLong("volumes.id"); + if (vol_id > 0){ + userVmData.setRootDeviceId(rs.getLong("volumes.device_id")); + userVmData.setRootDeviceType(rs.getString("volumes.volume_type")); + // storage pool + long pool_id = rs.getLong("storage_pool.id"); + if (pool_id > 0){ + userVmData.setRootDeviceType(rs.getString("storage_pool.pool_type")); + } + else { + userVmData.setRootDeviceType("Not created"); + } + } + userVmData.setInitialized(); + } + + + Long securityGroupId = rs.getLong("security_group.id"); + if (securityGroupId != null && securityGroupId.longValue() != 0){ + SecurityGroupData resp = userVmData.newSecurityGroupData(); + resp.setId(rs.getLong("security_group.id")); + resp.setName(rs.getString("security_group.name")); + resp.setDescription(rs.getString("security_group.description")); + resp.setObjectName("securitygroup"); + userVmData.addSecurityGroup(resp); + } + + long nic_id = rs.getLong("nics.id"); + if (nic_id > 0){ + NicData nicResponse = userVmData.newNicData(); + nicResponse.setId(nic_id); + nicResponse.setIpaddress(rs.getString("nics.ip4_address")); + nicResponse.setGateway(rs.getString("nics.gateway")); + nicResponse.setNetmask(rs.getString("nics.netmask")); + nicResponse.setNetworkid(rs.getLong("nics.network_id")); + nicResponse.setMacAddress(rs.getString("nics.mac_address")); + + int account_type = rs.getInt("account.type"); + if (account_type == Account.ACCOUNT_TYPE_ADMIN) { + nicResponse.setBroadcastUri(rs.getString("nics.broadcast_uri")); + nicResponse.setIsolationUri(rs.getString("nics.isolation_uri")); + } + + + nicResponse.setTrafficType(rs.getString("networks.traffic_type")); + nicResponse.setType(rs.getString("networks.guest_type")); + nicResponse.setIsDefault(rs.getBoolean("nics.default_nic")); + nicResponse.setObjectName("nic"); + userVmData.addNic(nicResponse); + } + + long publicIpId = rs.getLong("user_ip_address.id"); + if (publicIpId > 0){ + userVmData.setPublicIpId(publicIpId); + userVmData.setPublicIp(rs.getString("user_ip_address.public_ip_address")); + } + + return userVmData; + } + + public String getQueryBatchAppender(int count){ + StringBuilder sb = new StringBuilder(); + for (int i=0;i sc = CountByAccount.create(); + sc.setParameters("account", accountId); + sc.setParameters("type", VirtualMachine.Type.User); + sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging}); + return customSearch(sc, null).get(0); + } + + +} diff --git a/server/test/async-job-component.xml b/server/test/async-job-component.xml index 5b00136922b..a93fa198c30 100644 --- a/server/test/async-job-component.xml +++ b/server/test/async-job-component.xml @@ -1,185 +1,185 @@ - - - - - - - - - - 50 - -1 - - - - - 50 - -1 - - - 50 - -1 - - - - - - - 50 - -1 - routing - - - 5000 - 300 - - - - 50 - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2 - - - 2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + 50 + -1 + + + + + 50 + -1 + + + 50 + -1 + + + + + + + 50 + -1 + routing + + + 5000 + 300 + + + + 50 + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + + + 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/test/com/cloud/agent/manager/ResourceManagerTest.java b/server/test/com/cloud/agent/manager/ResourceManagerTest.java index 57433ad191e..254f79a5406 100755 --- a/server/test/com/cloud/agent/manager/ResourceManagerTest.java +++ b/server/test/com/cloud/agent/manager/ResourceManagerTest.java @@ -10,367 +10,367 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent.manager; - -import java.io.Serializable; -import java.lang.reflect.Field; - -import junit.framework.TestCase; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; - -import com.cloud.alert.AlertManagerImpl; -import com.cloud.alert.dao.AlertDaoImpl; -import com.cloud.api.BaseCmd; -import com.cloud.api.commands.CreatePodCmd; -import com.cloud.api.commands.CreateZoneCmd; -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.CapacityManagerImpl; -import com.cloud.capacity.dao.CapacityDaoImpl; -import com.cloud.certificate.dao.CertificateDaoImpl; -import com.cloud.cluster.CheckPointManagerImpl; -import com.cloud.cluster.ClusterFenceManagerImpl; -import com.cloud.cluster.ClusterManagerImpl; -import com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl; -import com.cloud.cluster.dao.ManagementServerHostDaoImpl; -import com.cloud.cluster.dao.StackMaidDaoImpl; -import com.cloud.configuration.ConfigurationManagerImpl; -import com.cloud.configuration.ConfigurationService; -import com.cloud.configuration.dao.ConfigurationDaoImpl; -import com.cloud.configuration.dao.ResourceCountDaoImpl; -import com.cloud.configuration.dao.ResourceLimitDaoImpl; -import com.cloud.consoleproxy.ConsoleProxyManagerImpl; -import com.cloud.dao.EntityManagerImpl; -import com.cloud.dc.ClusterDetailsDaoImpl; -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.DcDetailsDaoImpl; -import com.cloud.dc.dao.HostPodDaoImpl; -import com.cloud.dc.dao.PodVlanMapDaoImpl; -import com.cloud.dc.dao.VlanDaoImpl; -import com.cloud.domain.dao.DomainDaoImpl; -import com.cloud.event.dao.EventDaoImpl; -import com.cloud.event.dao.UsageEventDaoImpl; -import com.cloud.ha.HighAvailabilityManagerImpl; -import com.cloud.ha.dao.HighAvailabilityDaoImpl; -import com.cloud.host.dao.HostDaoImpl; -import com.cloud.host.dao.HostDetailsDaoImpl; -import com.cloud.host.dao.HostTagsDaoImpl; -import com.cloud.hypervisor.HypervisorGuruManagerImpl; -import com.cloud.hypervisor.dao.HypervisorCapabilitiesDaoImpl; -import com.cloud.keystore.KeystoreDaoImpl; -import com.cloud.keystore.KeystoreManagerImpl; -import com.cloud.maint.UpgradeManagerImpl; -import com.cloud.maint.dao.AgentUpgradeDaoImpl; -import com.cloud.network.NetworkManagerImpl; -import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; -import com.cloud.network.dao.FirewallRulesDaoImpl; -import com.cloud.network.dao.IPAddressDaoImpl; -import com.cloud.network.dao.InlineLoadBalancerNicMapDaoImpl; -import com.cloud.network.dao.LoadBalancerDaoImpl; -import com.cloud.network.dao.LoadBalancerVMMapDaoImpl; -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.VpnUserDaoImpl; -import com.cloud.network.firewall.FirewallManagerImpl; -import com.cloud.network.lb.ElasticLoadBalancerManagerImpl; -import com.cloud.network.lb.LoadBalancingRulesManagerImpl; -import com.cloud.network.lb.dao.ElasticLbVmMapDaoImpl; -import com.cloud.network.ovs.OvsNetworkManagerImpl; -import com.cloud.network.ovs.OvsTunnelManagerImpl; -import com.cloud.network.ovs.dao.GreTunnelDaoImpl; -import com.cloud.network.ovs.dao.OvsTunnelAccountDaoImpl; -import com.cloud.network.ovs.dao.OvsTunnelDaoImpl; -import com.cloud.network.ovs.dao.OvsWorkDaoImpl; -import com.cloud.network.ovs.dao.VlanMappingDaoImpl; -import com.cloud.network.ovs.dao.VlanMappingDirtyDaoImpl; -import com.cloud.network.ovs.dao.VmFlowLogDaoImpl; -import com.cloud.network.router.VirtualNetworkApplianceManagerImpl; -import com.cloud.network.rules.RulesManagerImpl; -import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl; -import com.cloud.network.security.SecurityGroupManagerImpl2; -import com.cloud.network.security.dao.SecurityGroupDaoImpl; -import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl; -import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl; -import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl; -import com.cloud.network.security.dao.VmRulesetLogDaoImpl; -import com.cloud.network.vpn.RemoteAccessVpnManagerImpl; -import com.cloud.offerings.dao.NetworkOfferingDaoImpl; -import com.cloud.projects.ProjectManagerImpl; -import com.cloud.projects.dao.ProjectAccountDaoImpl; -import com.cloud.projects.dao.ProjectDaoImpl; -import com.cloud.resource.ResourceManagerImpl; -import com.cloud.resourcelimit.ResourceLimitManagerImpl; -import com.cloud.service.dao.ServiceOfferingDaoImpl; -import com.cloud.storage.OCFS2ManagerImpl; -import com.cloud.storage.StorageManagerImpl; -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.SnapshotPolicyDaoImpl; -import com.cloud.storage.dao.SnapshotScheduleDaoImpl; -import com.cloud.storage.dao.StoragePoolDaoImpl; -import com.cloud.storage.dao.StoragePoolHostDaoImpl; -import com.cloud.storage.dao.StoragePoolWorkDaoImpl; -import com.cloud.storage.dao.SwiftDaoImpl; -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.secondary.SecondaryStorageManagerImpl; -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.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.ComponentLocator; -import com.cloud.utils.component.ComponentLocator.ComponentInfo; -import com.cloud.utils.component.Manager; -import com.cloud.utils.component.MockComponentLocator; -import com.cloud.utils.db.GenericDao; -import com.cloud.vm.ClusteredVirtualMachineManagerImpl; -import com.cloud.vm.ItWorkDaoImpl; -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.UserVmDetailsDaoImpl; -import com.cloud.vm.dao.VMInstanceDaoImpl; - -public class ResourceManagerTest extends TestCase { - MockComponentLocator _locator; - private static final Logger s_logger = Logger.getLogger(ResourceManagerTest.class); - ConfigurationService _configService; - - @Override - @Before - public void setUp() throws Exception { - _locator = new MockComponentLocator("management-server"); - _locator.addDao("StackMaidDao", StackMaidDaoImpl.class); - _locator.addDao("VMTemplateZoneDao", VMTemplateZoneDaoImpl.class); - _locator.addDao("DomainRouterDao", DomainRouterDaoImpl.class); - _locator.addDao("HostDao", HostDaoImpl.class); - _locator.addDao("VMInstanceDao", VMInstanceDaoImpl.class); - _locator.addDao("UserVmDao", UserVmDaoImpl.class); - ComponentInfo> info = _locator.addDao("ServiceOfferingDao", ServiceOfferingDaoImpl.class); - info.addParameter("cache.size", "50"); - info.addParameter("cache.time.to.live", "600"); - info = _locator.addDao("DiskOfferingDao", DiskOfferingDaoImpl.class); - info.addParameter("cache.size", "50"); - info.addParameter("cache.time.to.live", "600"); - info = _locator.addDao("DataCenterDao", DataCenterDaoImpl.class); - info.addParameter("cache.size", "50"); - info.addParameter("cache.time.to.live", "600"); - info = _locator.addDao("HostPodDao", HostPodDaoImpl.class); - info.addParameter("cache.size", "50"); - info.addParameter("cache.time.to.live", "600"); - _locator.addDao("IPAddressDao", IPAddressDaoImpl.class); - info = _locator.addDao("VlanDao", VlanDaoImpl.class); - info.addParameter("cache.size", "30"); - info.addParameter("cache.time.to.live", "3600"); - _locator.addDao("PodVlanMapDao", PodVlanMapDaoImpl.class); - _locator.addDao("AccountVlanMapDao", AccountVlanMapDaoImpl.class); - _locator.addDao("VolumeDao", VolumeDaoImpl.class); - _locator.addDao("EventDao", EventDaoImpl.class); - info = _locator.addDao("UserDao", UserDaoImpl.class); - info.addParameter("cache.size", "5000"); - info.addParameter("cache.time.to.live", "300"); - _locator.addDao("UserStatisticsDao", UserStatisticsDaoImpl.class); - _locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class); - _locator.addDao("LoadBalancerDao", LoadBalancerDaoImpl.class); - _locator.addDao("NetworkRuleConfigDao", NetworkRuleConfigDaoImpl.class); - _locator.addDao("LoadBalancerVMMapDao", LoadBalancerVMMapDaoImpl.class); - _locator.addDao("DataCenterIpAddressDao", DataCenterIpAddressDaoImpl.class); - _locator.addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); - //_locator.addDao("IngressRuleDao", IngressRuleDaoImpl.class); - _locator.addDao("SecurityGroupVMMapDao", SecurityGroupVMMapDaoImpl.class); - _locator.addDao("SecurityGroupRulesDao", SecurityGroupRulesDaoImpl.class); - _locator.addDao("SecurityGroupWorkDao", SecurityGroupWorkDaoImpl.class); - _locator.addDao("VmRulesetLogDao", VmRulesetLogDaoImpl.class); - _locator.addDao("AlertDao", AlertDaoImpl.class); - _locator.addDao("CapacityDao", CapacityDaoImpl.class); - _locator.addDao("DomainDao", DomainDaoImpl.class); - _locator.addDao("AccountDao", AccountDaoImpl.class); - _locator.addDao("ResourceLimitDao", ResourceLimitDaoImpl.class); - _locator.addDao("ResourceCountDao", ResourceCountDaoImpl.class); - _locator.addDao("UserAccountDao", UserAccountDaoImpl.class); - _locator.addDao("VMTemplateHostDao", VMTemplateHostDaoImpl.class); - _locator.addDao("UploadDao", UploadDaoImpl.class); - _locator.addDao("VMTemplatePoolDao", VMTemplatePoolDaoImpl.class); - _locator.addDao("LaunchPermissionDao", LaunchPermissionDaoImpl.class); - _locator.addDao("ConfigurationDao", ConfigurationDaoImpl.class); - info = _locator.addDao("VMTemplateDao", VMTemplateDaoImpl.class); - info.addParameter("cache.size", "100"); - info.addParameter("cache.time.to.live", "600"); - info.addParameter("routing.uniquename", "routing"); - _locator.addDao("HighAvailabilityDao", HighAvailabilityDaoImpl.class); - _locator.addDao("ConsoleProxyDao", ConsoleProxyDaoImpl.class); - _locator.addDao("SecondaryStorageVmDao", SecondaryStorageVmDaoImpl.class); - _locator.addDao("ManagementServerHostDao", ManagementServerHostDaoImpl.class); - _locator.addDao("AgentUpgradeDao", AgentUpgradeDaoImpl.class); - _locator.addDao("SnapshotDao", SnapshotDaoImpl.class); - _locator.addDao("AsyncJobDao", AsyncJobDaoImpl.class); - _locator.addDao("SyncQueueDao", SyncQueueDaoImpl.class); - _locator.addDao("SyncQueueItemDao", SyncQueueItemDaoImpl.class); - _locator.addDao("GuestOSDao", GuestOSDaoImpl.class); - _locator.addDao("GuestOSCategoryDao", GuestOSCategoryDaoImpl.class); - _locator.addDao("StoragePoolDao", StoragePoolDaoImpl.class); - _locator.addDao("StoragePoolHostDao", StoragePoolHostDaoImpl.class); - _locator.addDao("DetailsDao", HostDetailsDaoImpl.class); - _locator.addDao("SnapshotPolicyDao", SnapshotPolicyDaoImpl.class); - _locator.addDao("SnapshotScheduleDao", SnapshotScheduleDaoImpl.class); - _locator.addDao("ClusterDao", ClusterDaoImpl.class); - _locator.addDao("CertificateDao", CertificateDaoImpl.class); - _locator.addDao("NetworkConfigurationDao", NetworkDaoImpl.class); - _locator.addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); - _locator.addDao("NicDao", NicDaoImpl.class); - _locator.addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); - _locator.addDao("InstanceGroupVMMapDao", InstanceGroupVMMapDaoImpl.class); - _locator.addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); - _locator.addDao("VpnUserDao", VpnUserDaoImpl.class); - _locator.addDao("ItWorkDao", ItWorkDaoImpl.class); - _locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class); - _locator.addDao("PortForwardingRulesDao", PortForwardingRulesDaoImpl.class); - _locator.addDao("FirewallRulesCidrsDao", FirewallRulesCidrsDaoImpl.class); - _locator.addDao("SSHKeyPairDao", SSHKeyPairDaoImpl.class); - _locator.addDao("UsageEventDao", UsageEventDaoImpl.class); - _locator.addDao("ClusterDetailsDao", ClusterDetailsDaoImpl.class); - _locator.addDao("UserVmDetailsDao", UserVmDetailsDaoImpl.class); - _locator.addDao("VlanMappingDao", VlanMappingDaoImpl.class); - _locator.addDao("VlanMappingDirtyDao", VlanMappingDirtyDaoImpl.class); - _locator.addDao("OvsWorkDao", OvsWorkDaoImpl.class); - _locator.addDao("VmFlowLogDao", VmFlowLogDaoImpl.class); - _locator.addDao("GreTunnelDao", GreTunnelDaoImpl.class); - _locator.addDao("OvsTunnelDao", OvsTunnelDaoImpl.class); - _locator.addDao("OvsTunnelAccountDao", OvsTunnelAccountDaoImpl.class); - _locator.addDao("StoragePoolWorkDao", StoragePoolWorkDaoImpl.class); - _locator.addDao("HostTagsDao", HostTagsDaoImpl.class); - _locator.addDao("NetworkDomainDao", NetworkDomainDaoImpl.class); - _locator.addDao("KeystoreDao", KeystoreDaoImpl.class); - _locator.addDao("DcDetailsDao", DcDetailsDaoImpl.class); - _locator.addDao("SwiftDao", SwiftDaoImpl.class); - _locator.addDao("AgentTransferMapDao", HostTransferMapDaoImpl.class); - _locator.addDao("ProjectDao", ProjectDaoImpl.class); - _locator.addDao("InlineLoadBalancerNicMapDao", InlineLoadBalancerNicMapDaoImpl.class); - _locator.addDao("ElasticLbVmMap", ElasticLbVmMapDaoImpl.class); - _locator.addDao("ProjectsAccountDao", ProjectAccountDaoImpl.class); - info = _locator.addDao("HypervisorCapabilitiesDao", HypervisorCapabilitiesDaoImpl.class); - info.addParameter("cache.size", "100"); - info.addParameter("cache.time.to.live", "600"); - - _locator.addManager("StackMaidManager", CheckPointManagerImpl.class); - _locator.addManager("account manager", AccountManagerImpl.class); - _locator.addManager("domain manager", DomainManagerImpl.class); - _locator.addManager("resource limit manager", ResourceLimitManagerImpl.class); - _locator.addManager("configuration manager", ConfigurationManagerImpl.class); - _locator.addManager("network manager", NetworkManagerImpl.class); - _locator.addManager("download manager", DownloadMonitorImpl.class); - _locator.addManager("upload manager", UploadMonitorImpl.class); - _locator.addManager("keystore manager", KeystoreManagerImpl.class); - _locator.addManager("secondary storage vm manager", SecondaryStorageManagerImpl.class); - _locator.addManager("vm manager", UserVmManagerImpl.class); - _locator.addManager("upgrade manager", UpgradeManagerImpl.class); - _locator.addManager("StorageManager", StorageManagerImpl.class); - _locator.addManager("SyncQueueManager", SyncQueueManagerImpl.class); - _locator.addManager("AsyncJobManager", AsyncJobManagerImpl.class); - _locator.addManager("AsyncJobExecutorContext", AsyncJobExecutorContextImpl.class); - _locator.addManager("HA Manager", HighAvailabilityManagerImpl.class); - _locator.addManager("Alert Manager", AlertManagerImpl.class); - _locator.addManager("Template Manager", TemplateManagerImpl.class); - _locator.addManager("Snapshot Manager", SnapshotManagerImpl.class); - _locator.addManager("SnapshotScheduler", SnapshotSchedulerImpl.class); - _locator.addManager("SecurityGroupManager", SecurityGroupManagerImpl2.class); - _locator.addManager("DomainRouterManager", VirtualNetworkApplianceManagerImpl.class); - _locator.addManager("EntityManager", EntityManagerImpl.class); - _locator.addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class); - _locator.addManager("RulesManager", RulesManagerImpl.class); - _locator.addManager("RemoteAccessVpnManager", RemoteAccessVpnManagerImpl.class); - _locator.addManager("OvsNetworkManager", OvsNetworkManagerImpl.class); - _locator.addManager("OvsTunnelManager", OvsTunnelManagerImpl.class); - _locator.addManager("Capacity Manager", CapacityManagerImpl.class); - _locator.addManager("Cluster Manager", ClusterManagerImpl.class); - _locator.addManager("VirtualMachineManager", ClusteredVirtualMachineManagerImpl.class); - _locator.addManager("HypervisorGuruManager", HypervisorGuruManagerImpl.class); - _locator.addManager("ClusterFenceManager", ClusterFenceManagerImpl.class); - _locator.addManager("ResourceManager", ResourceManagerImpl.class); - - _locator.addManager("OCFS2Manager", OCFS2ManagerImpl.class); - _locator.addManager("FirewallManager", FirewallManagerImpl.class); - ComponentInfo info1 = _locator.addManager("ConsoleProxyManager", ConsoleProxyManagerImpl.class); - info1.addParameter("consoleproxy.sslEnabled", "true"); - _locator.addManager("ClusteredAgentManager", ClusteredAgentManagerImpl.class); - _locator.addManager("ProjectManager", ProjectManagerImpl.class); - _locator.addManager("ElasticLoadBalancerManager", ElasticLoadBalancerManagerImpl.class); - - _locator.makeActive(null); - _configService = ComponentLocator.inject(ConfigurationManagerImpl.class); - } - - private void evaluateCmd(T cmd, String name, Object value) { - try { - Field f = cmd.getClass().getDeclaredField(name); - f.set(cmd, value); - } catch (Exception e) { - s_logger.debug("Unable to evaluate " + cmd.getClass().getName() + "." + name, e); - TestCase.fail(); - } - } - - private void createZone(String zoneName) { - CreateZoneCmd cZone = new CreateZoneCmd(); - evaluateCmd(cZone, "dns1", "10.223.110.254"); - evaluateCmd(cZone, "internalDns1", "10.223.110.254"); - evaluateCmd(cZone, "zoneName", zoneName); - evaluateCmd(cZone, "networkType", "Basic"); - evaluateCmd(cZone, "securitygroupenabled", false); - s_logger.info("Create zone:" + cZone.getZoneName()); - - _configService.createZone(cZone); - } - - private void createPod(String name) { - CreatePodCmd cPod = new CreatePodCmd(); - evaluateCmd(cPod, "netmask", "255.255.255.0"); - - } - - private void deploy100Hosts() { - createZone("test1"); - } - - public void testDeploy100Hosts() { - deploy100Hosts(); - } - - @Override - @After - public void tearDown() throws Exception { - } - -} +package com.cloud.agent.manager; + +import java.io.Serializable; +import java.lang.reflect.Field; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; + +import com.cloud.alert.AlertManagerImpl; +import com.cloud.alert.dao.AlertDaoImpl; +import com.cloud.api.BaseCmd; +import com.cloud.api.commands.CreatePodCmd; +import com.cloud.api.commands.CreateZoneCmd; +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.CapacityManagerImpl; +import com.cloud.capacity.dao.CapacityDaoImpl; +import com.cloud.certificate.dao.CertificateDaoImpl; +import com.cloud.cluster.CheckPointManagerImpl; +import com.cloud.cluster.ClusterFenceManagerImpl; +import com.cloud.cluster.ClusterManagerImpl; +import com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl; +import com.cloud.cluster.dao.ManagementServerHostDaoImpl; +import com.cloud.cluster.dao.StackMaidDaoImpl; +import com.cloud.configuration.ConfigurationManagerImpl; +import com.cloud.configuration.ConfigurationService; +import com.cloud.configuration.dao.ConfigurationDaoImpl; +import com.cloud.configuration.dao.ResourceCountDaoImpl; +import com.cloud.configuration.dao.ResourceLimitDaoImpl; +import com.cloud.consoleproxy.ConsoleProxyManagerImpl; +import com.cloud.dao.EntityManagerImpl; +import com.cloud.dc.ClusterDetailsDaoImpl; +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.DcDetailsDaoImpl; +import com.cloud.dc.dao.HostPodDaoImpl; +import com.cloud.dc.dao.PodVlanMapDaoImpl; +import com.cloud.dc.dao.VlanDaoImpl; +import com.cloud.domain.dao.DomainDaoImpl; +import com.cloud.event.dao.EventDaoImpl; +import com.cloud.event.dao.UsageEventDaoImpl; +import com.cloud.ha.HighAvailabilityManagerImpl; +import com.cloud.ha.dao.HighAvailabilityDaoImpl; +import com.cloud.host.dao.HostDaoImpl; +import com.cloud.host.dao.HostDetailsDaoImpl; +import com.cloud.host.dao.HostTagsDaoImpl; +import com.cloud.hypervisor.HypervisorGuruManagerImpl; +import com.cloud.hypervisor.dao.HypervisorCapabilitiesDaoImpl; +import com.cloud.keystore.KeystoreDaoImpl; +import com.cloud.keystore.KeystoreManagerImpl; +import com.cloud.maint.UpgradeManagerImpl; +import com.cloud.maint.dao.AgentUpgradeDaoImpl; +import com.cloud.network.NetworkManagerImpl; +import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; +import com.cloud.network.dao.FirewallRulesDaoImpl; +import com.cloud.network.dao.IPAddressDaoImpl; +import com.cloud.network.dao.InlineLoadBalancerNicMapDaoImpl; +import com.cloud.network.dao.LoadBalancerDaoImpl; +import com.cloud.network.dao.LoadBalancerVMMapDaoImpl; +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.VpnUserDaoImpl; +import com.cloud.network.firewall.FirewallManagerImpl; +import com.cloud.network.lb.ElasticLoadBalancerManagerImpl; +import com.cloud.network.lb.LoadBalancingRulesManagerImpl; +import com.cloud.network.lb.dao.ElasticLbVmMapDaoImpl; +import com.cloud.network.ovs.OvsNetworkManagerImpl; +import com.cloud.network.ovs.OvsTunnelManagerImpl; +import com.cloud.network.ovs.dao.GreTunnelDaoImpl; +import com.cloud.network.ovs.dao.OvsTunnelAccountDaoImpl; +import com.cloud.network.ovs.dao.OvsTunnelDaoImpl; +import com.cloud.network.ovs.dao.OvsWorkDaoImpl; +import com.cloud.network.ovs.dao.VlanMappingDaoImpl; +import com.cloud.network.ovs.dao.VlanMappingDirtyDaoImpl; +import com.cloud.network.ovs.dao.VmFlowLogDaoImpl; +import com.cloud.network.router.VirtualNetworkApplianceManagerImpl; +import com.cloud.network.rules.RulesManagerImpl; +import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl; +import com.cloud.network.security.SecurityGroupManagerImpl2; +import com.cloud.network.security.dao.SecurityGroupDaoImpl; +import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl; +import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl; +import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl; +import com.cloud.network.security.dao.VmRulesetLogDaoImpl; +import com.cloud.network.vpn.RemoteAccessVpnManagerImpl; +import com.cloud.offerings.dao.NetworkOfferingDaoImpl; +import com.cloud.projects.ProjectManagerImpl; +import com.cloud.projects.dao.ProjectAccountDaoImpl; +import com.cloud.projects.dao.ProjectDaoImpl; +import com.cloud.resource.ResourceManagerImpl; +import com.cloud.resourcelimit.ResourceLimitManagerImpl; +import com.cloud.service.dao.ServiceOfferingDaoImpl; +import com.cloud.storage.OCFS2ManagerImpl; +import com.cloud.storage.StorageManagerImpl; +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.SnapshotPolicyDaoImpl; +import com.cloud.storage.dao.SnapshotScheduleDaoImpl; +import com.cloud.storage.dao.StoragePoolDaoImpl; +import com.cloud.storage.dao.StoragePoolHostDaoImpl; +import com.cloud.storage.dao.StoragePoolWorkDaoImpl; +import com.cloud.storage.dao.SwiftDaoImpl; +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.secondary.SecondaryStorageManagerImpl; +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.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.ComponentLocator; +import com.cloud.utils.component.ComponentLocator.ComponentInfo; +import com.cloud.utils.component.Manager; +import com.cloud.utils.component.MockComponentLocator; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.ClusteredVirtualMachineManagerImpl; +import com.cloud.vm.ItWorkDaoImpl; +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.UserVmDetailsDaoImpl; +import com.cloud.vm.dao.VMInstanceDaoImpl; + +public class ResourceManagerTest extends TestCase { + MockComponentLocator _locator; + private static final Logger s_logger = Logger.getLogger(ResourceManagerTest.class); + ConfigurationService _configService; + + @Override + @Before + public void setUp() throws Exception { + _locator = new MockComponentLocator("management-server"); + _locator.addDao("StackMaidDao", StackMaidDaoImpl.class); + _locator.addDao("VMTemplateZoneDao", VMTemplateZoneDaoImpl.class); + _locator.addDao("DomainRouterDao", DomainRouterDaoImpl.class); + _locator.addDao("HostDao", HostDaoImpl.class); + _locator.addDao("VMInstanceDao", VMInstanceDaoImpl.class); + _locator.addDao("UserVmDao", UserVmDaoImpl.class); + ComponentInfo> info = _locator.addDao("ServiceOfferingDao", ServiceOfferingDaoImpl.class); + info.addParameter("cache.size", "50"); + info.addParameter("cache.time.to.live", "600"); + info = _locator.addDao("DiskOfferingDao", DiskOfferingDaoImpl.class); + info.addParameter("cache.size", "50"); + info.addParameter("cache.time.to.live", "600"); + info = _locator.addDao("DataCenterDao", DataCenterDaoImpl.class); + info.addParameter("cache.size", "50"); + info.addParameter("cache.time.to.live", "600"); + info = _locator.addDao("HostPodDao", HostPodDaoImpl.class); + info.addParameter("cache.size", "50"); + info.addParameter("cache.time.to.live", "600"); + _locator.addDao("IPAddressDao", IPAddressDaoImpl.class); + info = _locator.addDao("VlanDao", VlanDaoImpl.class); + info.addParameter("cache.size", "30"); + info.addParameter("cache.time.to.live", "3600"); + _locator.addDao("PodVlanMapDao", PodVlanMapDaoImpl.class); + _locator.addDao("AccountVlanMapDao", AccountVlanMapDaoImpl.class); + _locator.addDao("VolumeDao", VolumeDaoImpl.class); + _locator.addDao("EventDao", EventDaoImpl.class); + info = _locator.addDao("UserDao", UserDaoImpl.class); + info.addParameter("cache.size", "5000"); + info.addParameter("cache.time.to.live", "300"); + _locator.addDao("UserStatisticsDao", UserStatisticsDaoImpl.class); + _locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class); + _locator.addDao("LoadBalancerDao", LoadBalancerDaoImpl.class); + _locator.addDao("NetworkRuleConfigDao", NetworkRuleConfigDaoImpl.class); + _locator.addDao("LoadBalancerVMMapDao", LoadBalancerVMMapDaoImpl.class); + _locator.addDao("DataCenterIpAddressDao", DataCenterIpAddressDaoImpl.class); + _locator.addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); + //_locator.addDao("IngressRuleDao", IngressRuleDaoImpl.class); + _locator.addDao("SecurityGroupVMMapDao", SecurityGroupVMMapDaoImpl.class); + _locator.addDao("SecurityGroupRulesDao", SecurityGroupRulesDaoImpl.class); + _locator.addDao("SecurityGroupWorkDao", SecurityGroupWorkDaoImpl.class); + _locator.addDao("VmRulesetLogDao", VmRulesetLogDaoImpl.class); + _locator.addDao("AlertDao", AlertDaoImpl.class); + _locator.addDao("CapacityDao", CapacityDaoImpl.class); + _locator.addDao("DomainDao", DomainDaoImpl.class); + _locator.addDao("AccountDao", AccountDaoImpl.class); + _locator.addDao("ResourceLimitDao", ResourceLimitDaoImpl.class); + _locator.addDao("ResourceCountDao", ResourceCountDaoImpl.class); + _locator.addDao("UserAccountDao", UserAccountDaoImpl.class); + _locator.addDao("VMTemplateHostDao", VMTemplateHostDaoImpl.class); + _locator.addDao("UploadDao", UploadDaoImpl.class); + _locator.addDao("VMTemplatePoolDao", VMTemplatePoolDaoImpl.class); + _locator.addDao("LaunchPermissionDao", LaunchPermissionDaoImpl.class); + _locator.addDao("ConfigurationDao", ConfigurationDaoImpl.class); + info = _locator.addDao("VMTemplateDao", VMTemplateDaoImpl.class); + info.addParameter("cache.size", "100"); + info.addParameter("cache.time.to.live", "600"); + info.addParameter("routing.uniquename", "routing"); + _locator.addDao("HighAvailabilityDao", HighAvailabilityDaoImpl.class); + _locator.addDao("ConsoleProxyDao", ConsoleProxyDaoImpl.class); + _locator.addDao("SecondaryStorageVmDao", SecondaryStorageVmDaoImpl.class); + _locator.addDao("ManagementServerHostDao", ManagementServerHostDaoImpl.class); + _locator.addDao("AgentUpgradeDao", AgentUpgradeDaoImpl.class); + _locator.addDao("SnapshotDao", SnapshotDaoImpl.class); + _locator.addDao("AsyncJobDao", AsyncJobDaoImpl.class); + _locator.addDao("SyncQueueDao", SyncQueueDaoImpl.class); + _locator.addDao("SyncQueueItemDao", SyncQueueItemDaoImpl.class); + _locator.addDao("GuestOSDao", GuestOSDaoImpl.class); + _locator.addDao("GuestOSCategoryDao", GuestOSCategoryDaoImpl.class); + _locator.addDao("StoragePoolDao", StoragePoolDaoImpl.class); + _locator.addDao("StoragePoolHostDao", StoragePoolHostDaoImpl.class); + _locator.addDao("DetailsDao", HostDetailsDaoImpl.class); + _locator.addDao("SnapshotPolicyDao", SnapshotPolicyDaoImpl.class); + _locator.addDao("SnapshotScheduleDao", SnapshotScheduleDaoImpl.class); + _locator.addDao("ClusterDao", ClusterDaoImpl.class); + _locator.addDao("CertificateDao", CertificateDaoImpl.class); + _locator.addDao("NetworkConfigurationDao", NetworkDaoImpl.class); + _locator.addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); + _locator.addDao("NicDao", NicDaoImpl.class); + _locator.addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); + _locator.addDao("InstanceGroupVMMapDao", InstanceGroupVMMapDaoImpl.class); + _locator.addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); + _locator.addDao("VpnUserDao", VpnUserDaoImpl.class); + _locator.addDao("ItWorkDao", ItWorkDaoImpl.class); + _locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class); + _locator.addDao("PortForwardingRulesDao", PortForwardingRulesDaoImpl.class); + _locator.addDao("FirewallRulesCidrsDao", FirewallRulesCidrsDaoImpl.class); + _locator.addDao("SSHKeyPairDao", SSHKeyPairDaoImpl.class); + _locator.addDao("UsageEventDao", UsageEventDaoImpl.class); + _locator.addDao("ClusterDetailsDao", ClusterDetailsDaoImpl.class); + _locator.addDao("UserVmDetailsDao", UserVmDetailsDaoImpl.class); + _locator.addDao("VlanMappingDao", VlanMappingDaoImpl.class); + _locator.addDao("VlanMappingDirtyDao", VlanMappingDirtyDaoImpl.class); + _locator.addDao("OvsWorkDao", OvsWorkDaoImpl.class); + _locator.addDao("VmFlowLogDao", VmFlowLogDaoImpl.class); + _locator.addDao("GreTunnelDao", GreTunnelDaoImpl.class); + _locator.addDao("OvsTunnelDao", OvsTunnelDaoImpl.class); + _locator.addDao("OvsTunnelAccountDao", OvsTunnelAccountDaoImpl.class); + _locator.addDao("StoragePoolWorkDao", StoragePoolWorkDaoImpl.class); + _locator.addDao("HostTagsDao", HostTagsDaoImpl.class); + _locator.addDao("NetworkDomainDao", NetworkDomainDaoImpl.class); + _locator.addDao("KeystoreDao", KeystoreDaoImpl.class); + _locator.addDao("DcDetailsDao", DcDetailsDaoImpl.class); + _locator.addDao("SwiftDao", SwiftDaoImpl.class); + _locator.addDao("AgentTransferMapDao", HostTransferMapDaoImpl.class); + _locator.addDao("ProjectDao", ProjectDaoImpl.class); + _locator.addDao("InlineLoadBalancerNicMapDao", InlineLoadBalancerNicMapDaoImpl.class); + _locator.addDao("ElasticLbVmMap", ElasticLbVmMapDaoImpl.class); + _locator.addDao("ProjectsAccountDao", ProjectAccountDaoImpl.class); + info = _locator.addDao("HypervisorCapabilitiesDao", HypervisorCapabilitiesDaoImpl.class); + info.addParameter("cache.size", "100"); + info.addParameter("cache.time.to.live", "600"); + + _locator.addManager("StackMaidManager", CheckPointManagerImpl.class); + _locator.addManager("account manager", AccountManagerImpl.class); + _locator.addManager("domain manager", DomainManagerImpl.class); + _locator.addManager("resource limit manager", ResourceLimitManagerImpl.class); + _locator.addManager("configuration manager", ConfigurationManagerImpl.class); + _locator.addManager("network manager", NetworkManagerImpl.class); + _locator.addManager("download manager", DownloadMonitorImpl.class); + _locator.addManager("upload manager", UploadMonitorImpl.class); + _locator.addManager("keystore manager", KeystoreManagerImpl.class); + _locator.addManager("secondary storage vm manager", SecondaryStorageManagerImpl.class); + _locator.addManager("vm manager", UserVmManagerImpl.class); + _locator.addManager("upgrade manager", UpgradeManagerImpl.class); + _locator.addManager("StorageManager", StorageManagerImpl.class); + _locator.addManager("SyncQueueManager", SyncQueueManagerImpl.class); + _locator.addManager("AsyncJobManager", AsyncJobManagerImpl.class); + _locator.addManager("AsyncJobExecutorContext", AsyncJobExecutorContextImpl.class); + _locator.addManager("HA Manager", HighAvailabilityManagerImpl.class); + _locator.addManager("Alert Manager", AlertManagerImpl.class); + _locator.addManager("Template Manager", TemplateManagerImpl.class); + _locator.addManager("Snapshot Manager", SnapshotManagerImpl.class); + _locator.addManager("SnapshotScheduler", SnapshotSchedulerImpl.class); + _locator.addManager("SecurityGroupManager", SecurityGroupManagerImpl2.class); + _locator.addManager("DomainRouterManager", VirtualNetworkApplianceManagerImpl.class); + _locator.addManager("EntityManager", EntityManagerImpl.class); + _locator.addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class); + _locator.addManager("RulesManager", RulesManagerImpl.class); + _locator.addManager("RemoteAccessVpnManager", RemoteAccessVpnManagerImpl.class); + _locator.addManager("OvsNetworkManager", OvsNetworkManagerImpl.class); + _locator.addManager("OvsTunnelManager", OvsTunnelManagerImpl.class); + _locator.addManager("Capacity Manager", CapacityManagerImpl.class); + _locator.addManager("Cluster Manager", ClusterManagerImpl.class); + _locator.addManager("VirtualMachineManager", ClusteredVirtualMachineManagerImpl.class); + _locator.addManager("HypervisorGuruManager", HypervisorGuruManagerImpl.class); + _locator.addManager("ClusterFenceManager", ClusterFenceManagerImpl.class); + _locator.addManager("ResourceManager", ResourceManagerImpl.class); + + _locator.addManager("OCFS2Manager", OCFS2ManagerImpl.class); + _locator.addManager("FirewallManager", FirewallManagerImpl.class); + ComponentInfo info1 = _locator.addManager("ConsoleProxyManager", ConsoleProxyManagerImpl.class); + info1.addParameter("consoleproxy.sslEnabled", "true"); + _locator.addManager("ClusteredAgentManager", ClusteredAgentManagerImpl.class); + _locator.addManager("ProjectManager", ProjectManagerImpl.class); + _locator.addManager("ElasticLoadBalancerManager", ElasticLoadBalancerManagerImpl.class); + + _locator.makeActive(null); + _configService = ComponentLocator.inject(ConfigurationManagerImpl.class); + } + + private void evaluateCmd(T cmd, String name, Object value) { + try { + Field f = cmd.getClass().getDeclaredField(name); + f.set(cmd, value); + } catch (Exception e) { + s_logger.debug("Unable to evaluate " + cmd.getClass().getName() + "." + name, e); + TestCase.fail(); + } + } + + private void createZone(String zoneName) { + CreateZoneCmd cZone = new CreateZoneCmd(); + evaluateCmd(cZone, "dns1", "10.223.110.254"); + evaluateCmd(cZone, "internalDns1", "10.223.110.254"); + evaluateCmd(cZone, "zoneName", zoneName); + evaluateCmd(cZone, "networkType", "Basic"); + evaluateCmd(cZone, "securitygroupenabled", false); + s_logger.info("Create zone:" + cZone.getZoneName()); + + _configService.createZone(cZone); + } + + private void createPod(String name) { + CreatePodCmd cPod = new CreatePodCmd(); + evaluateCmd(cPod, "netmask", "255.255.255.0"); + + } + + private void deploy100Hosts() { + createZone("test1"); + } + + public void testDeploy100Hosts() { + deploy100Hosts(); + } + + @Override + @After + public void tearDown() throws Exception { + } + +} diff --git a/server/test/com/cloud/agent/manager/SearchCriteria2Test.java b/server/test/com/cloud/agent/manager/SearchCriteria2Test.java index de008a10172..6bebcd69958 100755 --- a/server/test/com/cloud/agent/manager/SearchCriteria2Test.java +++ b/server/test/com/cloud/agent/manager/SearchCriteria2Test.java @@ -10,86 +10,86 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent.manager; - -import java.util.List; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; - -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDaoImpl; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.MockComponentLocator; -import com.cloud.utils.db.DbTestUtils; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.dao.VMInstanceDao; -import com.cloud.vm.dao.VMInstanceDaoImpl; - -import junit.framework.TestCase; - -public class SearchCriteria2Test extends TestCase { - private static final Logger s_logger = Logger.getLogger(SearchCriteria2Test.class); - - @Override - @Before - public void setUp() throws Exception { - DbTestUtils.executeScript("cleanup.sql", false, true); - MockComponentLocator locator = new MockComponentLocator("management-server"); - locator.addDao("HostDao", HostDaoImpl.class); - locator.addDao("VmInstance", VMInstanceDaoImpl.class); - s_logger.debug("Finding sample data from 2.1.12"); - DbTestUtils.executeScript("fake", false, true); - } - - public void testSearch() { - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - - HostDao _hostDao = locator.inject(HostDaoImpl.class); - VMInstanceDao _vmDao = locator.inject(VMInstanceDaoImpl.class); - - - s_logger.debug("Test seraching host:"); - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Disconnected); - List ups = sc.list(); - for (HostVO vo : ups) { - s_logger.info("Host id: " + vo.getId() + " is Disconnected"); - } - - SearchCriteriaService sc1 = SearchCriteria2.create(VMInstanceVO.class); - sc1.addAnd(sc1.getEntity().getState(), Op.EQ, VirtualMachine.State.Running); - List vms = sc1.list(); - for (VMInstanceVO vm : vms) { - s_logger.info("Vm name:" + vm.getInstanceName()); - } - - sc1 = SearchCriteria2.create(VMInstanceVO.class); - sc1.addAnd(sc1.getEntity().getInstanceName(), Op.EQ, "s-1-TEST"); - VMInstanceVO vo = sc1.find(); - s_logger.info("SSVM name is " + vo.getInstanceName()); - - SearchCriteriaService sc3 = SearchCriteria2.create(HostVO.class, Long.class); - sc3.selectField(sc3.getEntity().getId()); - sc3.addAnd(sc3.getEntity().getStatus(), Op.EQ, Status.Disconnected); - sc3.addAnd(sc3.getEntity().getType(), Op.EQ, Host.Type.Routing); - List hostIds = sc3.list(); - for (Long id : hostIds) { - s_logger.info("Host Id is " + id); - } - } - - @Override - @After - public void tearDown() throws Exception { - } - -} +package com.cloud.agent.manager; + +import java.util.List; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; + +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.Status; +import com.cloud.host.dao.HostDao; +import com.cloud.host.dao.HostDaoImpl; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.MockComponentLocator; +import com.cloud.utils.db.DbTestUtils; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.dao.VMInstanceDaoImpl; + +import junit.framework.TestCase; + +public class SearchCriteria2Test extends TestCase { + private static final Logger s_logger = Logger.getLogger(SearchCriteria2Test.class); + + @Override + @Before + public void setUp() throws Exception { + DbTestUtils.executeScript("cleanup.sql", false, true); + MockComponentLocator locator = new MockComponentLocator("management-server"); + locator.addDao("HostDao", HostDaoImpl.class); + locator.addDao("VmInstance", VMInstanceDaoImpl.class); + s_logger.debug("Finding sample data from 2.1.12"); + DbTestUtils.executeScript("fake", false, true); + } + + public void testSearch() { + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + + HostDao _hostDao = locator.inject(HostDaoImpl.class); + VMInstanceDao _vmDao = locator.inject(VMInstanceDaoImpl.class); + + + s_logger.debug("Test seraching host:"); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Disconnected); + List ups = sc.list(); + for (HostVO vo : ups) { + s_logger.info("Host id: " + vo.getId() + " is Disconnected"); + } + + SearchCriteriaService sc1 = SearchCriteria2.create(VMInstanceVO.class); + sc1.addAnd(sc1.getEntity().getState(), Op.EQ, VirtualMachine.State.Running); + List vms = sc1.list(); + for (VMInstanceVO vm : vms) { + s_logger.info("Vm name:" + vm.getInstanceName()); + } + + sc1 = SearchCriteria2.create(VMInstanceVO.class); + sc1.addAnd(sc1.getEntity().getInstanceName(), Op.EQ, "s-1-TEST"); + VMInstanceVO vo = sc1.find(); + s_logger.info("SSVM name is " + vo.getInstanceName()); + + SearchCriteriaService sc3 = SearchCriteria2.create(HostVO.class, Long.class); + sc3.selectField(sc3.getEntity().getId()); + sc3.addAnd(sc3.getEntity().getStatus(), Op.EQ, Status.Disconnected); + sc3.addAnd(sc3.getEntity().getType(), Op.EQ, Host.Type.Routing); + List hostIds = sc3.list(); + for (Long id : hostIds) { + s_logger.info("Host Id is " + id); + } + } + + @Override + @After + public void tearDown() throws Exception { + } + +} diff --git a/server/test/com/cloud/async/CleanupDelegate.java b/server/test/com/cloud/async/CleanupDelegate.java index 7119038f1e0..a68d8bc3b71 100644 --- a/server/test/com/cloud/async/CleanupDelegate.java +++ b/server/test/com/cloud/async/CleanupDelegate.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - -import org.apache.log4j.Logger; - -public class CleanupDelegate implements com.cloud.utils.CleanupDelegate { - private static final Logger s_logger = Logger.getLogger(CleanupDelegate.class); - - @Override - public boolean cleanup(String param, Object managerContext) { - s_logger.info("Action called with param: " + param); - return true; - } -} +package com.cloud.async; + +import org.apache.log4j.Logger; + +public class CleanupDelegate implements com.cloud.utils.CleanupDelegate { + private static final Logger s_logger = Logger.getLogger(CleanupDelegate.class); + + @Override + public boolean cleanup(String param, Object managerContext) { + s_logger.info("Action called with param: " + param); + return true; + } +} diff --git a/server/test/com/cloud/async/TestAsync.java b/server/test/com/cloud/async/TestAsync.java index 6f937c03e2c..c8f1b574e1f 100644 --- a/server/test/com/cloud/async/TestAsync.java +++ b/server/test/com/cloud/async/TestAsync.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; -import java.util.List; + +import java.util.List; import org.apache.log4j.Logger; - -import junit.framework.Assert; - + +import junit.framework.Assert; + import com.cloud.async.AsyncJobVO; import com.cloud.cluster.StackMaid; import com.cloud.cluster.CheckPointVO; @@ -30,102 +30,102 @@ import com.cloud.utils.Pair; import com.cloud.utils.db.Transaction; import com.cloud.utils.testcase.Log4jEnabledTestCase; - + public class TestAsync extends Log4jEnabledTestCase { private static final Logger s_logger = Logger.getLogger(TestAsync.class); - /* - public static class SampleAsyncResult { - @Param(name="name", propName="name") - private final String _name; - - @Param - private final int count; - - public SampleAsyncResult(String name, int count) { - _name = name; - this.count = count; - } - - public String getName() { return _name; } - public int getCount() { return count; } - } + /* + public static class SampleAsyncResult { + @Param(name="name", propName="name") + private final String _name; + + @Param + private final int count; + + public SampleAsyncResult(String name, int count) { + _name = name; + this.count = count; + } + + public String getName() { return _name; } + public int getCount() { return count; } + } - public void testDao() { - AsyncJobDao dao = new AsyncJobDaoImpl(); - AsyncJobVO job = new AsyncJobVO(1, 1, "TestCmd", null); - job.setInstanceType("user_vm"); - job.setInstanceId(1000L); - - char[] buf = new char[1024]; - for(int i = 0; i < 1024; i++) - buf[i] = 'a'; - - job.setResult(new String(buf)); - dao.persist(job); - - AsyncJobVO jobVerify = dao.findById(job.getId()); - - Assert.assertTrue(jobVerify.getCmd().equals(job.getCmd())); - Assert.assertTrue(jobVerify.getUserId() == 1); - Assert.assertTrue(jobVerify.getAccountId() == 1); - - String result = jobVerify.getResult(); - for(int i = 0; i < 1024; i++) - Assert.assertTrue(result.charAt(i) == 'a'); - - jobVerify = dao.findInstancePendingAsyncJob("user_vm", 1000L); - Assert.assertTrue(jobVerify != null); - Assert.assertTrue(jobVerify.getCmd().equals(job.getCmd())); - Assert.assertTrue(jobVerify.getUserId() == 1); - Assert.assertTrue(jobVerify.getAccountId() == 1); - } - - public void testSerialization() { - List> l; - int value = 1; - l = SerializerHelper.toPairList(value, "result"); - Assert.assertTrue(l.size() == 1); - Assert.assertTrue(l.get(0).first().equals("result")); - Assert.assertTrue(l.get(0).second().equals("1")); - l.clear(); - - SampleAsyncResult result = new SampleAsyncResult("vmops", 1); - l = SerializerHelper.toPairList(result, "result"); - - Assert.assertTrue(l.size() == 2); - Assert.assertTrue(l.get(0).first().equals("name")); - Assert.assertTrue(l.get(0).second().equals("vmops")); - Assert.assertTrue(l.get(1).first().equals("count")); - Assert.assertTrue(l.get(1).second().equals("1")); - } - - public void testAsyncResult() { - AsyncJobResult result = new AsyncJobResult(1); - - result.setResultObject(100); - Assert.assertTrue(result.getResult().equals("java.lang.Integer/100")); - - Object obj = result.getResultObject(); - Assert.assertTrue(obj instanceof Integer); - Assert.assertTrue(((Integer)obj).intValue() == 100); - } - - public void testTransaction() { - Transaction txn = Transaction.open("testTransaction"); - try { - txn.start(); - - AsyncJobDao dao = new AsyncJobDaoImpl(); - AsyncJobVO job = new AsyncJobVO(1, 1, "TestCmd", null); - job.setInstanceType("user_vm"); - job.setInstanceId(1000L); - job.setResult(""); - dao.persist(job); - txn.rollback(); - } finally { - txn.close(); - } + public void testDao() { + AsyncJobDao dao = new AsyncJobDaoImpl(); + AsyncJobVO job = new AsyncJobVO(1, 1, "TestCmd", null); + job.setInstanceType("user_vm"); + job.setInstanceId(1000L); + + char[] buf = new char[1024]; + for(int i = 0; i < 1024; i++) + buf[i] = 'a'; + + job.setResult(new String(buf)); + dao.persist(job); + + AsyncJobVO jobVerify = dao.findById(job.getId()); + + Assert.assertTrue(jobVerify.getCmd().equals(job.getCmd())); + Assert.assertTrue(jobVerify.getUserId() == 1); + Assert.assertTrue(jobVerify.getAccountId() == 1); + + String result = jobVerify.getResult(); + for(int i = 0; i < 1024; i++) + Assert.assertTrue(result.charAt(i) == 'a'); + + jobVerify = dao.findInstancePendingAsyncJob("user_vm", 1000L); + Assert.assertTrue(jobVerify != null); + Assert.assertTrue(jobVerify.getCmd().equals(job.getCmd())); + Assert.assertTrue(jobVerify.getUserId() == 1); + Assert.assertTrue(jobVerify.getAccountId() == 1); + } + + public void testSerialization() { + List> l; + int value = 1; + l = SerializerHelper.toPairList(value, "result"); + Assert.assertTrue(l.size() == 1); + Assert.assertTrue(l.get(0).first().equals("result")); + Assert.assertTrue(l.get(0).second().equals("1")); + l.clear(); + + SampleAsyncResult result = new SampleAsyncResult("vmops", 1); + l = SerializerHelper.toPairList(result, "result"); + + Assert.assertTrue(l.size() == 2); + Assert.assertTrue(l.get(0).first().equals("name")); + Assert.assertTrue(l.get(0).second().equals("vmops")); + Assert.assertTrue(l.get(1).first().equals("count")); + Assert.assertTrue(l.get(1).second().equals("1")); + } + + public void testAsyncResult() { + AsyncJobResult result = new AsyncJobResult(1); + + result.setResultObject(100); + Assert.assertTrue(result.getResult().equals("java.lang.Integer/100")); + + Object obj = result.getResultObject(); + Assert.assertTrue(obj instanceof Integer); + Assert.assertTrue(((Integer)obj).intValue() == 100); + } + + public void testTransaction() { + Transaction txn = Transaction.open("testTransaction"); + try { + txn.start(); + + AsyncJobDao dao = new AsyncJobDaoImpl(); + AsyncJobVO job = new AsyncJobVO(1, 1, "TestCmd", null); + job.setInstanceType("user_vm"); + job.setInstanceId(1000L); + job.setResult(""); + dao.persist(job); + txn.rollback(); + } finally { + txn.close(); + } } public void testMorevingian() { @@ -284,4 +284,4 @@ public class TestAsync extends Log4jEnabledTestCase { txn.close(); } -} +} diff --git a/server/test/com/cloud/async/TestAsyncJobManager.java b/server/test/com/cloud/async/TestAsyncJobManager.java index 1c4403d93b7..d0813c69cda 100644 --- a/server/test/com/cloud/async/TestAsyncJobManager.java +++ b/server/test/com/cloud/async/TestAsyncJobManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -32,217 +32,217 @@ import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.Transaction; import com.cloud.utils.testcase.ComponentSetup; import com.cloud.utils.testcase.ComponentTestCase; - -@ComponentSetup(managerName="management-server", setupXml="async-job-component.xml") -public class TestAsyncJobManager extends ComponentTestCase { - public static final Logger s_logger = Logger.getLogger(TestAsyncJobManager.class.getName()); - - volatile long s_count = 0; - + +@ComponentSetup(managerName="management-server", setupXml="async-job-component.xml") +public class TestAsyncJobManager extends ComponentTestCase { + public static final Logger s_logger = Logger.getLogger(TestAsyncJobManager.class.getName()); + + volatile long s_count = 0; + public void asyncCall() { - AsyncJobManager asyncMgr = ComponentLocator.getLocator(ManagementServer.Name).getManager(AsyncJobManager.class); - -// long jobId = mgr.rebootVirtualMachineAsync(1, 1); + AsyncJobManager asyncMgr = ComponentLocator.getLocator(ManagementServer.Name).getManager(AsyncJobManager.class); + +// long jobId = mgr.rebootVirtualMachineAsync(1, 1); long jobId = 0L; - s_logger.info("Async-call job id: " + jobId); - - while(true) { - AsyncJobResult result; - try { - result = asyncMgr.queryAsyncJobResult(jobId); - - if(result.getJobStatus() != AsyncJobResult.STATUS_IN_PROGRESS) { - s_logger.info("Async-call completed, result: " + result.toString()); - break; - } - s_logger.info("Async-call is in progress, progress: " + result.toString()); - - } catch (PermissionDeniedException e1) { - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - } - - public void sequence() { - final HostDao hostDao = new HostDaoImpl(); - long seq = hostDao.getNextSequence(1); - s_logger.info("******* seq : " + seq + " ********"); - - HashMap hashMap = new HashMap(); - final Map map = Collections.synchronizedMap(hashMap); - - s_count = 0; - final long maxCount = 1000000; // test one million times - - Thread t1 = new Thread(new Runnable() { - public void run() { - while(s_count < maxCount) { - s_count++; - long seq = hostDao.getNextSequence(1); - Assert.assertTrue(map.put(seq, seq) == null); - } - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - while(s_count < maxCount) { - s_count++; - long seq = hostDao.getNextSequence(1); - Assert.assertTrue(map.put(seq, seq) == null); - } - } - }); - - t1.start(); - t2.start(); - - try { - t1.join(); - t2.join(); - } catch (InterruptedException e) { - } - } + s_logger.info("Async-call job id: " + jobId); + + while(true) { + AsyncJobResult result; + try { + result = asyncMgr.queryAsyncJobResult(jobId); + + if(result.getJobStatus() != AsyncJobResult.STATUS_IN_PROGRESS) { + s_logger.info("Async-call completed, result: " + result.toString()); + break; + } + s_logger.info("Async-call is in progress, progress: " + result.toString()); + + } catch (PermissionDeniedException e1) { + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } + } + + public void sequence() { + final HostDao hostDao = new HostDaoImpl(); + long seq = hostDao.getNextSequence(1); + s_logger.info("******* seq : " + seq + " ********"); + + HashMap hashMap = new HashMap(); + final Map map = Collections.synchronizedMap(hashMap); + + s_count = 0; + final long maxCount = 1000000; // test one million times + + Thread t1 = new Thread(new Runnable() { + public void run() { + while(s_count < maxCount) { + s_count++; + long seq = hostDao.getNextSequence(1); + Assert.assertTrue(map.put(seq, seq) == null); + } + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + while(s_count < maxCount) { + s_count++; + long seq = hostDao.getNextSequence(1); + Assert.assertTrue(map.put(seq, seq) == null); + } + } + }); + + t1.start(); + t2.start(); + + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + } + } /* - public void ipAssignment() { - final IPAddressDao ipAddressDao = new IPAddressDaoImpl(); - - final ConcurrentHashMap map = new ConcurrentHashMap(); - //final Map map = Collections.synchronizedMap(hashMap); - - s_count = 0; - final long maxCount = 1000000; // test one million times - - Thread t1 = new Thread(new Runnable() { - public void run() { - while(s_count < maxCount) { - s_count++; - - Transaction txn = Transaction.open("Alex1"); - try { - IPAddressVO addr = ipAddressDao.assignIpAddress(1, 0, 1, false); - IPAddressVO returnStr = map.put(addr.getAddress(), addr); - if(returnStr != null) { - System.out.println("addr : " + addr.getAddress()); - } - Assert.assertTrue(returnStr == null); - } finally { - txn.close(); - } - } - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - while(s_count < maxCount) { - s_count++; - - Transaction txn = Transaction.open("Alex2"); - try { - IPAddressVO addr = ipAddressDao.assignIpAddress(1, 0, 1, false); - Assert.assertTrue(map.put(addr.getAddress(), addr) == null); - } finally { - txn.close(); - } - } - } - }); - - t1.start(); - t2.start(); - - try { - t1.join(); - t2.join(); - } catch (InterruptedException e) { - } + public void ipAssignment() { + final IPAddressDao ipAddressDao = new IPAddressDaoImpl(); + + final ConcurrentHashMap map = new ConcurrentHashMap(); + //final Map map = Collections.synchronizedMap(hashMap); + + s_count = 0; + final long maxCount = 1000000; // test one million times + + Thread t1 = new Thread(new Runnable() { + public void run() { + while(s_count < maxCount) { + s_count++; + + Transaction txn = Transaction.open("Alex1"); + try { + IPAddressVO addr = ipAddressDao.assignIpAddress(1, 0, 1, false); + IPAddressVO returnStr = map.put(addr.getAddress(), addr); + if(returnStr != null) { + System.out.println("addr : " + addr.getAddress()); + } + Assert.assertTrue(returnStr == null); + } finally { + txn.close(); + } + } + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + while(s_count < maxCount) { + s_count++; + + Transaction txn = Transaction.open("Alex2"); + try { + IPAddressVO addr = ipAddressDao.assignIpAddress(1, 0, 1, false); + Assert.assertTrue(map.put(addr.getAddress(), addr) == null); + } finally { + txn.close(); + } + } + } + }); + + t1.start(); + t2.start(); + + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + } } - */ - - private long getRandomLockId() { - return 1L; - - /* - * will use in the future test cases - int i = new Random().nextInt(); - if(i % 2 == 0) - return 1L; - return 2L; - */ - } - - public void tstLocking() { - - int testThreads = 20; - Thread[] threads = new Thread[testThreads]; - - for(int i = 0; i < testThreads; i++) { - final int current = i; - threads[i] = new Thread(new Runnable() { - public void run() { - - final HostDao hostDao = new HostDaoImpl(); - while(true) { - Transaction txn = Transaction.currentTxn(); - try { - HostVO host = hostDao.acquireInLockTable(getRandomLockId(), 10); - if(host != null) { - s_logger.info("Thread " + (current + 1) + " acquired lock"); - - try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} - - s_logger.info("Thread " + (current + 1) + " released lock"); - hostDao.releaseFromLockTable(host.getId()); - - try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} - } else { - s_logger.info("Thread " + (current + 1) + " is not able to acquire lock"); - } - } finally { - txn.close(); - } - } - } - }); - threads[i].start(); - } - - try { - for(int i = 0; i < testThreads; i++) - threads[i].join(); - } catch(InterruptedException e) { - } - } - - public void testDomain() { - getRandomMilliseconds(1, 100); - DomainDao domainDao = new DomainDaoImpl(); - - DomainVO domain1 = new DomainVO("d1", 2L, 1L, null); - domainDao.create(domain1); - - DomainVO domain2 = new DomainVO("d2", 2L, 1L, null); - domainDao.create(domain2); - - DomainVO domain3 = new DomainVO("d3", 2L, 1L, null); - domainDao.create(domain3); - - DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null); - domainDao.create(domain11); - - domainDao.remove(domain11.getId()); - - DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null); - domainDao.create(domain12); - - domainDao.remove(domain3.getId()); - DomainVO domain4 = new DomainVO("d4", 2L, 1L, null); - domainDao.create(domain4); - } -} + */ + + private long getRandomLockId() { + return 1L; + + /* + * will use in the future test cases + int i = new Random().nextInt(); + if(i % 2 == 0) + return 1L; + return 2L; + */ + } + + public void tstLocking() { + + int testThreads = 20; + Thread[] threads = new Thread[testThreads]; + + for(int i = 0; i < testThreads; i++) { + final int current = i; + threads[i] = new Thread(new Runnable() { + public void run() { + + final HostDao hostDao = new HostDaoImpl(); + while(true) { + Transaction txn = Transaction.currentTxn(); + try { + HostVO host = hostDao.acquireInLockTable(getRandomLockId(), 10); + if(host != null) { + s_logger.info("Thread " + (current + 1) + " acquired lock"); + + try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} + + s_logger.info("Thread " + (current + 1) + " released lock"); + hostDao.releaseFromLockTable(host.getId()); + + try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} + } else { + s_logger.info("Thread " + (current + 1) + " is not able to acquire lock"); + } + } finally { + txn.close(); + } + } + } + }); + threads[i].start(); + } + + try { + for(int i = 0; i < testThreads; i++) + threads[i].join(); + } catch(InterruptedException e) { + } + } + + public void testDomain() { + getRandomMilliseconds(1, 100); + DomainDao domainDao = new DomainDaoImpl(); + + DomainVO domain1 = new DomainVO("d1", 2L, 1L, null); + domainDao.create(domain1); + + DomainVO domain2 = new DomainVO("d2", 2L, 1L, null); + domainDao.create(domain2); + + DomainVO domain3 = new DomainVO("d3", 2L, 1L, null); + domainDao.create(domain3); + + DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null); + domainDao.create(domain11); + + domainDao.remove(domain11.getId()); + + DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null); + domainDao.create(domain12); + + domainDao.remove(domain3.getId()); + DomainVO domain4 = new DomainVO("d4", 2L, 1L, null); + domainDao.create(domain4); + } +} diff --git a/server/test/com/cloud/async/TestSyncQueueManager.java b/server/test/com/cloud/async/TestSyncQueueManager.java index fa2fa1c2803..112c892c3b5 100644 --- a/server/test/com/cloud/async/TestSyncQueueManager.java +++ b/server/test/com/cloud/async/TestSyncQueueManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.List; import org.apache.log4j.Logger; @@ -20,177 +20,177 @@ import org.junit.Assert; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.testcase.ComponentSetup; import com.cloud.utils.testcase.ComponentTestCase; - -@ComponentSetup(managerName="management-server", setupXml="sync-queue-component.xml") -public class TestSyncQueueManager extends ComponentTestCase { - public static final Logger s_logger = Logger.getLogger(TestSyncQueueManager.class.getName()); - - private volatile int count = 0; - private volatile long expectingCurrent = 1; - public void leftOverItems() { - SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - - List l = mgr.getActiveQueueItems(1L, false); - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item : l) { - s_logger.info("Left over item: " + item.toString()); - mgr.purgeItem(item.getId()); - } - } - } - - public void dequeueFromOneQueue() { - final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - - final int totalRuns = 5000; - final SyncQueueVO queue = mgr.queue("vm_instance", 1L, "Async-job", 1); - for(int i = 1; i < totalRuns; i++) - mgr.queue("vm_instance", 1L, "Async-job", i+1); - - count = 0; - expectingCurrent = 1; - Thread thread1 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns) { - SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); - if(item != null) { - s_logger.info("Thread 1 process item: " + item.toString()); - - Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); - expectingCurrent++; - count++; - - mgr.purgeItem(item.getId()); - } - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - Thread thread2 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns) { - SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); - if(item != null) { - s_logger.info("Thread 2 process item: " + item.toString()); - - Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); - expectingCurrent++; - count++; - mgr.purgeItem(item.getId()); - } - - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - thread1.start(); - thread2.start(); - try { - thread1.join(); - } catch (InterruptedException e) { - } - try { - thread2.join(); - } catch (InterruptedException e) { - } - - Assert.assertEquals(totalRuns, count); - } - - public void dequeueFromAnyQueue() { - final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - - // simulate 30 queues - final int queues = 30; - final int totalRuns = 100; - final int itemsPerRun = 20; - for(int q = 1; q <= queues; q++) - for(int i = 0; i < totalRuns; i++) - mgr.queue("vm_instance", q, "Async-job", i+1); - - count = 0; - Thread thread1 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns*queues) { - List l = mgr.dequeueFromAny(1L, itemsPerRun); - if(l != null && l.size() > 0) { - s_logger.info("Thread 1 get " + l.size() + " dequeued items"); - - for(SyncQueueItemVO item : l) { - s_logger.info("Thread 1 process item: " + item.toString()); - count++; - - mgr.purgeItem(item.getId()); - } - } - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - Thread thread2 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns*queues) { - List l = mgr.dequeueFromAny(1L, itemsPerRun); - if(l != null && l.size() > 0) { - s_logger.info("Thread 2 get " + l.size() + " dequeued items"); - - for(SyncQueueItemVO item : l) { - s_logger.info("Thread 2 process item: " + item.toString()); - count++; - mgr.purgeItem(item.getId()); - } - } - - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - thread1.start(); - thread2.start(); - try { - thread1.join(); - } catch (InterruptedException e) { - } - try { - thread2.join(); - } catch (InterruptedException e) { - } - Assert.assertEquals(queues*totalRuns, count); - } - - public void testPopulateQueueData() { - final int queues = 30000; - final int totalRuns = 100; - - final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - for(int q = 1; q <= queues; q++) - for(int i = 0; i < totalRuns; i++) - mgr.queue("vm_instance", q, "Async-job", i+1); +@ComponentSetup(managerName="management-server", setupXml="sync-queue-component.xml") +public class TestSyncQueueManager extends ComponentTestCase { + public static final Logger s_logger = Logger.getLogger(TestSyncQueueManager.class.getName()); + + private volatile int count = 0; + private volatile long expectingCurrent = 1; + + public void leftOverItems() { + SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + + List l = mgr.getActiveQueueItems(1L, false); + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item : l) { + s_logger.info("Left over item: " + item.toString()); + mgr.purgeItem(item.getId()); + } + } + } + + public void dequeueFromOneQueue() { + final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + + final int totalRuns = 5000; + final SyncQueueVO queue = mgr.queue("vm_instance", 1L, "Async-job", 1); + for(int i = 1; i < totalRuns; i++) + mgr.queue("vm_instance", 1L, "Async-job", i+1); + + count = 0; + expectingCurrent = 1; + Thread thread1 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns) { + SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); + if(item != null) { + s_logger.info("Thread 1 process item: " + item.toString()); + + Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); + expectingCurrent++; + count++; + + mgr.purgeItem(item.getId()); + } + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + Thread thread2 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns) { + SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); + if(item != null) { + s_logger.info("Thread 2 process item: " + item.toString()); + + Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); + expectingCurrent++; + count++; + mgr.purgeItem(item.getId()); + } + + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + thread1.start(); + thread2.start(); + try { + thread1.join(); + } catch (InterruptedException e) { + } + try { + thread2.join(); + } catch (InterruptedException e) { + } + + Assert.assertEquals(totalRuns, count); + } + + public void dequeueFromAnyQueue() { + final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + + // simulate 30 queues + final int queues = 30; + final int totalRuns = 100; + final int itemsPerRun = 20; + for(int q = 1; q <= queues; q++) + for(int i = 0; i < totalRuns; i++) + mgr.queue("vm_instance", q, "Async-job", i+1); + + count = 0; + Thread thread1 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns*queues) { + List l = mgr.dequeueFromAny(1L, itemsPerRun); + if(l != null && l.size() > 0) { + s_logger.info("Thread 1 get " + l.size() + " dequeued items"); + + for(SyncQueueItemVO item : l) { + s_logger.info("Thread 1 process item: " + item.toString()); + count++; + + mgr.purgeItem(item.getId()); + } + } + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + Thread thread2 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns*queues) { + List l = mgr.dequeueFromAny(1L, itemsPerRun); + if(l != null && l.size() > 0) { + s_logger.info("Thread 2 get " + l.size() + " dequeued items"); + + for(SyncQueueItemVO item : l) { + s_logger.info("Thread 2 process item: " + item.toString()); + count++; + mgr.purgeItem(item.getId()); + } + } + + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + thread1.start(); + thread2.start(); + try { + thread1.join(); + } catch (InterruptedException e) { + } + try { + thread2.join(); + } catch (InterruptedException e) { + } + Assert.assertEquals(queues*totalRuns, count); + } + + public void testPopulateQueueData() { + final int queues = 30000; + final int totalRuns = 100; + + final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + for(int q = 1; q <= queues; q++) + for(int i = 0; i < totalRuns; i++) + mgr.queue("vm_instance", q, "Async-job", i+1); } public void testSyncQueue() { @@ -207,5 +207,5 @@ public class TestSyncQueueManager extends ComponentTestCase { System.out.println("Blocked item. " + item.getContentType() + "-" + item.getContentId()); mgr.purgeItem(item.getId()); } - } -} + } +} diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index b50ccb27307..8bf3421ae3f 100755 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -10,855 +10,855 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; -import com.cloud.dc.DataCenter; -import com.cloud.dc.Vlan; -import com.cloud.dc.Vlan.VlanType; -import com.cloud.deploy.DataCenterDeployment; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -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.Networks.TrafficType; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.element.RemoteAccessVPNServiceProvider; -import com.cloud.network.element.UserDataServiceProvider; -import com.cloud.network.guru.NetworkGuru; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.NetworkOfferingVO; -import com.cloud.user.Account; -import com.cloud.user.User; -import com.cloud.utils.Pair; -import com.cloud.utils.component.Manager; -import com.cloud.vm.Nic; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; - -@Local(value = { NetworkManager.class, NetworkService.class }) -public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkService { - - @Override - public List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IpAddress associateIP(long ipId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean disassociateIpAddress(long ipAddressId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Network createNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForNetworks(ListNetworksCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deleteNetwork(long networkId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public int getActiveNicsInNetwork(long networkId) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public Network getNetwork(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IpAddress getIp(long id) { - // TODO Auto-generated method stub - return null; - } - - @Override - public NetworkProfile convertNetworkToNetworkProfile(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map> getNetworkCapabilities(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isNetworkAvailableInDomain(long networkId, long domainId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Long getDedicatedNetworkDomain(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Integer getNetworkRate(long networkId, Long vmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { - // TODO Auto-generated method stub - return null; - } - - @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 PublicIp assignSourceNatIpAddress(Account owner, Network network, long callerId) throws ConcurrentOperationException, InsufficientAddressCapacityException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean releasePublicIpAddress(long id, long userId, Account caller) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List listPublicIpAddressesInVirtualNetwork(long accountId, long dcId, Boolean sourceNat, Long associatedNetworkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) - throws ConcurrentOperationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId, - ACLType aclType, Boolean subdomainAccess) throws ConcurrentOperationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getSystemAccountNetworkOfferings(String... offeringNames) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void allocate(VirtualMachineProfile vm, List> networks) throws InsufficientCapacityException, ConcurrentOperationException { - // TODO Auto-generated method stub - - } - - @Override - public void prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException { - // TODO Auto-generated method stub - - } - - @Override - public void release(VirtualMachineProfile vmProfile, boolean forced) { - // TODO Auto-generated method stub - - } - - @Override - public void cleanupNics(VirtualMachineProfile vm) { - // TODO Auto-generated method stub - - } - - @Override - public void expungeNics(VirtualMachineProfile vm) { - // TODO Auto-generated method stub - - } - - @Override - public List getNics(long vmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getNicProfiles(VirtualMachine vm) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public PublicIpAddress getPublicIpAddress(long ipAddressId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listPodVlans(long podId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNetworksUsedByVm(long vmId, boolean isSystem) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void prepareNicForMigration(VirtualMachineProfile vm, DeployDestination dest) { - // TODO Auto-generated method stub - - } - - @Override - public boolean destroyNetwork(long networkId, ReservationContext context) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, boolean isSecurityGroupEnabled, - Long domainId, PhysicalNetwork physicalNetwork, long zoneId, ACLType aclType, Boolean subdomainAccess) throws ConcurrentOperationException, InsufficientCapacityException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network networkToAssociateWith) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public Nic getNicInNetwork(long vmId, long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getNicsForTraffic(long vmId, TrafficType type) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Network getDefaultNetworkForVm(long vmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Nic getDefaultNic(long vmId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean areServicesSupportedByNetworkOffering(long networkOfferingId, Service... services) { - // TODO Auto-generated method stub - return false; - } - - @Override - public NetworkVO getNetworkWithSecurityGroupEnabled(Long zoneId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean startNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // TODO Auto-generated method stub - return false; - } - - @Override - public String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IPAddressVO markIpAsUnavailable(long addrId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String acquireGuestIpAddress(Network network, String requestedIp) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getGlobalGuestDomainSuffix() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getStartIpAddress(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean applyStaticNats(List staticNats, boolean continueOnError) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public String getIpInNetwork(long vmId, long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getIpInNetworkIncludingRemoved(long vmId, long networkId) { - // TODO Auto-generated method stub - return null; - } - - public Map> getNetworkOfferingServiceProvidersMap(long networkOfferingId) { - return null; - } - - @Override - public List getRemoteAccessVpnElements() { - return null; - } - - @Override - public boolean isProviderSupportServiceInNetwork(long networkId, Service service, Provider provider) { - // TODO Auto-generated method stub - return false; - } - - @Override - public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List tags, String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, String newVnetRangeString, String state) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deletePhysicalNetwork(Long id) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List listNetworkServices(String providerName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listSupportedNetworkServiceProviders(String serviceName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, List enabledServices) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deleteNetworkServiceProvider(Long id) { - // TODO Auto-generated method stub - return false; - } - - @Override - public PhysicalNetwork getPhysicalNetwork(Long physicalNetworkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetwork getCreatedPhysicalNetwork(Long physicalNetworkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deletePhysicalNetworkTrafficType(Long id) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List listTrafficTypes(Long physicalNetworkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Network getExclusiveGuestNetwork(long zoneId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long getPodIdForVlan(long vlanDbId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Map getNetworkServiceCapabilities(long networkId, Service service) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNetworksForAccount(long accountId, long zoneId, GuestType type) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNetworkOfferingsForUpgrade(long networkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isSecurityGroupSupportedInNetwork(Network network) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isProviderEnabledInPhysicalNetwork(long physicalNetowrkId, String providerName) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List getElementServices(Provider provider) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean canElementEnableIndividualServices(Provider provider) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List getPasswordResetElements() { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String state, List enabledServices) { - // TODO Auto-generated method stub - return null; - } - - @Override - public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean areServicesSupportedInNetwork(long networkId, Service... services) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isNetworkSystem(Network network) { - // TODO Auto-generated method stub - return false; - } - - @Override - public PhysicalNetworkServiceProvider addDefaultVirtualRouterToPhysicalNetwork(long physicalNetworkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getNetworkOfferingServiceCapabilities(NetworkOffering offering, Service service) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean reallocate(VirtualMachineProfile vm, DataCenterDeployment dest) throws InsufficientCapacityException, ConcurrentOperationException { - // TODO Auto-generated method stub - return false; - } - - @Override - public Long getPhysicalNetworkId(Network network) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean getAllowSubdomainAccessGlobal() { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isProviderForNetwork(Provider provider, long networkId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - // TODO Auto-generated method stub - return false; - } - - @Override - public String getNetworkTag(HypervisorType hType, Network network) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void canProviderSupportServices( - Map> providersMap) { - // TODO Auto-generated method stub - - } - - @Override - public boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork(long physicalNetworkId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getPhysicalNetworkInfo(long dcId, HypervisorType hypervisorType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean canAddDefaultSecurityGroup() { - // TODO Auto-generated method stub - return false; - } - - @Override - public List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNetworkOfferingServices(long networkOfferingId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean areServicesEnabledInZone(long zoneId, NetworkOffering offering, List services) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Map> getIpToServices(List publicIps, boolean rulesRevoked, boolean includingFirewall) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map> getProviderToIpList(Network network, Map> ipToServices) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean checkIpForService(IPAddressVO ip, Service service) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr) { - // TODO Auto-generated method stub - - } - - @Override - public IpAddress allocateIP(long networkId, Account ipOwner, - boolean isSystem) throws ResourceAllocationException, - InsufficientAddressCapacityException, ConcurrentOperationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, - VlanType type, Long networkId, String requestedIp, boolean isSystem) - throws InsufficientAddressCapacityException { - // TODO Auto-generated method stub - return null; - } - - @Override - public void checkCapabilityForProvider(Set providers, - Service service, Capability cap, String capValue) { - // TODO Auto-generated method stub - - } - - @Override - public Provider getDefaultUniqueProviderForService(String serviceName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IpAddress assignSystemIp(long networkId, Account owner, - boolean forElasticLb, boolean forElasticIp) - throws InsufficientAddressCapacityException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean handleSystemIpRelease(IpAddress ip) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void checkNetworkPermissions(Account owner, Network network) { - // TODO Auto-generated method stub - - } - - @Override - public void allocateDirectIp(NicProfile nic, DataCenter dc, - VirtualMachineProfile vm, - Network network, String requestedIp) - throws InsufficientVirtualNetworkCapcityException, - InsufficientAddressCapacityException { - // TODO Auto-generated method stub - - } - - @Override - public boolean validateRule(FirewallRule rule) { - // TODO Auto-generated method stub - return false; - } - - @Override - public String getDefaultManagementTrafficLabel(long zoneId, HypervisorType hypervisorType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDefaultStorageTrafficLabel(long zoneId, HypervisorType hypervisorType) { - // TODO Auto-generated method stub - return null; - } - @Override - public Network updateGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long networkOfferingId, Boolean changeCidr) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) { - // TODO Auto-generated method stub - return null; - } - -} +package com.cloud.network; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.acl.ControlledEntity.ACLType; +import com.cloud.api.commands.CreateNetworkCmd; +import com.cloud.api.commands.ListNetworksCmd; +import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; +import com.cloud.api.commands.RestartNetworkCmd; +import com.cloud.dc.DataCenter; +import com.cloud.dc.Vlan; +import com.cloud.dc.Vlan.VlanType; +import com.cloud.deploy.DataCenterDeployment; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapcityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +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.Networks.TrafficType; +import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; +import com.cloud.network.element.UserDataServiceProvider; +import com.cloud.network.guru.NetworkGuru; +import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.StaticNat; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.NetworkOfferingVO; +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.utils.Pair; +import com.cloud.utils.component.Manager; +import com.cloud.vm.Nic; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@Local(value = { NetworkManager.class, NetworkService.class }) +public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkService { + + @Override + public List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IpAddress associateIP(long ipId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException, ResourceUnavailableException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean disassociateIpAddress(long ipAddressId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Network createNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchForNetworks(ListNetworksCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deleteNetwork(long networkId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getActiveNicsInNetwork(long networkId) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public Network getNetwork(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IpAddress getIp(long id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public NetworkProfile convertNetworkToNetworkProfile(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map> getNetworkCapabilities(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isNetworkAvailableInDomain(long networkId, long domainId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Long getDedicatedNetworkDomain(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Integer getNetworkRate(long networkId, Long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { + // TODO Auto-generated method stub + return null; + } + + @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 PublicIp assignSourceNatIpAddress(Account owner, Network network, long callerId) throws ConcurrentOperationException, InsufficientAddressCapacityException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean releasePublicIpAddress(long id, long userId, Account caller) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List listPublicIpAddressesInVirtualNetwork(long accountId, long dcId, Boolean sourceNat, Long associatedNetworkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) + throws ConcurrentOperationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId, + ACLType aclType, Boolean subdomainAccess) throws ConcurrentOperationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getSystemAccountNetworkOfferings(String... offeringNames) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void allocate(VirtualMachineProfile vm, List> networks) throws InsufficientCapacityException, ConcurrentOperationException { + // TODO Auto-generated method stub + + } + + @Override + public void prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException { + // TODO Auto-generated method stub + + } + + @Override + public void release(VirtualMachineProfile vmProfile, boolean forced) { + // TODO Auto-generated method stub + + } + + @Override + public void cleanupNics(VirtualMachineProfile vm) { + // TODO Auto-generated method stub + + } + + @Override + public void expungeNics(VirtualMachineProfile vm) { + // TODO Auto-generated method stub + + } + + @Override + public List getNics(long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getNicProfiles(VirtualMachine vm) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public PublicIpAddress getPublicIpAddress(long ipAddressId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listPodVlans(long podId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNetworksUsedByVm(long vmId, boolean isSystem) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void prepareNicForMigration(VirtualMachineProfile vm, DeployDestination dest) { + // TODO Auto-generated method stub + + } + + @Override + public boolean destroyNetwork(long networkId, ReservationContext context) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, boolean isSecurityGroupEnabled, + Long domainId, PhysicalNetwork physicalNetwork, long zoneId, ACLType aclType, Boolean subdomainAccess) throws ConcurrentOperationException, InsufficientCapacityException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network networkToAssociateWith) throws InsufficientCapacityException, + ConcurrentOperationException, ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public Nic getNicInNetwork(long vmId, long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getNicsForTraffic(long vmId, TrafficType type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Network getDefaultNetworkForVm(long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Nic getDefaultNic(long vmId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean areServicesSupportedByNetworkOffering(long networkOfferingId, Service... services) { + // TODO Auto-generated method stub + return false; + } + + @Override + public NetworkVO getNetworkWithSecurityGroupEnabled(Long zoneId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean startNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IPAddressVO markIpAsUnavailable(long addrId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String acquireGuestIpAddress(Network network, String requestedIp) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getGlobalGuestDomainSuffix() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getStartIpAddress(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean applyStaticNats(List staticNats, boolean continueOnError) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getIpInNetwork(long vmId, long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getIpInNetworkIncludingRemoved(long vmId, long networkId) { + // TODO Auto-generated method stub + return null; + } + + public Map> getNetworkOfferingServiceProvidersMap(long networkOfferingId) { + return null; + } + + @Override + public List getRemoteAccessVpnElements() { + return null; + } + + @Override + public boolean isProviderSupportServiceInNetwork(long networkId, Service service, Provider provider) { + // TODO Auto-generated method stub + return false; + } + + @Override + public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List tags, String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, String newVnetRangeString, String state) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deletePhysicalNetwork(Long id) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List listNetworkServices(String providerName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listSupportedNetworkServiceProviders(String serviceName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, List enabledServices) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deleteNetworkServiceProvider(Long id) { + // TODO Auto-generated method stub + return false; + } + + @Override + public PhysicalNetwork getPhysicalNetwork(Long physicalNetworkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetwork getCreatedPhysicalNetwork(Long physicalNetworkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean deletePhysicalNetworkTrafficType(Long id) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List listTrafficTypes(Long physicalNetworkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Network getExclusiveGuestNetwork(long zoneId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long getPodIdForVlan(long vlanDbId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Map getNetworkServiceCapabilities(long networkId, Service service) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNetworksForAccount(long accountId, long zoneId, GuestType type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNetworkOfferingsForUpgrade(long networkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isSecurityGroupSupportedInNetwork(Network network) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isProviderEnabledInPhysicalNetwork(long physicalNetowrkId, String providerName) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List getElementServices(Provider provider) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean canElementEnableIndividualServices(Provider provider) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List getPasswordResetElements() { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String state, List enabledServices) { + // TODO Auto-generated method stub + return null; + } + + @Override + public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean areServicesSupportedInNetwork(long networkId, Service... services) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isNetworkSystem(Network network) { + // TODO Auto-generated method stub + return false; + } + + @Override + public PhysicalNetworkServiceProvider addDefaultVirtualRouterToPhysicalNetwork(long physicalNetworkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getNetworkOfferingServiceCapabilities(NetworkOffering offering, Service service) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean reallocate(VirtualMachineProfile vm, DataCenterDeployment dest) throws InsufficientCapacityException, ConcurrentOperationException { + // TODO Auto-generated method stub + return false; + } + + @Override + public Long getPhysicalNetworkId(Network network) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean getAllowSubdomainAccessGlobal() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isProviderForNetwork(Provider provider, long networkId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getNetworkTag(HypervisorType hType, Network network) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void canProviderSupportServices( + Map> providersMap) { + // TODO Auto-generated method stub + + } + + @Override + public boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork(long physicalNetworkId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getPhysicalNetworkInfo(long dcId, HypervisorType hypervisorType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean canAddDefaultSecurityGroup() { + // TODO Auto-generated method stub + return false; + } + + @Override + public List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNetworkOfferingServices(long networkOfferingId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean areServicesEnabledInZone(long zoneId, NetworkOffering offering, List services) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Map> getIpToServices(List publicIps, boolean rulesRevoked, boolean includingFirewall) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map> getProviderToIpList(Network network, Map> ipToServices) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean checkIpForService(IPAddressVO ip, Service service) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr) { + // TODO Auto-generated method stub + + } + + @Override + public IpAddress allocateIP(long networkId, Account ipOwner, + boolean isSystem) throws ResourceAllocationException, + InsufficientAddressCapacityException, ConcurrentOperationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, + VlanType type, Long networkId, String requestedIp, boolean isSystem) + throws InsufficientAddressCapacityException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void checkCapabilityForProvider(Set providers, + Service service, Capability cap, String capValue) { + // TODO Auto-generated method stub + + } + + @Override + public Provider getDefaultUniqueProviderForService(String serviceName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IpAddress assignSystemIp(long networkId, Account owner, + boolean forElasticLb, boolean forElasticIp) + throws InsufficientAddressCapacityException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean handleSystemIpRelease(IpAddress ip) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void checkNetworkPermissions(Account owner, Network network) { + // TODO Auto-generated method stub + + } + + @Override + public void allocateDirectIp(NicProfile nic, DataCenter dc, + VirtualMachineProfile vm, + Network network, String requestedIp) + throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException { + // TODO Auto-generated method stub + + } + + @Override + public boolean validateRule(FirewallRule rule) { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getDefaultManagementTrafficLabel(long zoneId, HypervisorType hypervisorType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDefaultStorageTrafficLabel(long zoneId, HypervisorType hypervisorType) { + // TODO Auto-generated method stub + return null; + } + @Override + public Network updateGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long networkOfferingId, Boolean changeCidr) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/server/test/sync-queue-component.xml b/server/test/sync-queue-component.xml index 2c30ef8d2d5..d7ab85c65a4 100644 --- a/server/test/sync-queue-component.xml +++ b/server/test/sync-queue-component.xml @@ -1,8 +1,8 @@ - - - - - - - - + + + + + + + +