From 0a5228922b822b57af72249912ed854281e1d85a Mon Sep 17 00:00:00 2001 From: Edison Su Date: Wed, 29 May 2013 18:04:08 -0700 Subject: [PATCH] clean up storage related coded --- .../subsystem/api/storage/ClusterScope.java | 9 +- .../api/storage/CopyCommandResult.java | 7 +- .../api/storage/CreateCmdResult.java | 3 +- .../api/storage/DataMigrationSubSystem.java | 1 + .../api/storage/DataMotionService.java | 8 +- .../api/storage/DataMotionStrategy.java | 5 +- .../subsystem/api/storage/DataObject.java | 10 +- .../api/storage/DataObjectInStore.java | 5 +- .../subsystem/api/storage/DataStore.java | 9 + .../api/storage/DataStoreDriver.java | 9 + .../api/storage/DataStoreLifeCycle.java | 3 +- .../api/storage/DataStoreManager.java | 9 +- .../api/storage/DataStoreProvider.java | 14 +- .../api/storage/DataStoreProviderManager.java | 4 + .../subsystem/api/storage/EndPoint.java | 8 +- .../api/storage/EndPointSelector.java | 1 - .../subsystem/api/storage/HostScope.java | 5 +- .../api/storage/HypervisorHostListener.java | 1 + .../api/storage/ImageStoreProvider.java | 1 - .../ObjectInDataStoreStateMachine.java | 29 +- .../api/storage/PrimaryDataStoreDriver.java | 1 + .../api/storage/PrimaryDataStoreInfo.java | 16 +- .../storage/PrimaryDataStoreLifeCycle.java | 1 - .../storage/PrimaryDataStoreParameters.java | 40 +- .../engine/subsystem/api/storage/Scope.java | 2 + .../api/storage/SnapshotDataFactory.java | 3 +- .../subsystem/api/storage/SnapshotInfo.java | 17 +- .../api/storage/SnapshotProfile.java | 9 +- .../subsystem/api/storage/SnapshotResult.java | 43 +- .../api/storage/SnapshotService.java | 13 +- .../api/storage/SnapshotStrategy.java | 11 +- .../api/storage/StorageCacheManager.java | 8 +- .../subsystem/api/storage/StorageEvent.java | 4 +- .../api/storage/StorageOrchestrator.java | 18 +- .../api/storage/StoragePoolAllocator.java | 32 +- .../api/storage/StorageSubSystem.java | 2 + .../api/storage/TemplateDataFactory.java | 4 +- .../subsystem/api/storage/TemplateEvent.java | 5 +- .../subsystem/api/storage/TemplateInfo.java | 1 + .../api/storage/TemplateProfile.java | 489 +++--- .../api/storage/TemplateService.java | 21 +- .../subsystem/api/storage/TemplateState.java | 6 +- .../api/storage/VolumeDataFactory.java | 3 +- .../subsystem/api/storage/VolumeInfo.java | 17 +- .../subsystem/api/storage/VolumeProfile.java | 25 +- .../subsystem/api/storage/VolumeService.java | 23 +- .../subsystem/api/storage/ZoneScope.java | 5 +- .../api/storage/disktype/DiskFormat.java | 5 +- .../subsystem/api/storage/type/BaseImage.java | 6 +- .../subsystem/api/storage/type/DataDisk.java | 6 +- .../subsystem/api/storage/type/Iso.java | 6 +- .../subsystem/api/storage/type/RootDisk.java | 6 +- .../subsystem/api/storage/type/Unknown.java | 6 +- .../api/storage/type/VolumeTypeBase.java | 54 +- .../api/storage/type/VolumeTypeHelper.java | 34 +- .../storage/command/AttachAnswer.java | 2 + .../storage/command/AttachCommand.java | 13 +- .../command/AttachPrimaryDataStoreAnswer.java | 13 +- .../command/AttachPrimaryDataStoreCmd.java | 8 +- .../storage/command/CommandResult.java | 12 +- .../storage/command/CopyCmdAnswer.java | 8 +- .../storage/command/CopyCommand.java | 7 +- .../storage/command/CreateObjectAnswer.java | 10 +- .../storage/command/CreateObjectCommand.java | 5 +- .../command/CreatePrimaryDataStoreCmd.java | 10 +- .../storage/command/DeleteCommand.java | 15 +- .../storage/command/DettachAnswer.java | 4 +- .../storage/command/DettachCommand.java | 11 +- .../DownloadSystemTemplateCommand.java | 98 +- .../storage/datastore/db/ImageStoreDao.java | 6 +- .../datastore/db/ImageStoreDetailVO.java | 13 +- .../datastore/db/ImageStoreDetailsDao.java | 1 - .../storage/datastore/db/ImageStoreVO.java | 6 +- .../datastore/db/PrimaryDataStoreDao.java | 103 +- .../datastore/db/PrimaryDataStoreDaoImpl.java | 554 ++++--- .../db/PrimaryDataStoreDetailVO.java | 22 +- .../db/PrimaryDataStoreDetailsDao.java | 3 +- .../datastore/db/SnapshotDataStoreDao.java | 5 +- .../datastore/db/SnapshotDataStoreVO.java | 194 +-- .../datastore/db/StoragePoolDetailVO.java | 22 +- .../datastore/db/StoragePoolDetailsDao.java | 5 +- .../storage/datastore/db/StoragePoolVO.java | 24 +- .../datastore/db/TemplateDataStoreDao.java | 14 +- .../datastore/db/TemplateDataStoreVO.java | 224 ++- .../datastore/db/VolumeDataStoreDao.java | 5 +- .../datastore/db/VolumeDataStoreVO.java | 307 ++-- .../image/datastore/ImageStoreEntity.java | 5 + .../image/datastore/ImageStoreInfo.java | 1 + .../cloudstack/storage/to/ImageStoreTO.java | 3 +- .../storage/to/NfsPrimaryDataStoreTO.java | 44 - .../storage/to/PrimaryDataStoreTO.java | 12 +- .../storage/to/SnapshotObjectTO.java | 84 +- .../storage/to/TemplateObjectTO.java | 60 +- .../cloudstack/storage/to/VolumeObjectTO.java | 39 +- .../src/com/cloud/storage/DiskOfferingVO.java | 112 +- .../com/cloud/storage/GuestOSCategoryVO.java | 23 +- .../src/com/cloud/storage/GuestOSVO.java | 35 +- .../com/cloud/storage/LaunchPermissionVO.java | 11 +- engine/schema/src/com/cloud/storage/S3VO.java | 23 +- .../com/cloud/storage/SnapshotPolicyVO.java | 40 +- .../com/cloud/storage/SnapshotScheduleVO.java | 80 +- .../src/com/cloud/storage/SnapshotVO.java | 59 +- .../cloud/storage/StoragePoolHostAssoc.java | 16 +- .../com/cloud/storage/StoragePoolHostVO.java | 94 +- .../com/cloud/storage/StoragePoolWorkVO.java | 38 +- .../schema/src/com/cloud/storage/SwiftVO.java | 33 +- .../src/com/cloud/storage/UploadVO.java | 272 ++- .../com/cloud/storage/VMTemplateDetailVO.java | 81 +- .../com/cloud/storage/VMTemplateHostVO.java | 310 ++-- .../src/com/cloud/storage/VMTemplateS3VO.java | 34 +- .../storage/VMTemplateStoragePoolVO.java | 298 ++-- .../com/cloud/storage/VMTemplateSwiftVO.java | 3 +- .../src/com/cloud/storage/VMTemplateVO.java | 234 +-- .../com/cloud/storage/VMTemplateZoneVO.java | 128 +- .../src/com/cloud/storage/VolumeHostVO.java | 320 ++-- .../src/com/cloud/storage/VolumeVO.java | 97 +- .../cloud/storage/dao/DiskOfferingDao.java | 8 +- .../storage/dao/DiskOfferingDaoImpl.java | 57 +- .../cloud/storage/dao/GuestOSCategoryDao.java | 2 +- .../storage/dao/GuestOSCategoryDaoImpl.java | 10 +- .../src/com/cloud/storage/dao/GuestOSDao.java | 2 +- .../com/cloud/storage/dao/GuestOSDaoImpl.java | 18 +- .../storage/dao/LaunchPermissionDao.java | 28 +- .../storage/dao/LaunchPermissionDaoImpl.java | 31 +- .../src/com/cloud/storage/dao/S3DaoImpl.java | 3 +- .../com/cloud/storage/dao/SnapshotDao.java | 28 +- .../cloud/storage/dao/SnapshotDaoImpl.java | 83 +- .../cloud/storage/dao/SnapshotPolicyDao.java | 12 +- .../storage/dao/SnapshotPolicyDaoImpl.java | 45 +- .../storage/dao/SnapshotScheduleDao.java | 5 +- .../storage/dao/SnapshotScheduleDaoImpl.java | 87 +- .../dao/StoragePoolDetailsDaoImpl.java | 35 +- .../storage/dao/StoragePoolHostDaoImpl.java | 18 +- .../cloud/storage/dao/StoragePoolWorkDao.java | 3 +- .../storage/dao/StoragePoolWorkDaoImpl.java | 62 +- .../com/cloud/storage/dao/SwiftDaoImpl.java | 2 +- .../src/com/cloud/storage/dao/UploadDao.java | 11 +- .../com/cloud/storage/dao/UploadDaoImpl.java | 111 +- .../com/cloud/storage/dao/VMTemplateDao.java | 45 +- .../cloud/storage/dao/VMTemplateDaoImpl.java | 1460 ++++++++--------- .../storage/dao/VMTemplateDetailsDao.java | 10 +- .../storage/dao/VMTemplateDetailsDaoImpl.java | 64 +- .../cloud/storage/dao/VMTemplateHostDao.java | 15 +- .../storage/dao/VMTemplateHostDaoImpl.java | 562 +++---- .../cloud/storage/dao/VMTemplatePoolDao.java | 36 +- .../storage/dao/VMTemplatePoolDaoImpl.java | 427 ++--- .../storage/dao/VMTemplateS3DaoImpl.java | 25 +- .../cloud/storage/dao/VMTemplateZoneDao.java | 6 +- .../storage/dao/VMTemplateZoneDaoImpl.java | 87 +- .../src/com/cloud/storage/dao/VolumeDao.java | 9 +- .../com/cloud/storage/dao/VolumeDaoImpl.java | 358 ++-- .../com/cloud/storage/dao/VolumeHostDao.java | 13 +- .../cloud/storage/dao/VolumeHostDaoImpl.java | 37 +- .../StorageCacheRandomAllocator.java | 11 +- .../manager/StorageCacheManagerImpl.java | 75 +- .../motion/AncientDataMotionStrategy.java | 183 +-- .../storage/motion/DataMotionServiceImpl.java | 16 +- .../image/TemplateDataFactoryImpl.java | 17 +- .../storage/image/TemplateServiceImpl.java | 168 +- .../image/manager/ImageDataManagerImpl.java | 6 +- .../ImageStoreProviderManagerImpl.java | 15 +- .../storage/image/store/ImageStoreImpl.java | 46 +- .../storage/image/store/TemplateObject.java | 169 +- .../MockLocalNfsSecondaryStorageResource.java | 66 +- .../allocator/StorageAllocatorTest.java | 705 ++++---- .../StorageAllocatorTestConfiguration.java | 47 +- .../cloudstack/storage/test/AopTest.java | 2 +- .../storage/test/AopTestAdvice.java | 20 +- .../storage/test/ChildTestConfiguration.java | 157 +- .../storage/test/CloudStackTestNGBase.java | 50 +- .../test/DirectAgentManagerSimpleImpl.java | 75 +- .../storage/test/DirectAgentTest.java | 38 +- ...stEndpointRpcServerDirectCallResource.java | 70 - .../MockHypervisorHostEndPointRpcServer.java | 72 - .../storage/test/MockLocalHostEndPoint.java | 17 +- .../storage/test/MockRpcCallBack.java | 12 +- .../test/MockStorageMotionStrategy.java | 4 +- .../storage/test/S3TemplateTest.java | 161 +- .../cloudstack/storage/test/SnapshotTest.java | 135 +- .../storage/test/StorageFactoryBean.java | 11 +- .../cloudstack/storage/test/StorageTest.java | 11 +- .../cloudstack/storage/test/TemplateTest.java | 148 +- .../cloudstack/storage/test/TestHttp.java | 17 +- .../cloudstack/storage/test/TestNG.java | 5 +- .../cloudstack/storage/test/TestNGAop.java | 6 +- .../cloudstack/storage/test/VolumeTest.java | 106 +- .../storage/test/VolumeTestVmware.java | 107 +- .../storage/test/volumeServiceTest.java | 540 +++--- .../snapshot/SnapshotDataFactoryImpl.java | 12 +- .../storage/snapshot/SnapshotObject.java | 10 +- .../storage/snapshot/SnapshotServiceImpl.java | 650 ++++---- .../snapshot/SnapshotStateMachineManager.java | 2 +- .../SnapshotStateMachineManagerImpl.java | 53 +- .../snapshot/SnapshotStrategyBase.java | 20 +- .../snapshot/XenserverSnapshotStrategy.java | 270 ++- .../storage/snapshot/db/SnapshotVO.java | 78 +- .../test/src/SnapshotDataFactoryTest.java | 23 +- .../apache/cloudstack/storage/BaseType.java | 1 + .../storage/HostEndpointRpcServer.java | 29 - .../HypervisorHostEndPointRpcServer.java | 119 -- .../cloudstack/storage/LocalHostEndpoint.java | 111 +- .../storage/RemoteHostEndPoint.java | 46 +- .../AbstractStoragePoolAllocator.java | 173 +- .../ClusterScopeStoragePoolAllocator.java | 45 +- ...GarbageCollectingStoragePoolAllocator.java | 17 +- .../allocator/LocalStoragePoolAllocator.java | 32 +- .../allocator/UseLocalForRootAllocator.java | 10 +- .../ZoneWideStoragePoolAllocator.java | 65 +- .../backup/SnapshotOnBackupStoreInfo.java | 5 +- .../backup/datastore/BackupStoreInfo.java | 5 +- .../storage/datastore/DataObjectManager.java | 9 +- .../datastore/DataObjectManagerImpl.java | 170 +- .../datastore/DataStoreManagerImpl.java | 14 +- .../datastore/ObjectInDataStoreManager.java | 11 +- .../ObjectInDataStoreManagerImpl.java | 146 +- .../storage/datastore/PrimaryDataStore.java | 3 +- .../datastore/PrimaryDataStoreEntityImpl.java | 20 +- .../PrimaryDataStoreProviderManager.java | 3 +- .../datastore/protocol/DataStoreProtocol.java | 8 +- .../DataStoreProviderManagerImpl.java | 24 +- .../storage/db/ObjectInDataStoreDao.java | 3 +- .../storage/db/ObjectInDataStoreDaoImpl.java | 29 +- .../storage/db/ObjectInDataStoreVO.java | 24 +- .../endpoint/DefaultEndPointSelector.java | 62 +- .../storage/image/TemplateEntityImpl.java | 5 +- .../image/datastore/ImageStoreHelper.java | 45 +- .../datastore/ImageStoreProviderManager.java | 6 + .../storage/image/db/ImageStoreDaoImpl.java | 10 +- .../image/db/ImageStoreDetailsDaoImpl.java | 20 +- .../image/db/SnapshotDataStoreDaoImpl.java | 26 +- .../image/db/TemplateDataStoreDaoImpl.java | 93 +- .../image/db/VolumeDataStoreDaoImpl.java | 30 +- .../image/motion/ImageMotionService.java | 6 +- .../storage/snapshot/SnapshotEntityImpl.java | 254 +-- .../datastore/PrimaryDataStoreHelper.java | 58 +- .../db/PrimaryDataStoreDetailsDaoImpl.java | 42 +- .../db/TemplatePrimaryDataStoreDao.java | 4 +- .../db/TemplatePrimaryDataStoreDaoImpl.java | 43 +- .../volume/db/TemplatePrimaryDataStoreVO.java | 18 +- .../datastore/PrimaryDataStoreImpl.java | 38 +- .../PrimaryDataStoreProviderManagerImpl.java | 6 +- .../provider/DefaultHostListener.java | 32 +- .../volume/TemplateInstallStrategy.java | 28 - .../volume/TemplateInstallStrategyImpl.java | 289 ---- .../storage/volume/VolumeDataFactoryImpl.java | 7 +- .../storage/volume/VolumeEntityImpl.java | 71 +- .../storage/volume/VolumeMotionService.java | 23 - .../storage/volume/VolumeObject.java | 81 +- .../storage/volume/VolumeServiceImpl.java | 617 ++++--- .../storage/volume/test/ConfiguratorTest.java | 64 +- .../storage/volume/test/Server.java | 17 +- .../volume/test/TestConfiguration.java | 2 +- .../volume/test/TestInProcessAsync.java | 7 +- .../allocator/RandomStoragePoolAllocator.java | 51 +- .../CloudStackImageStoreDriverImpl.java | 237 ++- .../CloudStackImageStoreLifeCycleImpl.java | 70 +- .../CloudStackImageStoreProviderImpl.java | 7 +- .../driver/S3ImageStoreDriverImpl.java | 140 +- .../lifecycle/S3ImageStoreLifeCycleImpl.java | 69 +- .../provider/S3ImageStoreProviderImpl.java | 10 +- .../driver/SampleImageStoreDriverImpl.java | 29 +- .../SampleImageStoreLifeCycleImpl.java | 25 +- .../SampleImageStoreProviderImpl.java | 6 +- .../driver/SwiftImageStoreDriverImpl.java | 126 +- .../SwiftImageStoreLifeCycleImpl.java | 52 +- .../provider/SwiftImageStoreProviderImpl.java | 7 +- .../CloudStackPrimaryDataStoreDriverImpl.java | 313 ++-- ...oudStackPrimaryDataStoreLifeCycleImpl.java | 157 +- ...loudStackPrimaryDataStoreProviderImpl.java | 5 +- .../SamplePrimaryDataStoreDriverImpl.java | 184 +-- .../SamplePrimaryDataStoreLifeCycleImpl.java | 24 +- .../SamplePrimaryDatastoreProviderImpl.java | 6 +- .../SolidfirePrimaryDataStoreDriver.java | 20 +- .../SolidfirePrimaryDataStoreProvider.java | 19 +- .../storage/test/AopTestAdvice.java | 20 +- .../storage/test/ChildTestConfiguration.java | 47 +- .../storage/test/TestConfiguration.java | 17 +- .../cloudstack/storage/test/VolumeTest.java | 157 +- 278 files changed, 8757 insertions(+), 9784 deletions(-) delete mode 100644 engine/api/src/org/apache/cloudstack/storage/to/NfsPrimaryDataStoreTO.java delete mode 100644 engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHostEndpointRpcServerDirectCallResource.java delete mode 100644 engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHypervisorHostEndPointRpcServer.java delete mode 100644 engine/storage/src/org/apache/cloudstack/storage/HostEndpointRpcServer.java delete mode 100644 engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPointRpcServer.java delete mode 100644 engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategy.java delete mode 100644 engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategyImpl.java delete mode 100644 engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java index 938f055b2d9..15e6d45f9ca 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java @@ -20,19 +20,18 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; - public class ClusterScope extends AbstractScope { private ScopeType type = ScopeType.CLUSTER; private Long clusterId; private Long podId; private Long zoneId; - + public ClusterScope(Long clusterId, Long podId, Long zoneId) { this.clusterId = clusterId; this.podId = podId; this.zoneId = zoneId; } - + @Override public ScopeType getScopeType() { return this.type; @@ -42,11 +41,11 @@ public class ClusterScope extends AbstractScope { public Long getScopeId() { return this.clusterId; } - + public Long getPodId() { return this.podId; } - + public Long getZoneId() { return this.zoneId; } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CopyCommandResult.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CopyCommandResult.java index e9d7b110341..bb5ba14d25d 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CopyCommandResult.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CopyCommandResult.java @@ -25,17 +25,18 @@ import com.cloud.agent.api.Answer; public class CopyCommandResult extends CommandResult { private final String path; private final Answer answer; + public CopyCommandResult(String path, Answer answer) { super(); this.path = path; this.answer = answer; } - + public String getPath() { return this.path; } - + public Answer getAnswer() { - return this.answer; + return this.answer; } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CreateCmdResult.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CreateCmdResult.java index 2ecd97d071d..d05653cafb1 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CreateCmdResult.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/CreateCmdResult.java @@ -25,12 +25,13 @@ import com.cloud.agent.api.Answer; public class CreateCmdResult extends CommandResult { private String path; private Answer answer; + public CreateCmdResult(String path, Answer answer) { super(); this.path = path; this.answer = answer; } - + public String getPath() { return this.path; } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMigrationSubSystem.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMigrationSubSystem.java index 65928bd5537..ad810432fd2 100755 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMigrationSubSystem.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMigrationSubSystem.java @@ -25,5 +25,6 @@ import com.cloud.org.Grouping; public interface DataMigrationSubSystem { Class getScopeCoverage(); + void migrate(URI source, URI dest, String reservationId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionService.java index 40d6814e36b..5a124aa2725 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionService.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionService.java @@ -18,7 +18,6 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; - import java.util.Map; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; @@ -27,10 +26,9 @@ import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.host.Host; public interface DataMotionService { - public void copyAsync(DataObject srcData, DataObject destData, + public void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback); + + public void copyAsync(Map volumeMap, VirtualMachineTO vmTo, Host srcHost, Host destHost, AsyncCompletionCallback callback); - public void copyAsync(Map volumeMap, VirtualMachineTO vmTo, - Host srcHost, Host destHost, AsyncCompletionCallback callback); - } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionStrategy.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionStrategy.java index d2d35b7c077..5bff21f3c8a 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionStrategy.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataMotionStrategy.java @@ -18,7 +18,6 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; - import java.util.Map; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; @@ -26,14 +25,12 @@ import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.host.Host; - public interface DataMotionStrategy { public boolean canHandle(DataObject srcData, DataObject destData); public boolean canHandle(Map volumeMap, Host srcHost, Host destHost); - public Void copyAsync(DataObject srcData, DataObject destData, - AsyncCompletionCallback callback); + public Void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback); public Void copyAsync(Map volumeMap, VirtualMachineTO vmTo, Host srcHost, Host destHost, AsyncCompletionCallback callback); diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObject.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObject.java index 7610bca59bb..ef8798951c9 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObject.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObject.java @@ -24,13 +24,21 @@ import com.cloud.agent.api.to.DataTO; public interface DataObject { public long getId(); + public String getUri(); + public DataTO getTO(); + public DataStore getDataStore(); + public Long getSize(); + public DataObjectType getType(); - //public DiskFormat getFormat(); + + // public DiskFormat getFormat(); public String getUuid(); + public void processEvent(ObjectInDataStoreStateMachine.Event event); + public void processEvent(ObjectInDataStoreStateMachine.Event event, Answer answer); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObjectInStore.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObjectInStore.java index 0bfbd9a7aa4..929774c67c9 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObjectInStore.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataObjectInStore.java @@ -20,11 +20,14 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.utils.fsm.StateObject; - public interface DataObjectInStore extends StateObject { public String getInstallPath(); + public void setInstallPath(String path); + public long getObjectId(); + public long getDataStoreId(); + public ObjectInDataStoreStateMachine.State getObjectInStoreState(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStore.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStore.java index c0570a9148d..e9a8f50e105 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStore.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStore.java @@ -21,13 +21,22 @@ import com.cloud.storage.DataStoreRole; public interface DataStore { DataStoreDriver getDriver(); + DataStoreRole getRole(); + long getId(); + String getUuid(); + String getUri(); + Scope getScope(); + String getName(); + DataObject create(DataObject obj); + boolean delete(DataObject obj); + DataStoreTO getTO(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreDriver.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreDriver.java index 5ed9ab838ad..21430805c67 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreDriver.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreDriver.java @@ -28,13 +28,22 @@ import com.cloud.agent.api.to.DataTO; public interface DataStoreDriver { public String grantAccess(DataObject data, EndPoint ep); + public boolean revokeAccess(DataObject data, EndPoint ep); + public Set listObjects(DataStore store); + public void createAsync(DataObject data, AsyncCompletionCallback callback); + public void deleteAsync(DataObject data, AsyncCompletionCallback callback); + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback); + public boolean canCopy(DataObject srcData, DataObject destData); + public void resize(DataObject data, AsyncCompletionCallback callback); + public DataTO getTO(DataObject data); + public DataStoreTO getStoreTO(DataStore store); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreLifeCycle.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreLifeCycle.java index 2440bfdb197..d714df33df3 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreLifeCycle.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreLifeCycle.java @@ -22,12 +22,13 @@ import java.util.Map; import com.cloud.agent.api.StoragePoolInfo; - public interface DataStoreLifeCycle { public DataStore initialize(Map dsInfos); public boolean attachCluster(DataStore store, ClusterScope scope); + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo); + boolean attachZone(DataStore dataStore, ZoneScope scope); public boolean dettach(); diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java index e61734aded6..8617eb4c2ad 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java @@ -23,15 +23,22 @@ import java.util.Map; import com.cloud.storage.DataStoreRole; - public interface DataStoreManager { public DataStore getDataStore(long storeId, DataStoreRole role); + public DataStore getPrimaryDataStore(long storeId); + public DataStore getDataStore(String uuid, DataStoreRole role); + public List getImageStoresByScope(ZoneScope scope); + public DataStore getImageStore(long zoneId); + public List getImageStoresByProvider(String provider); + public List getImageCacheStores(Scope scope); + public DataStore registerDataStore(Map params, String providerUuid); + public List listImageStores(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProvider.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProvider.java index cdcdef8a8b4..a13c60bd772 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProvider.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProvider.java @@ -21,9 +21,6 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import java.util.Map; import java.util.Set; - - - public interface DataStoreProvider { // constants for provider names public static final String NFS_IMAGE = "NFS"; @@ -34,16 +31,19 @@ public interface DataStoreProvider { public static final String DEFAULT_PRIMARY = "DefaultPrimary"; public static enum DataStoreProviderType { - PRIMARY, - IMAGE, - ImageCache + PRIMARY, IMAGE, ImageCache } + public DataStoreLifeCycle getDataStoreLifeCycle(); + public DataStoreDriver getDataStoreDriver(); + public HypervisorHostListener getHostListener(); + public String getName(); + public boolean configure(Map params); + public Set getTypes(); - } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProviderManager.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProviderManager.java index 6872bdfc726..84272ef412c 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProviderManager.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreProviderManager.java @@ -25,9 +25,13 @@ import com.cloud.utils.component.Manager; public interface DataStoreProviderManager extends Manager, DataStoreProviderApiService { public DataStoreProvider getDataStoreProvider(String name); + public DataStoreProvider getDefaultPrimaryDataStoreProvider(); + public DataStoreProvider getDefaultImageDataStoreProvider(); + public DataStoreProvider getDefaultCacheDataStoreProvider(); + public List getDataStoreProviders(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPoint.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPoint.java index 904ee989f2c..ed9c0ebe908 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPoint.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPoint.java @@ -23,8 +23,12 @@ import com.cloud.agent.api.Command; public interface EndPoint { public long getId(); + public String getHostAddr(); + public String getPublicAddr(); - public Answer sendMessage(Command cmd); - public void sendMessageAsync(Command cmd, AsyncCompletionCallback callback); + + public Answer sendMessage(Command cmd); + + public void sendMessageAsync(Command cmd, AsyncCompletionCallback callback); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java index d3eb1ecd3f7..a51fad817c0 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import java.util.List; - public interface EndPointSelector { public EndPoint select(DataObject srcData, DataObject destData); diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java index ab21f6805e4..ff33077146a 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java @@ -20,9 +20,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; - public class HostScope extends AbstractScope { - private ScopeType type = ScopeType.HOST; private Long hostId; private Long zoneId; @@ -30,9 +28,10 @@ public class HostScope extends AbstractScope { this.hostId = hostId; this.zoneId = zoneId; } + @Override public ScopeType getScopeType() { - return this.type; + return ScopeType.HOST; } @Override diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HypervisorHostListener.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HypervisorHostListener.java index 3ac17598bb0..8db4101ffc0 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HypervisorHostListener.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/HypervisorHostListener.java @@ -20,5 +20,6 @@ package org.apache.cloudstack.engine.subsystem.api.storage; public interface HypervisorHostListener { boolean hostConnect(long hostId, long poolId); + boolean hostDisconnected(long hostId, long poolId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageStoreProvider.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageStoreProvider.java index 0f3f05b3ee7..bde4fe4c597 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageStoreProvider.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageStoreProvider.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; - public interface ImageStoreProvider extends DataStoreProvider { public boolean isScopeSupported(ScopeType scope); diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ObjectInDataStoreStateMachine.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ObjectInDataStoreStateMachine.java index 94ae800ab8e..04522f628d5 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ObjectInDataStoreStateMachine.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ObjectInDataStoreStateMachine.java @@ -22,16 +22,11 @@ import com.cloud.utils.fsm.StateObject; public interface ObjectInDataStoreStateMachine extends StateObject { enum State { - Allocated("The initial state"), - Creating2("This is only used with createOnlyRequested event"), - Creating("The object is being creating on data store"), - Created("The object is created"), - Ready("Template downloading is accomplished"), - Copying("The object is being coping"), - Migrating("The object is being migrated"), - Destroying("Template is destroying"), - Destroyed("Template is destroyed"), - Failed("Failed to download template"); + Allocated("The initial state"), Creating2("This is only used with createOnlyRequested event"), Creating( + "The object is being creating on data store"), Created("The object is created"), Ready( + "Template downloading is accomplished"), Copying("The object is being coping"), Migrating( + "The object is being migrated"), Destroying("Template is destroying"), Destroyed( + "Template is destroyed"), Failed("Failed to download template"); String _description; private State(String description) { @@ -42,17 +37,9 @@ public interface ObjectInDataStoreStateMachine extends StateObject callback); + public void revertSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreInfo.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreInfo.java index 3497f7a894f..c69cd3a75cb 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreInfo.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreInfo.java @@ -18,7 +18,6 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; - import org.apache.cloudstack.engine.subsystem.api.storage.disktype.DiskFormat; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -26,12 +25,15 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StoragePool; public interface PrimaryDataStoreInfo extends StoragePool { - public boolean isHypervisorSupported(HypervisorType hypervisor); - public boolean isLocalStorageSupported(); - public boolean isVolumeDiskTypeSupported(DiskFormat diskType); + public boolean isHypervisorSupported(HypervisorType hypervisor); - public String getUuid(); + public boolean isLocalStorageSupported(); - public StoragePoolType getPoolType(); - public PrimaryDataStoreLifeCycle getLifeCycle(); + public boolean isVolumeDiskTypeSupported(DiskFormat diskType); + + public String getUuid(); + + public StoragePoolType getPoolType(); + + public PrimaryDataStoreLifeCycle getLifeCycle(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java index cf29d9fea09..28b06f5234c 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java @@ -18,6 +18,5 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; - public interface PrimaryDataStoreLifeCycle extends DataStoreLifeCycle { } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreParameters.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreParameters.java index b2b787cc133..3b5362a2d06 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreParameters.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreParameters.java @@ -36,6 +36,7 @@ public class PrimaryDataStoreParameters { private String uuid; private String name; private String userInfo; + /** * @return the userInfo */ @@ -44,7 +45,8 @@ public class PrimaryDataStoreParameters { } /** - * @param userInfo the userInfo to set + * @param userInfo + * the userInfo to set */ public void setUserInfo(String userInfo) { this.userInfo = userInfo; @@ -58,7 +60,8 @@ public class PrimaryDataStoreParameters { } /** - * @param name the name to set + * @param name + * the name to set */ public void setName(String name) { this.name = name; @@ -72,7 +75,8 @@ public class PrimaryDataStoreParameters { } /** - * @param uuid the uuid to set + * @param uuid + * the uuid to set */ public void setUuid(String uuid) { this.uuid = uuid; @@ -86,7 +90,8 @@ public class PrimaryDataStoreParameters { } /** - * @param port the port to set + * @param port + * the port to set */ public void setPort(int port) { this.port = port; @@ -100,7 +105,8 @@ public class PrimaryDataStoreParameters { } /** - * @param path the path to set + * @param path + * the path to set */ public void setPath(String path) { this.path = path; @@ -114,7 +120,8 @@ public class PrimaryDataStoreParameters { } /** - * @param host the host to set + * @param host + * the host to set */ public void setHost(String host) { this.host = host; @@ -128,7 +135,8 @@ public class PrimaryDataStoreParameters { } /** - * @param type the type to set + * @param type + * the type to set */ public void setType(StoragePoolType type) { this.type = type; @@ -142,7 +150,8 @@ public class PrimaryDataStoreParameters { } /** - * @param tags the tags to set + * @param tags + * the tags to set */ public void setTags(String tags) { this.tags = tags; @@ -156,7 +165,8 @@ public class PrimaryDataStoreParameters { } /** - * @param details the details to set + * @param details + * the details to set */ public void setDetails(Map details) { this.details = details; @@ -170,7 +180,8 @@ public class PrimaryDataStoreParameters { } /** - * @param providerName the providerName to set + * @param providerName + * the providerName to set */ public void setProviderName(String providerName) { this.providerName = providerName; @@ -184,7 +195,8 @@ public class PrimaryDataStoreParameters { } /** - * @param clusterId the clusterId to set + * @param clusterId + * the clusterId to set */ public void setClusterId(Long clusterId) { this.clusterId = clusterId; @@ -198,7 +210,8 @@ public class PrimaryDataStoreParameters { } /** - * @param podId the podId to set + * @param podId + * the podId to set */ public void setPodId(Long podId) { this.podId = podId; @@ -212,7 +225,8 @@ public class PrimaryDataStoreParameters { } /** - * @param zoneId the zoneId to set + * @param zoneId + * the zoneId to set */ public void setZoneId(Long zoneId) { this.zoneId = zoneId; diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/Scope.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/Scope.java index 25226f984ea..5c71f3cc220 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/Scope.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/Scope.java @@ -22,6 +22,8 @@ import com.cloud.storage.ScopeType; public interface Scope { public ScopeType getScopeType(); + public boolean isSameScope(Scope scope); + public Long getScopeId(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java index 0e9e3b3aec0..04b67d427c1 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java @@ -20,9 +20,10 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.DataStoreRole; - public interface SnapshotDataFactory { public SnapshotInfo getSnapshot(long snapshotId, DataStore store); + public SnapshotInfo getSnapshot(DataObject obj, DataStore store); + public SnapshotInfo getSnapshot(long snapshotId, DataStoreRole role); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotInfo.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotInfo.java index 41ea5f3dd3c..91e0fd79fa9 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotInfo.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotInfo.java @@ -18,13 +18,18 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.Snapshot; - public interface SnapshotInfo extends DataObject, Snapshot { - public SnapshotInfo getParent(); - public String getPath(); - public SnapshotInfo getChild(); - public VolumeInfo getBaseVolume(); - public void addPayload(Object data); + public SnapshotInfo getParent(); + + public String getPath(); + + public SnapshotInfo getChild(); + + public VolumeInfo getBaseVolume(); + + public void addPayload(Object data); + Long getDataCenterId(); + ObjectInDataStoreStateMachine.State getStatus(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotProfile.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotProfile.java index 50a12002cf2..a51a51dedf8 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotProfile.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotProfile.java @@ -19,8 +19,9 @@ package org.apache.cloudstack.engine.subsystem.api.storage; public class SnapshotProfile { - private String _uri; - public String getURI() { - return _uri; - } + private String _uri; + + public String getURI() { + return _uri; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotResult.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotResult.java index a886a86b921..80dbbf83590 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotResult.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotResult.java @@ -16,28 +16,33 @@ // under the License. package org.apache.cloudstack.engine.subsystem.api.storage; - import org.apache.cloudstack.storage.command.CommandResult; import com.cloud.agent.api.Answer; public class SnapshotResult extends CommandResult { - private SnapshotInfo snashot; - private Answer answer; - public SnapshotResult(SnapshotInfo snapshot, Answer answer) { - this.setSnashot(snapshot); - this.setAnswer(answer); - } - public SnapshotInfo getSnashot() { - return snashot; - } - public void setSnashot(SnapshotInfo snashot) { - this.snashot = snashot; - } - public Answer getAnswer() { - return answer; - } - public void setAnswer(Answer answer) { - this.answer = answer; - } + private SnapshotInfo snashot; + private Answer answer; + + public SnapshotResult(SnapshotInfo snapshot, Answer answer) { + super(); + this.setSnashot(snapshot); + this.setAnswer(answer); + } + + public SnapshotInfo getSnashot() { + return snashot; + } + + public void setSnashot(SnapshotInfo snashot) { + this.snashot = snashot; + } + + public Answer getAnswer() { + return answer; + } + + public void setAnswer(Answer answer) { + this.answer = answer; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java index b248054e569..67c88471dfc 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java @@ -17,11 +17,12 @@ package org.apache.cloudstack.engine.subsystem.api.storage; - - public interface SnapshotService { - public SnapshotResult takeSnapshot(SnapshotInfo snapshot); - public SnapshotInfo backupSnapshot(SnapshotInfo snapshot); - public boolean deleteSnapshot(SnapshotInfo snapshot); - public boolean revertSnapshot(SnapshotInfo snapshot); + public SnapshotResult takeSnapshot(SnapshotInfo snapshot); + + public SnapshotInfo backupSnapshot(SnapshotInfo snapshot); + + public boolean deleteSnapshot(SnapshotInfo snapshot); + + public boolean revertSnapshot(SnapshotInfo snapshot); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotStrategy.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotStrategy.java index 2a0d2bb30cb..542246ae36f 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotStrategy.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotStrategy.java @@ -18,12 +18,13 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.Snapshot; - - public interface SnapshotStrategy { - public SnapshotInfo takeSnapshot(SnapshotInfo snapshot); - public SnapshotInfo backupSnapshot(SnapshotInfo snapshot); - public boolean deleteSnapshot(Long snapshotId); + public SnapshotInfo takeSnapshot(SnapshotInfo snapshot); + + public SnapshotInfo backupSnapshot(SnapshotInfo snapshot); + + public boolean deleteSnapshot(Long snapshotId); + /** * @param snapshot * @return diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageCacheManager.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageCacheManager.java index 917a5376526..fd5211f1dd0 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageCacheManager.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageCacheManager.java @@ -18,15 +18,19 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; - public interface StorageCacheManager { public DataStore getCacheStorage(Scope scope); + public DataObject createCacheObject(DataObject data, Scope scope); - /** only create cache object in db + + /** + * only create cache object in db + * * @param data * @param scope * @return */ DataObject getCacheObject(DataObject data, Scope scope); + boolean deleteCacheObject(DataObject data); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageEvent.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageEvent.java index 3f64002ed9e..6147b6ab6cc 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageEvent.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageEvent.java @@ -19,7 +19,5 @@ package org.apache.cloudstack.engine.subsystem.api.storage; public enum StorageEvent { - DownloadTemplateToPrimary, - RegisterTemplate, - CreateVolumeFromTemplate; + DownloadTemplateToPrimary, RegisterTemplate, CreateVolumeFromTemplate; } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageOrchestrator.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageOrchestrator.java index fdb15c7331c..d4455c8059a 100755 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageOrchestrator.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageOrchestrator.java @@ -31,6 +31,7 @@ public interface StorageOrchestrator { /** * Prepares all storage ready for a VM to start + * * @param vm * @param reservationId */ @@ -38,6 +39,7 @@ public interface StorageOrchestrator { /** * Releases all storage that were used for a VM shutdown + * * @param vm * @param disks * @param reservationId @@ -46,6 +48,7 @@ public interface StorageOrchestrator { /** * Destroy all disks + * * @param disks * @param reservationId */ @@ -53,16 +56,21 @@ public interface StorageOrchestrator { /** * Cancel a reservation - * @param reservationId reservation to + * + * @param reservationId + * reservation to */ void cancel(String reservationId); - + /** - * If attaching a volume in allocated state to a running vm, need to create this volume + * If attaching a volume in allocated state to a running vm, need to create + * this volume */ void prepareAttachDiskToVM(long diskId, long vmId, String reservationId); - + boolean createVolume(VolumeEntity volume, long dataStoreId, DiskFormat diskType); + boolean createVolumeFromTemplate(VolumeEntity volume, long dataStoreId, DiskFormat dis, TemplateEntity template); - VolumeEntity allocateVolumeInDb(long size, VolumeType type,String volName, Long templateId); + + VolumeEntity allocateVolumeInDb(long size, VolumeType type, String volName, Long templateId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java index ffced54c28c..13eb0de6f70 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java @@ -29,17 +29,23 @@ import com.cloud.vm.VirtualMachineProfile; /** */ public interface StoragePoolAllocator extends Adapter { - /** - * Determines which storage pools are suitable for the guest virtual machine - * - * @param DiskProfile dskCh - * @param VirtualMachineProfile vmProfile - * @param DeploymentPlan plan - * @param ExcludeList avoid - * @param int returnUpTo (use -1 to return all possible pools) - * @return List List of storage pools that are suitable for the VM - **/ - List allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo); - - public static int RETURN_UPTO_ALL = -1; + /** + * Determines which storage pools are suitable for the guest virtual machine + * + * @param DiskProfile + * dskCh + * @param VirtualMachineProfile + * vmProfile + * @param DeploymentPlan + * plan + * @param ExcludeList + * avoid + * @param int returnUpTo (use -1 to return all possible pools) + * @return List List of storage pools that are suitable for the + * VM + **/ + List allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, + DeploymentPlan plan, ExcludeList avoid, int returnUpTo); + + public static int RETURN_UPTO_ALL = -1; } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageSubSystem.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageSubSystem.java index 8043487d46b..e5a74a452a1 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageSubSystem.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageSubSystem.java @@ -22,8 +22,10 @@ import com.cloud.org.Grouping; public interface StorageSubSystem { String getType(); + Class getScope(); URI grantAccess(String vol, String reservationId); + URI RemoveAccess(String vol, String reservationId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateDataFactory.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateDataFactory.java index 8916f6681cf..0b78da058ed 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateDataFactory.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateDataFactory.java @@ -20,10 +20,12 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.DataStoreRole; - public interface TemplateDataFactory { TemplateInfo getTemplate(long templateId, DataStore store); + TemplateInfo getTemplate(DataObject obj, DataStore store); + TemplateInfo getTemplate(long templateId, DataStoreRole storeRole); + TemplateInfo getTemplate(long templateId, DataStoreRole storeRole, Long zoneId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateEvent.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateEvent.java index c677166b39a..be74c7a9d8a 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateEvent.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateEvent.java @@ -19,8 +19,5 @@ package org.apache.cloudstack.engine.subsystem.api.storage; public enum TemplateEvent { - CreateRequested, - OperationFailed, - OperationSucceeded, - DestroyRequested; + CreateRequested, OperationFailed, OperationSucceeded, DestroyRequested; } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateInfo.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateInfo.java index 3ee1d2faf01..91dba115e09 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateInfo.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateInfo.java @@ -22,5 +22,6 @@ import com.cloud.template.VirtualMachineTemplate; public interface TemplateInfo extends DataObject, VirtualMachineTemplate { public String getUniqueName(); + public String getInstallPath(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateProfile.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateProfile.java index e05e7db67fa..dcfd4074bfd 100755 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateProfile.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateProfile.java @@ -22,266 +22,291 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; -public class TemplateProfile { - Long userId; - String name; - String displayText; - Integer bits; - Boolean passwordEnabled; - Boolean sshKeyEnbaled; - Boolean requiresHvm; - String url; - Boolean isPublic; - Boolean featured; - Boolean isExtractable; - ImageFormat format; - Long guestOsId; - Long zoneId; - HypervisorType hypervisorType; - String accountName; - Long domainId; - Long accountId; - String chksum; - Boolean bootable; - Long templateId; - VirtualMachineTemplate template; - String templateTag; - Map details; - - public TemplateProfile(Long templateId, Long userId, String name, String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHvm, - String url, Boolean isPublic, Boolean featured, Boolean isExtractable, ImageFormat format, Long guestOsId, Long zoneId, - HypervisorType hypervisorType, String accountName, Long domainId, Long accountId, String chksum, Boolean bootable, Map details, Boolean sshKeyEnabled) { - this.templateId = templateId; - this.userId = userId; - this.name = name; - this.displayText = displayText; - this.bits = bits; - this.passwordEnabled = passwordEnabled; - this.requiresHvm = requiresHvm; - this.url = url; - this.isPublic = isPublic; - this.featured = featured; - this.isExtractable = isExtractable; - this.format = format; - this.guestOsId = guestOsId; - this.zoneId = zoneId; - this.hypervisorType = hypervisorType; - this.accountName = accountName; - this.domainId = domainId; - this.accountId = accountId; - this.chksum = chksum; - this.bootable = bootable; - this.details = details; - this.sshKeyEnbaled = sshKeyEnabled; - } - - public TemplateProfile(Long userId, VirtualMachineTemplate template, Long zoneId) { - this.userId = userId; - this.template = template; - this.zoneId = zoneId; - } - - public TemplateProfile(Long templateId, Long userId, String name, String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHvm, - String url, Boolean isPublic, Boolean featured, Boolean isExtractable, ImageFormat format, Long guestOsId, Long zoneId, - HypervisorType hypervisorType, String accountName, Long domainId, Long accountId, String chksum, Boolean bootable, String templateTag, Map details, Boolean sshKeyEnabled) { - this(templateId, userId, name, displayText, bits, passwordEnabled, requiresHvm, url, isPublic, featured, isExtractable, format, guestOsId, zoneId, - hypervisorType, accountName, domainId, accountId, chksum, bootable, details, sshKeyEnabled); +public class TemplateProfile { + Long userId; + String name; + String displayText; + Integer bits; + Boolean passwordEnabled; + Boolean sshKeyEnbaled; + Boolean requiresHvm; + String url; + Boolean isPublic; + Boolean featured; + Boolean isExtractable; + ImageFormat format; + Long guestOsId; + Long zoneId; + HypervisorType hypervisorType; + String accountName; + Long domainId; + Long accountId; + String chksum; + Boolean bootable; + Long templateId; + VirtualMachineTemplate template; + String templateTag; + Map details; + + public TemplateProfile(Long templateId, Long userId, String name, String displayText, Integer bits, + Boolean passwordEnabled, Boolean requiresHvm, String url, Boolean isPublic, Boolean featured, + Boolean isExtractable, ImageFormat format, Long guestOsId, Long zoneId, HypervisorType hypervisorType, + String accountName, Long domainId, Long accountId, String chksum, Boolean bootable, Map details, + Boolean sshKeyEnabled) { + this.templateId = templateId; + this.userId = userId; + this.name = name; + this.displayText = displayText; + this.bits = bits; + this.passwordEnabled = passwordEnabled; + this.requiresHvm = requiresHvm; + this.url = url; + this.isPublic = isPublic; + this.featured = featured; + this.isExtractable = isExtractable; + this.format = format; + this.guestOsId = guestOsId; + this.zoneId = zoneId; + this.hypervisorType = hypervisorType; + this.accountName = accountName; + this.domainId = domainId; + this.accountId = accountId; + this.chksum = chksum; + this.bootable = bootable; + this.details = details; + this.sshKeyEnbaled = sshKeyEnabled; + } + + public TemplateProfile(Long userId, VirtualMachineTemplate template, Long zoneId) { + this.userId = userId; + this.template = template; + this.zoneId = zoneId; + } + + public TemplateProfile(Long templateId, Long userId, String name, String displayText, Integer bits, + Boolean passwordEnabled, Boolean requiresHvm, String url, Boolean isPublic, Boolean featured, + Boolean isExtractable, ImageFormat format, Long guestOsId, Long zoneId, HypervisorType hypervisorType, + String accountName, Long domainId, Long accountId, String chksum, Boolean bootable, String templateTag, + Map details, Boolean sshKeyEnabled) { + this(templateId, userId, name, displayText, bits, passwordEnabled, requiresHvm, url, isPublic, featured, + isExtractable, format, guestOsId, zoneId, hypervisorType, accountName, domainId, accountId, chksum, + bootable, details, sshKeyEnabled); this.templateTag = templateTag; - } - - public Long getTemplateId() { - return templateId; - } - public void setTemplateId(Long id) { - this.templateId = id; - } - - public Long getUserId() { - return userId; - } - public void setUserId(Long userId) { - this.userId = userId; - } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - public String getDisplayText() { - return displayText; - } - public void setDisplayText(String text) { - this.displayText = text; - } - - public Integer getBits() { - return bits; - } - public void setBits(Integer bits) { - this.bits = bits; - } - - public Boolean getPasswordEnabled() { - return passwordEnabled; - } - public void setPasswordEnabled(Boolean enabled) { - this.passwordEnabled = enabled; - } - - public Boolean getRequiresHVM() { - return requiresHvm; - } - public void setRequiresHVM(Boolean hvm) { - this.requiresHvm = hvm; - } - - public String getUrl() { - return url; - } - public void setUrl(String url) { - this.url = url; - } - - public Boolean getIsPublic() { - return isPublic; - } - public void setIsPublic(Boolean is) { - this.isPublic = is; - } - - public Boolean getFeatured() { - return featured; - } - public void setFeatured(Boolean featured) { - this.featured = featured; - } - - public Boolean getIsExtractable() { - return isExtractable; - } - public void setIsExtractable(Boolean is) { - this.isExtractable = is; - } - - public ImageFormat getFormat() { - return format; - } - public void setFormat(ImageFormat format) { - this.format = format; - } - - public Long getGuestOsId() { - return guestOsId; - } - public void setGuestOsId(Long id) { - this.guestOsId = id; - } - - public Long getZoneId() { - return zoneId; - } - public void setZoneId(Long id) { - this.zoneId = id; - } - - public HypervisorType getHypervisorType() { - return hypervisorType; - } - public void setHypervisorType(HypervisorType type) { - this.hypervisorType = type; - } - - public Long getDomainId() { - return domainId; - } - public void setDomainId(Long id) { - this.domainId = id; - } - - public Long getAccountId() { - return accountId; - } - public void setAccountId(Long id) { - this.accountId = id; - } - - public String getCheckSum() { - return chksum; - } - public void setCheckSum(String chksum) { - this.chksum = chksum; - } - - public Boolean getBootable() { - return this.bootable; - } - public void setBootable(Boolean bootable) { - this.bootable = bootable; - } - - public VirtualMachineTemplate getTemplate() { - return template; - } - public void setTemplate(VirtualMachineTemplate template) { - this.template = template; - } - + } + + public Long getTemplateId() { + return templateId; + } + + public void setTemplateId(Long id) { + this.templateId = id; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String text) { + this.displayText = text; + } + + public Integer getBits() { + return bits; + } + + public void setBits(Integer bits) { + this.bits = bits; + } + + public Boolean getPasswordEnabled() { + return passwordEnabled; + } + + public void setPasswordEnabled(Boolean enabled) { + this.passwordEnabled = enabled; + } + + public Boolean getRequiresHVM() { + return requiresHvm; + } + + public void setRequiresHVM(Boolean hvm) { + this.requiresHvm = hvm; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Boolean getIsPublic() { + return isPublic; + } + + public void setIsPublic(Boolean is) { + this.isPublic = is; + } + + public Boolean getFeatured() { + return featured; + } + + public void setFeatured(Boolean featured) { + this.featured = featured; + } + + public Boolean getIsExtractable() { + return isExtractable; + } + + public void setIsExtractable(Boolean is) { + this.isExtractable = is; + } + + public ImageFormat getFormat() { + return format; + } + + public void setFormat(ImageFormat format) { + this.format = format; + } + + public Long getGuestOsId() { + return guestOsId; + } + + public void setGuestOsId(Long id) { + this.guestOsId = id; + } + + public Long getZoneId() { + return zoneId; + } + + public void setZoneId(Long id) { + this.zoneId = id; + } + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + public void setHypervisorType(HypervisorType type) { + this.hypervisorType = type; + } + + public Long getDomainId() { + return domainId; + } + + public void setDomainId(Long id) { + this.domainId = id; + } + + public Long getAccountId() { + return accountId; + } + + public void setAccountId(Long id) { + this.accountId = id; + } + + public String getCheckSum() { + return chksum; + } + + public void setCheckSum(String chksum) { + this.chksum = chksum; + } + + public Boolean getBootable() { + return this.bootable; + } + + public void setBootable(Boolean bootable) { + this.bootable = bootable; + } + + public VirtualMachineTemplate getTemplate() { + return template; + } + + public void setTemplate(VirtualMachineTemplate template) { + this.template = template; + } + public String getTemplateTag() { return templateTag; - } + } public void setTemplateTag(String templateTag) { this.templateTag = templateTag; - } - + } + public Map getDetails() { - return this.details; + return this.details; } - + public void setDetails(Map details) { - this.details = details; + this.details = details; } - + public void setSshKeyEnabled(Boolean enabled) { - this.sshKeyEnbaled = enabled; + this.sshKeyEnbaled = enabled; } - + public Boolean getSshKeyEnabled() { - return this.sshKeyEnbaled; + return this.sshKeyEnbaled; } - + public String getImageStorageUri() { - return null; + return null; } - + public void setLocalPath(String path) { - + } - + public String getLocalPath() { - return null; + return null; } - + public String getJobId() { - return null; + return null; } - + public void setTemplatePoolRefId(long id) { - + } - + public long getId() { - return 0; + return 0; } - + public long getTemplatePoolRefId() { - return 0; + return 0; } - + public long getSize() { - return 0; + return 0; } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java index 5e0c9f278a1..52e18f195f1 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java @@ -22,8 +22,6 @@ import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.storage.command.CommandResult; - - import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.StoragePool; @@ -31,7 +29,9 @@ public interface TemplateService { public class TemplateApiResult extends CommandResult { private final TemplateInfo template; + public TemplateApiResult(TemplateInfo template) { + super(); this.template = template; } @@ -40,16 +40,25 @@ public interface TemplateService { } } - void createTemplateAsync(TemplateInfo template, DataStore store, AsyncCompletionCallback callback); - AsyncCallFuture createTemplateFromSnapshotAsync(SnapshotInfo snapshot, TemplateInfo template, DataStore store); - AsyncCallFuture createTemplateFromVolumeAsync(VolumeInfo volume, TemplateInfo template, DataStore store); + + AsyncCallFuture createTemplateFromSnapshotAsync(SnapshotInfo snapshot, TemplateInfo template, + DataStore store); + + AsyncCallFuture createTemplateFromVolumeAsync(VolumeInfo volume, TemplateInfo template, + DataStore store); + AsyncCallFuture deleteTemplateAsync(TemplateInfo template); + AsyncCallFuture copyTemplate(TemplateInfo srcTemplate, DataStore destStore); - AsyncCallFuture prepareTemplateOnPrimary(TemplateInfo srcTemplate, StoragePool pool ); + + AsyncCallFuture prepareTemplateOnPrimary(TemplateInfo srcTemplate, StoragePool pool); void handleSysTemplateDownload(HypervisorType hostHyper, Long dcId); + void handleTemplateSync(DataStore store); + void downloadBootstrapSysTemplate(DataStore store); + void addSystemVMTemplatesToSecondary(DataStore store); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateState.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateState.java index ef2488080f8..43ea82a2688 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateState.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateState.java @@ -19,9 +19,5 @@ package org.apache.cloudstack.engine.subsystem.api.storage; public enum TemplateState { - Allocated, - Creating, - Destroying, - Destroyed, - Ready; + Allocated, Creating, Destroying, Destroyed, Ready; } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeDataFactory.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeDataFactory.java index 1518fd2eb43..fc65a32c33e 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeDataFactory.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeDataFactory.java @@ -18,9 +18,10 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; - public interface VolumeDataFactory { VolumeInfo getVolume(long volumeId, DataStore store); + VolumeInfo getVolume(DataObject volume, DataStore store); + VolumeInfo getVolume(long volumeId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java index 7165f370bac..d0b9be99678 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java @@ -22,10 +22,15 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Volume; public interface VolumeInfo extends DataObject, Volume { - public boolean isAttachedVM(); - public void addPayload(Object data); - public Object getpayload(); - public HypervisorType getHypervisorType(); - public Long getLastPoolId(); - public String getAttachedVmName(); + public boolean isAttachedVM(); + + public void addPayload(Object data); + + public Object getpayload(); + + public HypervisorType getHypervisorType(); + + public Long getLastPoolId(); + + public String getAttachedVmName(); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeProfile.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeProfile.java index ed4d42187be..8701912f304 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeProfile.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeProfile.java @@ -19,16 +19,17 @@ package org.apache.cloudstack.engine.subsystem.api.storage; public class VolumeProfile { - private String _uri; - public String getURI() { - return _uri; - } - - public String getPath() { - return null; - } - - public long getSize() { - return 0; - } + private String _uri; + + public String getURI() { + return _uri; + } + + public String getPath() { + return null; + } + + public long getSize() { + return 0; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java index 3f725e1077c..39479523271 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import java.util.Map; + import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.storage.command.CommandResult; @@ -31,7 +32,9 @@ public interface VolumeService { public class VolumeApiResult extends CommandResult { private final VolumeInfo volume; + public VolumeApiResult(VolumeInfo volume) { + super(); this.volume = volume; } @@ -42,16 +45,16 @@ public interface VolumeService { /** * Creates the volume based on the given criteria - * + * * @param cmd - * + * * @return the volume object */ AsyncCallFuture createVolumeAsync(VolumeInfo volume, DataStore store); /** * Delete volume - * + * * @param volumeId * @return * @throws ConcurrentOperationException @@ -66,15 +69,19 @@ public interface VolumeService { /** * */ - AsyncCallFuture createVolumeFromSnapshot(VolumeInfo volume, DataStore store, SnapshotInfo snapshot); - + AsyncCallFuture createVolumeFromSnapshot(VolumeInfo volume, DataStore store, SnapshotInfo snapshot); VolumeEntity getVolumeEntity(long volumeId); - AsyncCallFuture createVolumeFromTemplateAsync(VolumeInfo volume, long dataStoreId, TemplateInfo template); + AsyncCallFuture createVolumeFromTemplateAsync(VolumeInfo volume, long dataStoreId, + TemplateInfo template); + AsyncCallFuture copyVolume(VolumeInfo srcVolume, DataStore destStore); + AsyncCallFuture migrateVolume(VolumeInfo srcVolume, DataStore destStore); - AsyncCallFuture migrateVolumes(Map volumeMap, VirtualMachineTO vmTo, Host srcHost, Host destHost); + + AsyncCallFuture migrateVolumes(Map volumeMap, VirtualMachineTO vmTo, + Host srcHost, Host destHost); boolean destroyVolume(long volumeId) throws ConcurrentOperationException; @@ -84,6 +91,6 @@ public interface VolumeService { void handleVolumeSync(DataStore store); - SnapshotInfo takeSnapshot(VolumeInfo volume); + SnapshotInfo takeSnapshot(VolumeInfo volume); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java index a71a9c7ffb5..9ba1d10012a 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java @@ -20,15 +20,14 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; - public class ZoneScope extends AbstractScope { private ScopeType type = ScopeType.ZONE; private Long zoneId; - + public ZoneScope(Long zoneId) { this.zoneId = zoneId; } - + @Override public ScopeType getScopeType() { return this.type; diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/disktype/DiskFormat.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/disktype/DiskFormat.java index e059fa90320..6be7a6bb49e 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/disktype/DiskFormat.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/disktype/DiskFormat.java @@ -19,10 +19,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage.disktype; import com.cloud.utils.exception.CloudRuntimeException; public enum DiskFormat { - VMDK, - VHD, - ISO, - QCOW2; + VMDK, VHD, ISO, QCOW2; public static DiskFormat getFormat(String format) { if (VMDK.toString().equalsIgnoreCase(format)) { return VMDK; diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/BaseImage.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/BaseImage.java index 9991cedfa27..495d45c183c 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/BaseImage.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/BaseImage.java @@ -17,7 +17,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage.type; public class BaseImage extends VolumeTypeBase { - public BaseImage() { - this.type = "BaseImage"; - } + public BaseImage() { + this.type = "BaseImage"; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/DataDisk.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/DataDisk.java index 762233e940f..a533f55d31c 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/DataDisk.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/DataDisk.java @@ -20,7 +20,7 @@ import org.springframework.stereotype.Component; @Component public class DataDisk extends VolumeTypeBase { - public DataDisk() { - this.type = "DataDisk"; - } + public DataDisk() { + this.type = "DataDisk"; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Iso.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Iso.java index 43611b461b1..85c62725597 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Iso.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Iso.java @@ -20,7 +20,7 @@ import org.springframework.stereotype.Component; @Component public class Iso extends VolumeTypeBase { - public Iso() { - this.type = "iso"; - } + public Iso() { + this.type = "iso"; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/RootDisk.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/RootDisk.java index 723d59c66cf..e8f4ce5c128 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/RootDisk.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/RootDisk.java @@ -20,7 +20,7 @@ import org.springframework.stereotype.Component; @Component public class RootDisk extends VolumeTypeBase { - public RootDisk() { - this.type = "Root"; - } + public RootDisk() { + this.type = "Root"; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Unknown.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Unknown.java index 6f8904a5af2..f264d21757f 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Unknown.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/Unknown.java @@ -17,8 +17,8 @@ package org.apache.cloudstack.engine.subsystem.api.storage.type; public class Unknown extends VolumeTypeBase { - public Unknown() { - this.type = "Unknown"; - } + public Unknown() { + this.type = "Unknown"; + } } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeBase.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeBase.java index 6ffd9d7c9c8..cf466ea8144 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeBase.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeBase.java @@ -17,31 +17,31 @@ package org.apache.cloudstack.engine.subsystem.api.storage.type; public class VolumeTypeBase implements VolumeType { - protected String type = "Unknown"; - - @Override - public boolean equals(Object that) { - if (this == that) { - return true; - } - if (that instanceof String) { - if (this.toString().equalsIgnoreCase((String)that)) { - return true; - } - } else if (that instanceof VolumeTypeBase) { - VolumeTypeBase th = (VolumeTypeBase)that; - if (this.toString().equalsIgnoreCase(th.toString())) { - return true; - } - } else { - return false; - } - return false; - } - - @Override - public String toString() { - return type; - } - + protected String type = "Unknown"; + + @Override + public boolean equals(Object that) { + if (this == that) { + return true; + } + if (that instanceof String) { + if (this.toString().equalsIgnoreCase((String) that)) { + return true; + } + } else if (that instanceof VolumeTypeBase) { + VolumeTypeBase th = (VolumeTypeBase) that; + if (this.toString().equalsIgnoreCase(th.toString())) { + return true; + } + } else { + return false; + } + return false; + } + + @Override + public String toString() { + return type; + } + } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeHelper.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeHelper.java index f29dd08721f..6dc2cd48c3d 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeHelper.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/type/VolumeTypeHelper.java @@ -24,21 +24,21 @@ import org.springframework.stereotype.Component; @Component public class VolumeTypeHelper { - static private List types; - private static VolumeType defaultType = new Unknown(); - - @Inject - public void setTypes(List types) { - VolumeTypeHelper.types = types; - } - - public static VolumeType getType(String type) { - for (VolumeType ty : types) { - if (ty.equals(type)) { - return ty; - } - } - return VolumeTypeHelper.defaultType; - } - + static private List types; + private static VolumeType defaultType = new Unknown(); + + @Inject + public void setTypes(List types) { + VolumeTypeHelper.types = types; + } + + public static VolumeType getType(String type) { + for (VolumeType ty : types) { + if (ty.equals(type)) { + return ty; + } + } + return VolumeTypeHelper.defaultType; + } + } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/AttachAnswer.java b/engine/api/src/org/apache/cloudstack/storage/command/AttachAnswer.java index 092ec63df44..5a26d4a3f13 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/AttachAnswer.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/AttachAnswer.java @@ -23,6 +23,7 @@ import com.cloud.agent.api.to.DiskTO; public class AttachAnswer extends Answer { private DiskTO disk; + public AttachAnswer() { super(null); } @@ -31,6 +32,7 @@ public class AttachAnswer extends Answer { super(null); this.setDisk(disk); } + public AttachAnswer(String errMsg) { super(null, false, errMsg); } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/AttachCommand.java b/engine/api/src/org/apache/cloudstack/storage/command/AttachCommand.java index fa205a55eb6..6b4e9f7ed00 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/AttachCommand.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/AttachCommand.java @@ -18,33 +18,36 @@ */ package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Command; import com.cloud.agent.api.to.DiskTO; -public class AttachCommand extends Command implements StorageSubSystemCommand { +public final class AttachCommand extends Command implements StorageSubSystemCommand { private DiskTO disk; private String vmName; - + public AttachCommand(DiskTO disk, String vmName) { + super(); this.disk = disk; this.vmName = vmName; } - + @Override public boolean executeInSequence() { - // TODO Auto-generated method stub return false; } + public DiskTO getDisk() { return disk; } + public void setDisk(DiskTO disk) { this.disk = disk; } + public String getVmName() { return vmName; } + public void setVmName(String vmName) { this.vmName = vmName; } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreAnswer.java b/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreAnswer.java index cd15030084d..6d5bbaf6a68 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreAnswer.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreAnswer.java @@ -25,30 +25,31 @@ public class AttachPrimaryDataStoreAnswer extends Answer { private String uuid; private long capacity; private long avail; + public AttachPrimaryDataStoreAnswer(Command cmd) { super(cmd); } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public String getUuid() { return this.uuid; } - + public void setCapacity(long capacity) { this.capacity = capacity; } - + public long getCapacity() { return this.capacity; } - + public void setAvailable(long avail) { this.avail = avail; } - + public long getAvailable() { return this.avail; } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java b/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java index 15573a08a32..2083876b567 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java @@ -18,22 +18,22 @@ */ package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Command; -public class AttachPrimaryDataStoreCmd extends Command implements StorageSubSystemCommand { +public final class AttachPrimaryDataStoreCmd extends Command implements StorageSubSystemCommand { private final String dataStore; + public AttachPrimaryDataStoreCmd(String uri) { + super(); this.dataStore = uri; } - + public String getDataStore() { return this.dataStore; } @Override public boolean executeInSequence() { - // TODO Auto-generated method stub return false; } } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/CommandResult.java b/engine/api/src/org/apache/cloudstack/storage/command/CommandResult.java index 129f6f82375..0a33c519f01 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/CommandResult.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/CommandResult.java @@ -21,27 +21,28 @@ package org.apache.cloudstack.storage.command; public class CommandResult { private boolean success; private String result; + public CommandResult() { this.success = true; this.result = ""; } - + public boolean isSuccess() { return this.success; } - + public boolean isFailed() { return !this.success; } - + public void setSuccess(boolean success) { this.success = success; } - + public String getResult() { return this.result; } - + public void setResult(String result) { this.result = result; if (result != null) { @@ -49,4 +50,3 @@ public class CommandResult { } } } - \ No newline at end of file diff --git a/engine/api/src/org/apache/cloudstack/storage/command/CopyCmdAnswer.java b/engine/api/src/org/apache/cloudstack/storage/command/CopyCmdAnswer.java index 132832af636..95c0e8990f8 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/CopyCmdAnswer.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/CopyCmdAnswer.java @@ -16,23 +16,21 @@ // under the License. package org.apache.cloudstack.storage.command; - - import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataTO; public class CopyCmdAnswer extends Answer { private DataTO newData; - + public CopyCmdAnswer(DataTO newData) { super(null); this.newData = newData; } - + public DataTO getNewData() { return this.newData; } - + public CopyCmdAnswer(String errMsg) { super(null, false, errMsg); } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/CopyCommand.java b/engine/api/src/org/apache/cloudstack/storage/command/CopyCommand.java index d512e60d779..852d8013c93 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/CopyCommand.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/CopyCommand.java @@ -16,11 +16,10 @@ // under the License. package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Command; import com.cloud.agent.api.to.DataTO; -public class CopyCommand extends Command implements StorageSubSystemCommand { +public final class CopyCommand extends Command implements StorageSubSystemCommand { private DataTO srcTO; private DataTO destTO; private DataTO cacheTO; @@ -31,11 +30,11 @@ public class CopyCommand extends Command implements StorageSubSystemCommand { this.destTO = destData; this.setWait(timeout); } - + public DataTO getDestTO() { return this.destTO; } - + public DataTO getSrcTO() { return this.srcTO; } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectAnswer.java b/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectAnswer.java index 2c174e4687f..b0c47447f6f 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectAnswer.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectAnswer.java @@ -18,12 +18,12 @@ */ package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataTO; -public class CreateObjectAnswer extends Answer { +public final class CreateObjectAnswer extends Answer { private DataTO data; + protected CreateObjectAnswer() { super(); } @@ -32,12 +32,12 @@ public class CreateObjectAnswer extends Answer { super(); this.data = data; } - + public DataTO getData() { return this.data; } - + public CreateObjectAnswer(String errMsg) { super(null, false, errMsg); - } + } } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java b/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java index dfadc2dcea1..a282a51e78a 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java @@ -18,11 +18,10 @@ */ package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Command; import com.cloud.agent.api.to.DataTO; -public class CreateObjectCommand extends Command implements StorageSubSystemCommand { +public final class CreateObjectCommand extends Command implements StorageSubSystemCommand { private DataTO data; public CreateObjectCommand(DataTO obj) { @@ -39,7 +38,7 @@ public class CreateObjectCommand extends Command implements StorageSubSystemComm // TODO Auto-generated method stub return false; } - + public DataTO getData() { return this.data; } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java b/engine/api/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java index 59ed0a8c2ea..b536028927f 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java @@ -16,22 +16,22 @@ // under the License. package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Command; -public class CreatePrimaryDataStoreCmd extends Command implements StorageSubSystemCommand { +public final class CreatePrimaryDataStoreCmd extends Command implements StorageSubSystemCommand { private final String dataStore; + public CreatePrimaryDataStoreCmd(String uri) { + super(); this.dataStore = uri; } - + public String getDataStore() { return this.dataStore; } - + @Override public boolean executeInSequence() { - // TODO Auto-generated method stub return false; } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/DeleteCommand.java b/engine/api/src/org/apache/cloudstack/storage/command/DeleteCommand.java index 41af42c58ab..76696da30ae 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/DeleteCommand.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/DeleteCommand.java @@ -18,25 +18,26 @@ */ package org.apache.cloudstack.storage.command; - import com.cloud.agent.api.Command; import com.cloud.agent.api.to.DataTO; -public class DeleteCommand extends Command implements StorageSubSystemCommand { - private DataTO data; +public final class DeleteCommand extends Command implements StorageSubSystemCommand { + private DataTO data; + public DeleteCommand(DataTO data) { + super(); this.data = data; } - + protected DeleteCommand() { - + super(); } + @Override public boolean executeInSequence() { - // TODO Auto-generated method stub return false; } - + public DataTO getData() { return this.data; } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/DettachAnswer.java b/engine/api/src/org/apache/cloudstack/storage/command/DettachAnswer.java index 6606a7fd743..62ce2465ab5 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/DettachAnswer.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/DettachAnswer.java @@ -21,8 +21,9 @@ package org.apache.cloudstack.storage.command; import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DiskTO; -public class DettachAnswer extends Answer { +public final class DettachAnswer extends Answer { private DiskTO disk; + public DettachAnswer() { super(null); } @@ -31,6 +32,7 @@ public class DettachAnswer extends Answer { super(null); this.setDisk(disk); } + public DettachAnswer(String errMsg) { super(null, false, errMsg); } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/DettachCommand.java b/engine/api/src/org/apache/cloudstack/storage/command/DettachCommand.java index c435e102120..a0ab4b2e6f4 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/DettachCommand.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/DettachCommand.java @@ -24,29 +24,32 @@ import com.cloud.agent.api.to.DiskTO; public class DettachCommand extends Command implements StorageSubSystemCommand { private DiskTO disk; private String vmName; - + public DettachCommand(DiskTO disk, String vmName) { + super(); this.disk = disk; this.vmName = vmName; } - + @Override public boolean executeInSequence() { - // TODO Auto-generated method stub return false; } + public DiskTO getDisk() { return disk; } + public void setDisk(DiskTO disk) { this.disk = disk; } + public String getVmName() { return vmName; } + public void setVmName(String vmName) { this.vmName = vmName; } - } diff --git a/engine/api/src/org/apache/cloudstack/storage/command/DownloadSystemTemplateCommand.java b/engine/api/src/org/apache/cloudstack/storage/command/DownloadSystemTemplateCommand.java index 864f5b6a931..9528ff788d8 100644 --- a/engine/api/src/org/apache/cloudstack/storage/command/DownloadSystemTemplateCommand.java +++ b/engine/api/src/org/apache/cloudstack/storage/command/DownloadSystemTemplateCommand.java @@ -16,138 +16,114 @@ // under the License. package org.apache.cloudstack.storage.command; - - import com.cloud.agent.api.Command; import com.cloud.agent.api.storage.PasswordAuth; import com.cloud.agent.api.storage.Proxy; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.template.VirtualMachineTemplate; - public class DownloadSystemTemplateCommand extends Command { - - private PasswordAuth auth; - private Proxy _proxy; - private DataStoreTO _store; + private PasswordAuth auth; + private Proxy _proxy; + private DataStoreTO _store; private Long resourceId; private Long accountId; private String url; private Long maxDownloadSizeInBytes; private String name; - protected DownloadSystemTemplateCommand() { - } + protected DownloadSystemTemplateCommand() { + super(); + } - - - public DownloadSystemTemplateCommand(DataStoreTO store, String secUrl, VirtualMachineTemplate template, Long maxDownloadSizeInBytes) { - this._store = store; - this.accountId = template.getAccountId(); - this.url = secUrl; - this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; - this.resourceId = template.getId(); - this.name = template.getUniqueName(); - } - - - public DownloadSystemTemplateCommand(DataStoreTO store, String secUrl, String url, VirtualMachineTemplate template, String user, String passwd, Long maxDownloadSizeInBytes) { + public DownloadSystemTemplateCommand(DataStoreTO store, String secUrl, VirtualMachineTemplate template, + Long maxDownloadSizeInBytes) { + super(); this._store = store; this.accountId = template.getAccountId(); this.url = secUrl; this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; this.resourceId = template.getId(); - auth = new PasswordAuth(user, passwd); - this.name = template.getUniqueName(); - } + this.name = template.getUniqueName(); + } + public DownloadSystemTemplateCommand(DataStoreTO store, String secUrl, String url, VirtualMachineTemplate template, + String user, String passwd, Long maxDownloadSizeInBytes) { + super(); + this._store = store; + this.accountId = template.getAccountId(); + this.url = secUrl; + this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; + this.resourceId = template.getId(); + auth = new PasswordAuth(user, passwd); + this.name = template.getUniqueName(); + } + public PasswordAuth getAuth() { + return auth; + } + public void setCreds(String userName, String passwd) { + auth = new PasswordAuth(userName, passwd); + } - public PasswordAuth getAuth() { - return auth; - } + public Proxy getProxy() { + return _proxy; + } - public void setCreds(String userName, String passwd) { - auth = new PasswordAuth(userName, passwd); - } - - public Proxy getProxy() { - return _proxy; - } - - public void setProxy(Proxy proxy) { - _proxy = proxy; - } - - public Long getMaxDownloadSizeInBytes() { - return maxDownloadSizeInBytes; - } + public void setProxy(Proxy proxy) { + _proxy = proxy; + } + public Long getMaxDownloadSizeInBytes() { + return maxDownloadSizeInBytes; + } public DataStoreTO getDataStore() { return _store; } - public void setDataStore(DataStoreTO _store) { this._store = _store; } - public Long getResourceId() { return resourceId; } - public void setResourceId(Long resourceId) { this.resourceId = resourceId; } - - public Long getAccountId() { return accountId; } - - public void setAccountId(Long accountId) { this.accountId = accountId; } - - public String getUrl() { return url; } - - public void setUrl(String url) { this.url = url; } - - public String getName() { return name; } - - public void setName(String name) { this.name = name; } - - @Override public boolean executeInSequence() { // TODO Auto-generated method stub return false; } - } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java index 4ac2ffc9c91..8d63a82be69 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java @@ -20,16 +20,18 @@ package org.apache.cloudstack.storage.datastore.db; import java.util.List; - import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; - import com.cloud.utils.db.GenericDao; public interface ImageStoreDao extends GenericDao { public ImageStoreVO findByName(String name); + public List findByProvider(String provider); + public List findByScope(ZoneScope scope); + public List findImageCacheByScope(ZoneScope scope); + public List listImageStores(); } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailVO.java index 63ac9e4f3f9..b9221489e05 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailVO.java @@ -26,20 +26,20 @@ import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(name="image_store_details") +@Table(name = "image_store_details") public class ImageStoreDetailVO implements InternalIdentity { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") long id; - @Column(name="store_id") + @Column(name = "store_id") long storeId; - @Column(name="name") + @Column(name = "name") String name; - @Column(name="value") + @Column(name = "value") String value; public ImageStoreDetailVO() { @@ -79,5 +79,4 @@ public class ImageStoreDetailVO implements InternalIdentity { this.value = value; } - } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDao.java index 033a818faa7..91fff280d91 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDao.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDao.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.storage.datastore.db; import java.util.Map; - import com.cloud.utils.db.GenericDao; public interface ImageStoreDetailsDao extends GenericDao { diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java index fb320477603..3c903ad6e20 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java @@ -37,7 +37,8 @@ import com.cloud.utils.db.GenericDao; @Table(name = "image_store") public class ImageStoreVO implements ImageStore { @Id - @TableGenerator(name = "image_store_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "image_store_seq", allocationSize = 1) + @TableGenerator(name = "image_store_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", + pkColumnValue = "image_store_seq", allocationSize = 1) @Column(name = "id", nullable = false) private long id; @@ -76,7 +77,7 @@ public class ImageStoreVO implements ImageStore { @Column(name = "parent") private String parent; - @Column(name="total_size") + @Column(name = "total_size") private Long totalSize; public DataStoreRole getRole() { @@ -179,5 +180,4 @@ public class ImageStoreVO implements ImageStore { this.totalSize = totalSize; } - } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java index 16fed3586aa..5458de58725 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java @@ -20,93 +20,104 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; - import com.cloud.storage.ScopeType; import com.cloud.storage.StoragePoolStatus; import com.cloud.utils.db.GenericDao; + /** * Data Access Object for storage_pool table */ public interface PrimaryDataStoreDao extends GenericDao { - /** - * @param datacenterId -- the id of the datacenter (availability zone) - */ - List listByDataCenterId(long datacenterId); - - /** - * @param datacenterId -- the id of the datacenter (availability zone) - */ - List listBy(long datacenterId, long podId, Long clusterId, ScopeType scope); - - /** - * Set capacity of storage pool in bytes - * @param id pool id. - * @param capacity capacity in bytes - */ + /** + * @param datacenterId + * -- the id of the datacenter (availability zone) + */ + List listByDataCenterId(long datacenterId); + + /** + * @param datacenterId + * -- the id of the datacenter (availability zone) + */ + List listBy(long datacenterId, long podId, Long clusterId, ScopeType scope); + + /** + * Set capacity of storage pool in bytes + * + * @param id + * pool id. + * @param capacity + * capacity in bytes + */ void updateCapacity(long id, long capacity); - - /** - * Set available bytes of storage pool in bytes - * @param id pool id. - * @param available available capacity in bytes - */ + + /** + * Set available bytes of storage pool in bytes + * + * @param id + * pool id. + * @param available + * available capacity in bytes + */ void updateAvailable(long id, long available); - - + StoragePoolVO persist(StoragePoolVO pool, Map details); - + /** * Find pool by name. * - * @param name name of pool. - * @return the single StoragePoolVO + * @param name + * name of pool. + * @return the single StoragePoolVO */ List findPoolByName(String name); - + /** * Find pools by the pod that matches the details. * - * @param podId pod id to find the pools in. - * @param details details to match. All must match for the pool to be returned. + * @param podId + * pod id to find the pools in. + * @param details + * details to match. All must match for the pool to be returned. * @return List of StoragePoolVO */ - List findPoolsByDetails(long dcId, long podId, Long clusterId, Map details, ScopeType scope); - + List findPoolsByDetails(long dcId, long podId, Long clusterId, Map details, + ScopeType scope); + List findPoolsByTags(long dcId, long podId, Long clusterId, String[] tags); - + /** * Find pool by UUID. * - * @param uuid uuid of pool. - * @return the single StoragePoolVO + * @param uuid + * uuid of pool. + * @return the single StoragePoolVO */ StoragePoolVO findPoolByUUID(String uuid); List listByStorageHost(String hostFqdnOrIp); StoragePoolVO findPoolByHostPath(long dcId, Long podId, String host, String path, String uuid); - + List listPoolByHostPath(String host, String path); - + void updateDetails(long poolId, Map details); - + Map getDetails(long poolId); - List searchForStoragePoolDetails(long poolId, String value); - - List findIfDuplicatePoolsExistByUUID(String uuid); + List searchForStoragePoolDetails(long poolId, String value); + + List findIfDuplicatePoolsExistByUUID(String uuid); List listByStatus(StoragePoolStatus status); long countPoolsByStatus(StoragePoolStatus... statuses); - List listByStatusInZone(long dcId, StoragePoolStatus status); - + List listByStatusInZone(long dcId, StoragePoolStatus status); + List listPoolsByCluster(long clusterId); - List findLocalStoragePoolsByTags(long dcId, long podId, - Long clusterId, String[] tags); + List findLocalStoragePoolsByTags(long dcId, long podId, Long clusterId, String[] tags); - List findZoneWideStoragePoolsByTags(long dcId, String[] tags); + List findZoneWideStoragePoolsByTags(long dcId, String[] tags); } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index 7e7e6fd4002..5d6e2cf9b72 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -48,141 +48,136 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @Component -@Local(value={PrimaryDataStoreDao.class}) @DB(txn=false) -public class PrimaryDataStoreDaoImpl extends GenericDaoBase implements PrimaryDataStoreDao { +@Local(value = { PrimaryDataStoreDao.class }) +@DB(txn = false) +public class PrimaryDataStoreDaoImpl extends GenericDaoBase implements PrimaryDataStoreDao { protected final SearchBuilder AllFieldSearch; - protected final SearchBuilder DcPodSearch; + protected final SearchBuilder DcPodSearch; protected final SearchBuilder DcPodAnyClusterSearch; protected final SearchBuilder DeleteLvmSearch; protected final GenericSearchBuilder StatusCountSearch; - - @Inject protected StoragePoolDetailsDao _detailsDao; - + + @Inject + protected StoragePoolDetailsDao _detailsDao; + private final String DetailsSqlPrefix = "SELECT storage_pool.* from storage_pool LEFT JOIN storage_pool_details ON storage_pool.id = storage_pool_details.pool_id WHERE storage_pool.removed is null and storage_pool.status = 'Up' and storage_pool.data_center_id = ? and (storage_pool.pod_id = ? or storage_pool.pod_id is null) and storage_pool.scope = ? and ("; - private final String DetailsSqlSuffix = ") GROUP BY storage_pool_details.pool_id HAVING COUNT(storage_pool_details.name) >= ?"; - private final String ZoneWideDetailsSqlPrefix = "SELECT storage_pool.* from storage_pool LEFT JOIN storage_pool_details ON storage_pool.id = storage_pool_details.pool_id WHERE storage_pool.removed is null and storage_pool.status = 'Up' and storage_pool.data_center_id = ? and storage_pool.scope = ? and ("; - private final String ZoneWideDetailsSqlSuffix = ") GROUP BY storage_pool_details.pool_id HAVING COUNT(storage_pool_details.name) >= ?"; - - private final String FindPoolTagDetails = "SELECT storage_pool_details.name FROM storage_pool_details WHERE pool_id = ? and value = ?"; - + private final String DetailsSqlSuffix = ") GROUP BY storage_pool_details.pool_id HAVING COUNT(storage_pool_details.name) >= ?"; + private final String ZoneWideDetailsSqlPrefix = "SELECT storage_pool.* from storage_pool LEFT JOIN storage_pool_details ON storage_pool.id = storage_pool_details.pool_id WHERE storage_pool.removed is null and storage_pool.status = 'Up' and storage_pool.data_center_id = ? and storage_pool.scope = ? and ("; + private final String ZoneWideDetailsSqlSuffix = ") GROUP BY storage_pool_details.pool_id HAVING COUNT(storage_pool_details.name) >= ?"; + + private final String FindPoolTagDetails = "SELECT storage_pool_details.name FROM storage_pool_details WHERE pool_id = ? and value = ?"; + public PrimaryDataStoreDaoImpl() { AllFieldSearch = createSearchBuilder(); AllFieldSearch.and("name", AllFieldSearch.entity().getName(), SearchCriteria.Op.EQ); AllFieldSearch.and("uuid", AllFieldSearch.entity().getUuid(), SearchCriteria.Op.EQ); AllFieldSearch.and("datacenterId", AllFieldSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); AllFieldSearch.and("hostAddress", AllFieldSearch.entity().getHostAddress(), SearchCriteria.Op.EQ); - AllFieldSearch.and("status",AllFieldSearch.entity().getStatus(),SearchCriteria.Op.EQ); + AllFieldSearch.and("status", AllFieldSearch.entity().getStatus(), SearchCriteria.Op.EQ); AllFieldSearch.and("path", AllFieldSearch.entity().getPath(), SearchCriteria.Op.EQ); AllFieldSearch.and("podId", AllFieldSearch.entity().getPodId(), Op.EQ); AllFieldSearch.and("clusterId", AllFieldSearch.entity().getClusterId(), Op.EQ); - AllFieldSearch.done(); - - DcPodSearch = createSearchBuilder(); - DcPodSearch.and("datacenterId", DcPodSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - DcPodSearch.and("status", DcPodSearch.entity().getStatus(), SearchCriteria.Op.EQ); - DcPodSearch.and("scope", DcPodSearch.entity().getScope(), SearchCriteria.Op.EQ); - DcPodSearch.and().op("nullpod", DcPodSearch.entity().getPodId(), SearchCriteria.Op.NULL); - DcPodSearch.or("podId", DcPodSearch.entity().getPodId(), SearchCriteria.Op.EQ); - DcPodSearch.cp(); - DcPodSearch.and().op("nullcluster", DcPodSearch.entity().getClusterId(), SearchCriteria.Op.NULL); - DcPodSearch.or("cluster", DcPodSearch.entity().getClusterId(), SearchCriteria.Op.EQ); - DcPodSearch.cp(); - DcPodSearch.done(); - - DcPodAnyClusterSearch = createSearchBuilder(); - DcPodAnyClusterSearch.and("datacenterId", DcPodAnyClusterSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + AllFieldSearch.done(); + + DcPodSearch = createSearchBuilder(); + DcPodSearch.and("datacenterId", DcPodSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + DcPodSearch.and("status", DcPodSearch.entity().getStatus(), SearchCriteria.Op.EQ); + DcPodSearch.and("scope", DcPodSearch.entity().getScope(), SearchCriteria.Op.EQ); + DcPodSearch.and().op("nullpod", DcPodSearch.entity().getPodId(), SearchCriteria.Op.NULL); + DcPodSearch.or("podId", DcPodSearch.entity().getPodId(), SearchCriteria.Op.EQ); + DcPodSearch.cp(); + DcPodSearch.and().op("nullcluster", DcPodSearch.entity().getClusterId(), SearchCriteria.Op.NULL); + DcPodSearch.or("cluster", DcPodSearch.entity().getClusterId(), SearchCriteria.Op.EQ); + DcPodSearch.cp(); + DcPodSearch.done(); + + DcPodAnyClusterSearch = createSearchBuilder(); + DcPodAnyClusterSearch.and("datacenterId", DcPodAnyClusterSearch.entity().getDataCenterId(), + SearchCriteria.Op.EQ); DcPodAnyClusterSearch.and("status", DcPodAnyClusterSearch.entity().getStatus(), SearchCriteria.Op.EQ); DcPodAnyClusterSearch.and("scope", DcPodAnyClusterSearch.entity().getScope(), SearchCriteria.Op.EQ); DcPodAnyClusterSearch.and().op("nullpod", DcPodAnyClusterSearch.entity().getPodId(), SearchCriteria.Op.NULL); DcPodAnyClusterSearch.or("podId", DcPodAnyClusterSearch.entity().getPodId(), SearchCriteria.Op.EQ); DcPodAnyClusterSearch.cp(); DcPodAnyClusterSearch.done(); - + DeleteLvmSearch = createSearchBuilder(); DeleteLvmSearch.and("ids", DeleteLvmSearch.entity().getId(), SearchCriteria.Op.IN); DeleteLvmSearch.and().op("LVM", DeleteLvmSearch.entity().getPoolType(), SearchCriteria.Op.EQ); DeleteLvmSearch.or("Filesystem", DeleteLvmSearch.entity().getPoolType(), SearchCriteria.Op.EQ); DeleteLvmSearch.cp(); - DeleteLvmSearch.done(); + DeleteLvmSearch.done(); - - StatusCountSearch = createSearchBuilder(Long.class); StatusCountSearch.and("status", StatusCountSearch.entity().getStatus(), SearchCriteria.Op.IN); StatusCountSearch.select(null, Func.COUNT, null); StatusCountSearch.done(); } - - @Override - public List findPoolByName(String name) { - SearchCriteria sc = AllFieldSearch.create(); + + @Override + public List findPoolByName(String name) { + SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("name", name); return listIncludingRemovedBy(sc); - } + } - - @Override - public StoragePoolVO findPoolByUUID(String uuid) { - SearchCriteria sc = AllFieldSearch.create(); + @Override + public StoragePoolVO findPoolByUUID(String uuid) { + SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("uuid", uuid); return findOneIncludingRemovedBy(sc); - } - - + } - @Override - public List findIfDuplicatePoolsExistByUUID(String uuid) { - SearchCriteria sc = AllFieldSearch.create(); + @Override + public List findIfDuplicatePoolsExistByUUID(String uuid) { + SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("uuid", uuid); return listBy(sc); - } + } - - @Override - public List listByDataCenterId(long datacenterId) { - SearchCriteria sc = AllFieldSearch.create(); + @Override + public List listByDataCenterId(long datacenterId) { + SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("datacenterId", datacenterId); return listBy(sc); - } + } + @Override + public void updateAvailable(long id, long available) { + StoragePoolVO pool = createForUpdate(id); + pool.setAvailableBytes(available); + update(id, pool); + } - @Override - public void updateAvailable(long id, long available) { - StoragePoolVO pool = createForUpdate(id); - pool.setAvailableBytes(available); - update(id, pool); - } + @Override + public void updateCapacity(long id, long capacity) { + StoragePoolVO pool = createForUpdate(id); + pool.setCapacityBytes(capacity); + update(id, pool); + } - @Override - public void updateCapacity(long id, long capacity) { - StoragePoolVO pool = createForUpdate(id); - pool.setCapacityBytes(capacity); - update(id, pool); - - } - @Override public List listByStorageHost(String hostFqdnOrIp) { SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("hostAddress", hostFqdnOrIp); return listIncludingRemovedBy(sc); } - + @Override - public List listByStatus(StoragePoolStatus status){ + public List listByStatus(StoragePoolStatus status) { SearchCriteria sc = AllFieldSearch.create(); - sc.setParameters("status", status); - return listBy(sc); + sc.setParameters("status", status); + return listBy(sc); } - + @Override - public List listByStatusInZone(long dcId, StoragePoolStatus status){ + public List listByStatusInZone(long dcId, StoragePoolStatus status) { SearchCriteria sc = AllFieldSearch.create(); - sc.setParameters("status", status); - sc.setParameters("datacenterId", dcId); - return listBy(sc); + sc.setParameters("status", status); + sc.setParameters("datacenterId", dcId); + return listBy(sc); } @Override @@ -193,238 +188,239 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase sc.setParameters("datacenterId", datacenterId); sc.setParameters("podId", podId); sc.setParameters("uuid", uuid); - + return findOneBy(sc); } - @Override - public List listBy(long datacenterId, long podId, Long clusterId, ScopeType scope) { - if (clusterId != null) { - SearchCriteria sc = DcPodSearch.create(); + @Override + public List listBy(long datacenterId, long podId, Long clusterId, ScopeType scope) { + if (clusterId != null) { + SearchCriteria sc = DcPodSearch.create(); sc.setParameters("datacenterId", datacenterId); sc.setParameters("podId", podId); sc.setParameters("status", Status.Up); sc.setParameters("scope", scope); - + sc.setParameters("cluster", clusterId); return listBy(sc); - } else { - SearchCriteria sc = DcPodAnyClusterSearch.create(); - sc.setParameters("datacenterId", datacenterId); - sc.setParameters("podId", podId); - sc.setParameters("status", Status.Up); - sc.setParameters("scope", scope); - return listBy(sc); - } - } + } else { + SearchCriteria sc = DcPodAnyClusterSearch.create(); + sc.setParameters("datacenterId", datacenterId); + sc.setParameters("podId", podId); + sc.setParameters("status", Status.Up); + sc.setParameters("scope", scope); + return listBy(sc); + } + } - @Override - public List listPoolByHostPath(String host, String path) { + @Override + public List listPoolByHostPath(String host, String path) { SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("hostAddress", host); sc.setParameters("path", path); - + return listBy(sc); - } - - public StoragePoolVO listById(Integer id) - { + } + + public StoragePoolVO listById(Integer id) { SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("id", id); - + return findOneIncludingRemovedBy(sc); - } - - @Override @DB - public StoragePoolVO persist(StoragePoolVO pool, Map details) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - pool = super.persist(pool); - if (details != null) { - for (Map.Entry detail : details.entrySet()) { - StoragePoolDetailVO vo = new StoragePoolDetailVO(pool.getId(), detail.getKey(), detail.getValue()); - _detailsDao.persist(vo); - } - } - txn.commit(); - return pool; - } - - @DB - @Override - public List findPoolsByDetails(long dcId, long podId, Long clusterId, Map details, ScopeType scope) { - StringBuilder sql = new StringBuilder(DetailsSqlPrefix); - if (clusterId != null) { - sql.append("storage_pool.cluster_id = ? OR storage_pool.cluster_id IS NULL) AND ("); - } - - for (Map.Entry detail : details.entrySet()) { - sql.append("((storage_pool_details.name='").append(detail.getKey()).append("') AND (storage_pool_details.value='").append(detail.getValue()).append("')) OR "); - } - sql.delete(sql.length() - 4, sql.length()); - sql.append(DetailsSqlSuffix); - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql.toString()); - int i = 1; - pstmt.setLong(i++, dcId); - pstmt.setLong(i++, podId); - pstmt.setString(i++, scope.toString()); - if (clusterId != null) { - pstmt.setLong(i++, clusterId); - } - pstmt.setInt(i++, details.size()); - ResultSet rs = pstmt.executeQuery(); - List pools = new ArrayList(); - while (rs.next()) { - pools.add(toEntityBean(rs, false)); - } - return pools; - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to execute " + pstmt, e); - } - } - - protected Map tagsToDetails(String[] tags) { - Map details = new HashMap(tags.length); - for (String tag: tags) { - details.put(tag, "true"); - } - return details; - } - - @Override - public List findPoolsByTags(long dcId, long podId, Long clusterId, String[] tags) { - List storagePools = null; - if (tags == null || tags.length == 0) { - storagePools = listBy(dcId, podId, clusterId, ScopeType.CLUSTER); - } else { - Map details = tagsToDetails(tags); - storagePools = findPoolsByDetails(dcId, podId, clusterId, details, ScopeType.CLUSTER); - } - - return storagePools; - } - - @Override - public List findLocalStoragePoolsByTags(long dcId, long podId, Long clusterId, String[] tags) { - List storagePools = null; - if (tags == null || tags.length == 0) { - storagePools = listBy(dcId, podId, clusterId, ScopeType.HOST); - } else { - Map details = tagsToDetails(tags); - storagePools = findPoolsByDetails(dcId, podId, clusterId, details, ScopeType.HOST); - } - - return storagePools; - } - - @Override - public List findZoneWideStoragePoolsByTags(long dcId, String[] tags) { - List storagePools = null; - if (tags == null || tags.length == 0) { - SearchCriteriaService sc = SearchCriteria2.create(StoragePoolVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); - return sc.list(); - } else { - Map details = tagsToDetails(tags); - - StringBuilder sql = new StringBuilder(ZoneWideDetailsSqlPrefix); - - for (Map.Entry detail : details.entrySet()) { - sql.append("((storage_pool_details.name='").append(detail.getKey()).append("') AND (storage_pool_details.value='").append(detail.getValue()).append("')) OR "); - } - sql.delete(sql.length() - 4, sql.length()); - sql.append(ZoneWideDetailsSqlSuffix); - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql.toString()); - int i = 1; - pstmt.setLong(i++, dcId); - pstmt.setString(i++, ScopeType.ZONE.toString()); - pstmt.setInt(i++, details.size()); - ResultSet rs = pstmt.executeQuery(); - List pools = new ArrayList(); - while (rs.next()) { - pools.add(toEntityBean(rs, false)); - } - return pools; - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to execute " + pstmt, e); - } - } - } - - @Override - @DB - public List searchForStoragePoolDetails(long poolId, String value){ - - StringBuilder sql = new StringBuilder(FindPoolTagDetails); - - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql.toString()); - pstmt.setLong(1, poolId); - pstmt.setString(2, value); - - ResultSet rs = pstmt.executeQuery(); - List tags = new ArrayList(); - - while (rs.next()) { - tags.add(rs.getString("name")); - } - return tags; - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to execute " + pstmt.toString(), e); - } - - } - - @Override - public void updateDetails(long poolId, Map details) { - if (details != null) { - _detailsDao.update(poolId, details); - } } - - @Override - public Map getDetails(long poolId) { - return _detailsDao.getDetails(poolId); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _detailsDao.configure("DetailsDao", params); - return true; - } - - - + @Override - public long countPoolsByStatus( StoragePoolStatus... statuses) { + @DB + public StoragePoolVO persist(StoragePoolVO pool, Map details) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + pool = super.persist(pool); + if (details != null) { + for (Map.Entry detail : details.entrySet()) { + StoragePoolDetailVO vo = new StoragePoolDetailVO(pool.getId(), detail.getKey(), detail.getValue()); + _detailsDao.persist(vo); + } + } + txn.commit(); + return pool; + } + + @DB + @Override + public List findPoolsByDetails(long dcId, long podId, Long clusterId, Map details, + ScopeType scope) { + StringBuilder sql = new StringBuilder(DetailsSqlPrefix); + if (clusterId != null) { + sql.append("storage_pool.cluster_id = ? OR storage_pool.cluster_id IS NULL) AND ("); + } + + for (Map.Entry detail : details.entrySet()) { + sql.append("((storage_pool_details.name='").append(detail.getKey()) + .append("') AND (storage_pool_details.value='").append(detail.getValue()).append("')) OR "); + } + sql.delete(sql.length() - 4, sql.length()); + sql.append(DetailsSqlSuffix); + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql.toString()); + int i = 1; + pstmt.setLong(i++, dcId); + pstmt.setLong(i++, podId); + pstmt.setString(i++, scope.toString()); + if (clusterId != null) { + pstmt.setLong(i++, clusterId); + } + pstmt.setInt(i++, details.size()); + ResultSet rs = pstmt.executeQuery(); + List pools = new ArrayList(); + while (rs.next()) { + pools.add(toEntityBean(rs, false)); + } + return pools; + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to execute " + pstmt, e); + } + } + + protected Map tagsToDetails(String[] tags) { + Map details = new HashMap(tags.length); + for (String tag : tags) { + details.put(tag, "true"); + } + return details; + } + + @Override + public List findPoolsByTags(long dcId, long podId, Long clusterId, String[] tags) { + List storagePools = null; + if (tags == null || tags.length == 0) { + storagePools = listBy(dcId, podId, clusterId, ScopeType.CLUSTER); + } else { + Map details = tagsToDetails(tags); + storagePools = findPoolsByDetails(dcId, podId, clusterId, details, ScopeType.CLUSTER); + } + + return storagePools; + } + + @Override + public List findLocalStoragePoolsByTags(long dcId, long podId, Long clusterId, String[] tags) { + List storagePools = null; + if (tags == null || tags.length == 0) { + storagePools = listBy(dcId, podId, clusterId, ScopeType.HOST); + } else { + Map details = tagsToDetails(tags); + storagePools = findPoolsByDetails(dcId, podId, clusterId, details, ScopeType.HOST); + } + + return storagePools; + } + + @Override + public List findZoneWideStoragePoolsByTags(long dcId, String[] tags) { + List storagePools = null; + if (tags == null || tags.length == 0) { + SearchCriteriaService sc = SearchCriteria2.create(StoragePoolVO.class); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); + sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); + return sc.list(); + } else { + Map details = tagsToDetails(tags); + + StringBuilder sql = new StringBuilder(ZoneWideDetailsSqlPrefix); + + for (Map.Entry detail : details.entrySet()) { + sql.append("((storage_pool_details.name='").append(detail.getKey()) + .append("') AND (storage_pool_details.value='").append(detail.getValue()).append("')) OR "); + } + sql.delete(sql.length() - 4, sql.length()); + sql.append(ZoneWideDetailsSqlSuffix); + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql.toString()); + int i = 1; + pstmt.setLong(i++, dcId); + pstmt.setString(i++, ScopeType.ZONE.toString()); + pstmt.setInt(i++, details.size()); + ResultSet rs = pstmt.executeQuery(); + List pools = new ArrayList(); + while (rs.next()) { + pools.add(toEntityBean(rs, false)); + } + return pools; + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to execute " + pstmt, e); + } + } + } + + @Override + @DB + public List searchForStoragePoolDetails(long poolId, String value) { + + StringBuilder sql = new StringBuilder(FindPoolTagDetails); + + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement(sql.toString()); + pstmt.setLong(1, poolId); + pstmt.setString(2, value); + + ResultSet rs = pstmt.executeQuery(); + List tags = new ArrayList(); + + while (rs.next()) { + tags.add(rs.getString("name")); + } + return tags; + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to execute " + pstmt.toString(), e); + } + + } + + @Override + public void updateDetails(long poolId, Map details) { + if (details != null) { + _detailsDao.update(poolId, details); + } + } + + @Override + public Map getDetails(long poolId) { + return _detailsDao.getDetails(poolId); + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + _detailsDao.configure("DetailsDao", params); + return true; + } + + @Override + public long countPoolsByStatus(StoragePoolStatus... statuses) { SearchCriteria sc = StatusCountSearch.create(); - - sc.setParameters("status", (Object[])statuses); - + + sc.setParameters("status", (Object[]) statuses); + List rs = customSearchIncludingRemoved(sc, null); if (rs.size() == 0) { return 0; } - + return rs.get(0); } - + @Override public List listPoolsByCluster(long clusterId) { SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("clusterId", clusterId); - + return listBy(sc); } } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java index d1f802de949..0d9af4b5fb3 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java @@ -24,28 +24,28 @@ import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(name="storage_pool_details") +@Table(name = "storage_pool_details") public class PrimaryDataStoreDetailVO { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") long id; - - @Column(name="pool_id") + + @Column(name = "pool_id") long poolId; - - @Column(name="name") + + @Column(name = "name") String name; - - @Column(name="value") + + @Column(name = "value") String value; - + public PrimaryDataStoreDetailVO(long poolId, String name, String value) { this.poolId = poolId; this.name = name; this.value = value; } - + public long getId() { return id; } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java index c2b109a959e..18e2f1c7018 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java @@ -21,7 +21,8 @@ import java.util.Map; import com.cloud.utils.db.GenericDao; public interface PrimaryDataStoreDetailsDao extends GenericDao { - + void update(long poolId, Map details); + Map getDetails(long poolId); } \ No newline at end of file diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java index f5b46aaa85a..48d0db28127 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java @@ -16,18 +16,17 @@ // under the License. package org.apache.cloudstack.storage.datastore.db; - import java.util.List; import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; - import com.cloud.storage.DataStoreRole; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface SnapshotDataStoreDao extends GenericDao, StateDao { +public interface SnapshotDataStoreDao extends GenericDao, + StateDao { public List listByStoreId(long id, DataStoreRole role); diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java index edb23d034f9..6ceb0d0fcba 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java @@ -40,49 +40,48 @@ import com.cloud.utils.fsm.StateObject; /** * Join table for image_data_store and snapshots - * + * */ @Entity -@Table(name="snapshot_store_ref") +@Table(name = "snapshot_store_ref") public class SnapshotDataStoreVO implements StateObject, DataObjectInStore { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Long id; - @Column(name="store_id") - private long dataStoreId; + @Column(name = "store_id") + private long dataStoreId; - @Column(name="store_role") - @Enumerated(EnumType.STRING) - private DataStoreRole role; + @Column(name = "store_role") + @Enumerated(EnumType.STRING) + private DataStoreRole role; - @Column(name="snapshot_id") - private long snapshotId; + @Column(name = "snapshot_id") + private long snapshotId; - @Column(name=GenericDaoBase.CREATED_COLUMN) - private Date created = null; + @Column(name = GenericDaoBase.CREATED_COLUMN) + private Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastUpdated = null; - @Column (name="size") - private long size; + @Column(name = "size") + private long size; - @Column (name="physical_size") - private long physicalSize; + @Column(name = "physical_size") + private long physicalSize; - @Column(name="parent_snapshot_id") - private long parentSnapshotId; + @Column(name = "parent_snapshot_id") + private long parentSnapshotId; - @Column (name="job_id") - private String jobId; + @Column(name = "job_id") + private String jobId; - @Column (name="install_path") + @Column(name = "install_path") private String installPath; - - @Column(name="update_count", updatable = true, nullable=false) + @Column(name = "update_count", updatable = true, nullable = false) protected long updatedCount; @Column(name = "updated") @@ -94,97 +93,78 @@ public class SnapshotDataStoreVO implements StateObject { - + void update(long poolId, Map details); + Map getDetails(long poolId); + StoragePoolDetailVO findDetail(long poolId, String name); } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/StoragePoolVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/StoragePoolVO.java index 6a7c8544c53..78a5779f167 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/StoragePoolVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/StoragePoolVO.java @@ -29,7 +29,6 @@ import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; - import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.ScopeType; import com.cloud.storage.StoragePool; @@ -37,10 +36,11 @@ import com.cloud.storage.StoragePoolStatus; import com.cloud.utils.db.GenericDao; @Entity -@Table(name="storage_pool") -public class StoragePoolVO implements StoragePool{ +@Table(name = "storage_pool") +public class StoragePoolVO implements StoragePool { @Id - @TableGenerator(name = "storage_pool_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "storage_pool_seq", allocationSize = 1) + @TableGenerator(name = "storage_pool_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", + pkColumnValue = "storage_pool_seq", allocationSize = 1) @Column(name = "id", updatable = false, nullable = false) private long id; @@ -113,10 +113,10 @@ public class StoragePoolVO implements StoragePool{ public StoragePoolVO() { this.status = StoragePoolStatus.Initial; } - - public StoragePoolVO(long poolId, String name, String uuid, StoragePoolType type, - long dataCenterId, Long podId, long availableBytes, long capacityBytes, String hostAddress, int port, String hostPath) { - this.name = name; + + public StoragePoolVO(long poolId, String name, String uuid, StoragePoolType type, long dataCenterId, Long podId, + long availableBytes, long capacityBytes, String hostAddress, int port, String hostPath) { + this.name = name; this.id = poolId; this.uuid = uuid; this.poolType = type; @@ -131,7 +131,8 @@ public class StoragePoolVO implements StoragePool{ } public StoragePoolVO(StoragePoolVO that) { - this(that.id, that.name, that.uuid, that.poolType, that.dataCenterId, that.podId, that.availableBytes, that.capacityBytes, that.hostAddress, that.port, that.path); + this(that.id, that.name, that.uuid, that.poolType, that.dataCenterId, that.podId, that.availableBytes, + that.capacityBytes, that.hostAddress, that.port, that.path); } public StoragePoolVO(StoragePoolType type, String hostAddress, int port, String path) { @@ -143,7 +144,6 @@ public class StoragePoolVO implements StoragePool{ this.uuid = UUID.randomUUID().toString(); } - public String getName() { return name; } @@ -294,11 +294,11 @@ public class StoragePoolVO implements StoragePool{ public String toString() { return new StringBuilder("Pool[").append(id).append("|").append(poolType).append("]").toString(); } - + public boolean isShared() { return this.scope == ScopeType.HOST ? false : true; } - + public boolean isLocal() { return !isShared(); } diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java index b83c590266f..79acd319ab5 100644 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java @@ -22,14 +22,13 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreState import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; - import com.cloud.storage.DataStoreRole; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface TemplateDataStoreDao extends GenericDao, StateDao { - +public interface TemplateDataStoreDao extends GenericDao, + StateDao { public List listByStoreId(long id); @@ -43,11 +42,14 @@ public interface TemplateDataStoreDao extends GenericDao listByTemplateStoreStatus(long templateId, long storeId, State... states); - List listByTemplateStoreDownloadStatus(long templateId, long storeId, VMTemplateStorageResourceAssoc.Status... status); + List listByTemplateStoreDownloadStatus(long templateId, long storeId, + VMTemplateStorageResourceAssoc.Status... status); - List listByTemplateZoneDownloadStatus(long templateId, Long zoneId, VMTemplateStorageResourceAssoc.Status... status); + List listByTemplateZoneDownloadStatus(long templateId, Long zoneId, + VMTemplateStorageResourceAssoc.Status... status); - TemplateDataStoreVO findByTemplateZoneDownloadStatus(long templateId, Long zoneId, VMTemplateStorageResourceAssoc.Status... status); + TemplateDataStoreVO findByTemplateZoneDownloadStatus(long templateId, Long zoneId, + VMTemplateStorageResourceAssoc.Status... status); TemplateDataStoreVO findByStoreTemplate(long storeId, long templateId); diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java index 44bda70a00b..2cee4d13e8e 100755 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java @@ -41,67 +41,67 @@ import com.cloud.utils.fsm.StateObject; /** * Join table for image_data_store and templates - * + * */ @Entity -@Table(name="template_store_ref") +@Table(name = "template_store_ref") public class TemplateDataStoreVO implements StateObject, DataObjectInStore { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Long id; - @Column(name="store_id") - private Long dataStoreId; // this can be null for baremetal templates + @Column(name = "store_id") + private Long dataStoreId; // this can be null for baremetal templates - @Column(name="template_id") - private long templateId; + @Column(name = "template_id") + private long templateId; - @Column(name="store_role") + @Column(name = "store_role") @Enumerated(EnumType.STRING) private DataStoreRole dataStoreRole; - @Column(name=GenericDaoBase.CREATED_COLUMN) - private Date created = null; + @Column(name = GenericDaoBase.CREATED_COLUMN) + private Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastUpdated = null; - @Column (name="download_pct") - private int downloadPercent; + @Column(name = "download_pct") + private int downloadPercent; - @Column (name="size") - private long size; + @Column(name = "size") + private long size; - @Column (name="physical_size") - private long physicalSize; + @Column(name = "physical_size") + private long physicalSize; - @Column (name="download_state") - @Enumerated(EnumType.STRING) - private Status downloadState; + @Column(name = "download_state") + @Enumerated(EnumType.STRING) + private Status downloadState; - @Column (name="local_path") - private String localDownloadPath; + @Column(name = "local_path") + private String localDownloadPath; - @Column (name="error_str") - private String errorString; + @Column(name = "error_str") + private String errorString; - @Column (name="job_id") - private String jobId; + @Column(name = "job_id") + private String jobId; - @Column (name="install_path") + @Column(name = "install_path") private String installPath; - @Column (name="url") - private String downloadUrl; + @Column(name = "url") + private String downloadUrl; - @Column(name="is_copy") - private boolean isCopy = false; + @Column(name = "is_copy") + private boolean isCopy = false; - @Column(name="destroyed") + @Column(name = "destroyed") boolean destroyed = false; - @Column(name="update_count", updatable = true, nullable=false) + @Column(name = "update_count", updatable = true, nullable = false) protected long updatedCount; @Column(name = "updated") @@ -112,31 +112,27 @@ public class TemplateDataStoreVO implements StateObject, StateDao { +public interface VolumeDataStoreDao extends GenericDao, + StateDao { public List listByStoreId(long id); diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java index 7e89de44e9e..d2e5c2585e1 100755 --- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java +++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java @@ -41,66 +41,66 @@ import com.cloud.utils.fsm.StateObject; /** * Join table for image_data_store and volumes - * + * */ @Entity -@Table(name="volume_store_ref") +@Table(name = "volume_store_ref") public class VolumeDataStoreVO implements StateObject, DataObjectInStore { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Long id; - @Column(name="store_id") - private long dataStoreId; + @Column(name = "store_id") + private long dataStoreId; - @Column(name="volume_id") - private long volumeId; + @Column(name = "volume_id") + private long volumeId; - @Column(name="zone_id") - private long zoneId; + @Column(name = "zone_id") + private long zoneId; - @Column(name=GenericDaoBase.CREATED_COLUMN) - private Date created = null; + @Column(name = GenericDaoBase.CREATED_COLUMN) + private Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastUpdated = null; - @Column (name="download_pct") - private int downloadPercent; + @Column(name = "download_pct") + private int downloadPercent; - @Column (name="size") - private long size; + @Column(name = "size") + private long size; - @Column (name="physical_size") - private long physicalSize; + @Column(name = "physical_size") + private long physicalSize; - @Column (name="download_state") - @Enumerated(EnumType.STRING) - private Status downloadState; + @Column(name = "download_state") + @Enumerated(EnumType.STRING) + private Status downloadState; - @Column(name="checksum") + @Column(name = "checksum") private String checksum; - @Column (name="local_path") - private String localDownloadPath; + @Column(name = "local_path") + private String localDownloadPath; - @Column (name="error_str") - private String errorString; + @Column(name = "error_str") + private String errorString; - @Column (name="job_id") - private String jobId; + @Column(name = "job_id") + private String jobId; - @Column (name="install_path") + @Column(name = "install_path") private String installPath; - @Column (name="url") - private String downloadUrl; + @Column(name = "url") + private String downloadUrl; - @Column(name="destroyed") + @Column(name = "destroyed") boolean destroyed = false; - @Column(name="update_count", updatable = true, nullable=false) + @Column(name = "update_count", updatable = true, nullable = false) protected long updatedCount; @Column(name = "updated") @@ -112,164 +112,144 @@ public class VolumeDataStoreVO implements StateObject listTemplates(); + String getMountPoint(); // get the mount point on ssvm. } diff --git a/engine/api/src/org/apache/cloudstack/storage/image/datastore/ImageStoreInfo.java b/engine/api/src/org/apache/cloudstack/storage/image/datastore/ImageStoreInfo.java index c5f7ca98c1d..d51780da566 100644 --- a/engine/api/src/org/apache/cloudstack/storage/image/datastore/ImageStoreInfo.java +++ b/engine/api/src/org/apache/cloudstack/storage/image/datastore/ImageStoreInfo.java @@ -22,5 +22,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; public interface ImageStoreInfo extends DataStore { public long getImageStoreId(); + public String getType(); } diff --git a/engine/api/src/org/apache/cloudstack/storage/to/ImageStoreTO.java b/engine/api/src/org/apache/cloudstack/storage/to/ImageStoreTO.java index 96e94794c57..45d0e98aa8f 100644 --- a/engine/api/src/org/apache/cloudstack/storage/to/ImageStoreTO.java +++ b/engine/api/src/org/apache/cloudstack/storage/to/ImageStoreTO.java @@ -27,7 +27,7 @@ public class ImageStoreTO implements DataStoreTO { private String providerName; private DataStoreRole role; - public ImageStoreTO(){ + public ImageStoreTO() { } @@ -53,7 +53,6 @@ public class ImageStoreTO implements DataStoreTO { return providerName; } - public void setType(String type) { this.type = type; } diff --git a/engine/api/src/org/apache/cloudstack/storage/to/NfsPrimaryDataStoreTO.java b/engine/api/src/org/apache/cloudstack/storage/to/NfsPrimaryDataStoreTO.java deleted file mode 100644 index 96fb6bb2401..00000000000 --- a/engine/api/src/org/apache/cloudstack/storage/to/NfsPrimaryDataStoreTO.java +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package org.apache.cloudstack.storage.to; - -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; - -public class NfsPrimaryDataStoreTO extends PrimaryDataStoreTO { - private String server; - private String path; - - public NfsPrimaryDataStoreTO(PrimaryDataStoreInfo dataStore) { - super(dataStore); - } - - public void setServer(String server) { - this.server = server; - } - - public String getServer() { - return this.server; - } - - public void setPath(String path) { - this.path = path; - } - - public String getPath() { - return this.path; - } -} diff --git a/engine/api/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java b/engine/api/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java index c3ce0e086d4..1b4c08ffeb8 100644 --- a/engine/api/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java +++ b/engine/api/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java @@ -25,35 +25,35 @@ import com.cloud.storage.Storage.StoragePoolType; public class PrimaryDataStoreTO implements DataStoreTO { private final String uuid; private final String name; - private String type; + private String type; private final long id; private StoragePoolType poolType; private String host; private String path; private int port; + public PrimaryDataStoreTO(PrimaryDataStoreInfo dataStore) { this.uuid = dataStore.getUuid(); this.name = dataStore.getName(); - // this.type = dataStore.getType(); this.id = dataStore.getId(); this.setPoolType(dataStore.getPoolType()); this.setHost(dataStore.getHostAddress()); this.setPath(dataStore.getPath()); this.setPort(dataStore.getPort()); } - + public long getId() { return this.id; } - + public String getUuid() { return this.uuid; } - + public String getName() { return this.name; } - + public String getType() { return this.type; } diff --git a/engine/api/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java b/engine/api/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java index 492bd06d67f..f8f622c9307 100644 --- a/engine/api/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java +++ b/engine/api/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java @@ -24,50 +24,50 @@ import com.cloud.agent.api.to.DataTO; import com.cloud.hypervisor.Hypervisor.HypervisorType; public class SnapshotObjectTO implements DataTO { - private String path; - private VolumeObjectTO volume; - private String parentSnapshotPath; - private DataStoreTO dataStore; - private String vmName; - private String name; - private HypervisorType hypervisorType; - private long id; - - public SnapshotObjectTO() { - - } - - public SnapshotObjectTO(SnapshotInfo snapshot) { - this.path = snapshot.getPath(); - this.setId(snapshot.getId()); - this.volume = (VolumeObjectTO)snapshot.getBaseVolume().getTO(); - this.setVmName(snapshot.getBaseVolume().getAttachedVmName()); - if (snapshot.getParent() != null) { - this.parentSnapshotPath = snapshot.getParent().getPath(); - } - this.dataStore = snapshot.getDataStore().getTO(); - this.setName(snapshot.getName()); - this.hypervisorType = snapshot.getHypervisorType(); - } - - @Override - public DataObjectType getObjectType() { - return DataObjectType.SNAPSHOT; - } + private String path; + private VolumeObjectTO volume; + private String parentSnapshotPath; + private DataStoreTO dataStore; + private String vmName; + private String name; + private HypervisorType hypervisorType; + private long id; - @Override - public DataStoreTO getDataStore() { - return this.dataStore; - } + public SnapshotObjectTO() { - @Override - public String getPath() { - return this.path; - } - - public void setPath(String path) { - this.path = path; - } + } + + public SnapshotObjectTO(SnapshotInfo snapshot) { + this.path = snapshot.getPath(); + this.setId(snapshot.getId()); + this.volume = (VolumeObjectTO) snapshot.getBaseVolume().getTO(); + this.setVmName(snapshot.getBaseVolume().getAttachedVmName()); + if (snapshot.getParent() != null) { + this.parentSnapshotPath = snapshot.getParent().getPath(); + } + this.dataStore = snapshot.getDataStore().getTO(); + this.setName(snapshot.getName()); + this.hypervisorType = snapshot.getHypervisorType(); + } + + @Override + public DataObjectType getObjectType() { + return DataObjectType.SNAPSHOT; + } + + @Override + public DataStoreTO getDataStore() { + return this.dataStore; + } + + @Override + public String getPath() { + return this.path; + } + + public void setPath(String path) { + this.path = path; + } public VolumeObjectTO getVolume() { return volume; diff --git a/engine/api/src/org/apache/cloudstack/storage/to/TemplateObjectTO.java b/engine/api/src/org/apache/cloudstack/storage/to/TemplateObjectTO.java index 3d7a901e352..fefb0ad3ec4 100644 --- a/engine/api/src/org/apache/cloudstack/storage/to/TemplateObjectTO.java +++ b/engine/api/src/org/apache/cloudstack/storage/to/TemplateObjectTO.java @@ -17,8 +17,6 @@ package org.apache.cloudstack.storage.to; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.disktype.DiskFormat; -import org.apache.cloudstack.storage.image.datastore.ImageStoreInfo; import com.cloud.agent.api.to.DataObjectType; import com.cloud.agent.api.to.DataStoreTO; @@ -27,17 +25,17 @@ import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; public class TemplateObjectTO implements DataTO { - private String path; + private String path; private String origUrl; - private String uuid; + private String uuid; private long id; private ImageFormat format; private long accountId; private String checksum; private boolean hvm; private String displayText; - private DataStoreTO imageDataStore; - private String name; + private DataStoreTO imageDataStore; + private String name; private String guestOsType; private Long size; @@ -45,7 +43,7 @@ public class TemplateObjectTO implements DataTO { } - public TemplateObjectTO(VirtualMachineTemplate template){ + public TemplateObjectTO(VirtualMachineTemplate template) { this.uuid = template.getUuid(); this.id = template.getId(); this.origUrl = template.getUrl(); @@ -69,7 +67,7 @@ public class TemplateObjectTO implements DataTO { this.name = template.getUniqueName(); this.format = template.getFormat(); if (template.getDataStore() != null) { - this.imageDataStore = template.getDataStore().getTO(); + this.imageDataStore = template.getDataStore().getTO(); } } @@ -85,28 +83,35 @@ public class TemplateObjectTO implements DataTO { public long getId() { return id; } + public ImageFormat getFormat() { return format; } + public long getAccountId() { return accountId; } + public String getChecksum() { return checksum; } + public boolean isRequiresHvm() { return hvm; } - public void setRequiresHvm(boolean hvm){ + + public void setRequiresHvm(boolean hvm) { this.hvm = hvm; } + public String getDescription() { return displayText; } - public void setDescription(String desc){ + public void setDescription(String desc) { this.displayText = desc; } + public DataStoreTO getImageDataStore() { return this.imageDataStore; } @@ -118,7 +123,7 @@ public class TemplateObjectTO implements DataTO { @Override public DataStoreTO getDataStore() { - return (DataStoreTO)this.imageDataStore; + return (DataStoreTO) this.imageDataStore; } /** @@ -127,30 +132,39 @@ public class TemplateObjectTO implements DataTO { public String getName() { return name; } + public void setPath(String path) { this.path = path; } + public void setUuid(String uuid) { this.uuid = uuid; } + public void setName(String name) { this.name = name; } - public String getOrigUrl() { - return origUrl; - } - public void setOrigUrl(String origUrl) { - this.origUrl = origUrl; - } + + public String getOrigUrl() { + return origUrl; + } + + public void setOrigUrl(String origUrl) { + this.origUrl = origUrl; + } + public void setFormat(ImageFormat format) { this.format = format; } + public void setAccountId(long accountId) { this.accountId = accountId; } + public void setChecksum(String checksum) { this.checksum = checksum; } + public void setImageDataStore(DataStoreTO imageDataStore) { this.imageDataStore = imageDataStore; } @@ -163,11 +177,11 @@ public class TemplateObjectTO implements DataTO { this.guestOsType = guestOsType; } - public Long getSize() { - return size; - } + public Long getSize() { + return size; + } - public void setSize(Long size) { - this.size = size; - } + public void setSize(Long size) { + this.size = size; + } } diff --git a/engine/api/src/org/apache/cloudstack/storage/to/VolumeObjectTO.java b/engine/api/src/org/apache/cloudstack/storage/to/VolumeObjectTO.java index 96cfbc7bf2d..be268ffc677 100644 --- a/engine/api/src/org/apache/cloudstack/storage/to/VolumeObjectTO.java +++ b/engine/api/src/org/apache/cloudstack/storage/to/VolumeObjectTO.java @@ -72,7 +72,7 @@ public class VolumeObjectTO implements DataTO { public Volume.Type getVolumeType() { return this.volumeType; } - + public DataStoreTO getDataStore() { return this.dataStore; } @@ -133,29 +133,28 @@ public class VolumeObjectTO implements DataTO { this.vmName = vmName; } - public String getChainInfo() { - return chainInfo; - } + public String getChainInfo() { + return chainInfo; + } - public void setChainInfo(String chainInfo) { - this.chainInfo = chainInfo; - } + public void setChainInfo(String chainInfo) { + this.chainInfo = chainInfo; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public Storage.ImageFormat getFormat() { - return format; - } - - public void setFormat(Storage.ImageFormat format) { - this.format = format; - } + public Storage.ImageFormat getFormat() { + return format; + } + public void setFormat(Storage.ImageFormat format) { + this.format = format; + } } diff --git a/engine/schema/src/com/cloud/storage/DiskOfferingVO.java b/engine/schema/src/com/cloud/storage/DiskOfferingVO.java index 909d7fe6325..23b8d60e31c 100755 --- a/engine/schema/src/com/cloud/storage/DiskOfferingVO.java +++ b/engine/schema/src/com/cloud/storage/DiskOfferingVO.java @@ -34,80 +34,78 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import org.apache.cloudstack.api.Identity; import com.cloud.offering.DiskOffering; import com.cloud.utils.db.GenericDao; -import org.apache.cloudstack.api.InternalIdentity; @Entity -@Table(name="disk_offering") -@Inheritance(strategy=InheritanceType.JOINED) -@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) +@Table(name = "disk_offering") +@Inheritance(strategy = InheritanceType.JOINED) +@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, length = 32) public class DiskOfferingVO implements DiskOffering { public enum Type { - Disk, - Service + Disk, Service }; @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") long id; - @Column(name="domain_id") + @Column(name = "domain_id") Long domainId; - @Column(name="unique_name") + @Column(name = "unique_name") private String uniqueName; - @Column(name="name") + @Column(name = "name") private String name = null; - @Column(name="display_text", length=4096) + @Column(name = "display_text", length = 4096) private String displayText = null; - @Column(name="disk_size") + @Column(name = "disk_size") long diskSize; - @Column(name="tags", length=4096) + @Column(name = "tags", length = 4096) String tags; - @Column(name="type") + @Column(name = "type") Type type; - @Column(name=GenericDao.REMOVED) + @Column(name = GenericDao.REMOVED) @Temporal(TemporalType.TIMESTAMP) private Date removed; - @Column(name=GenericDao.CREATED_COLUMN) + @Column(name = GenericDao.CREATED_COLUMN) private Date created; - @Column(name="recreatable") + @Column(name = "recreatable") private boolean recreatable; - @Column(name="use_local_storage") + @Column(name = "use_local_storage") private boolean useLocalStorage; - @Column(name="system_use") + @Column(name = "system_use") private boolean systemUse; - @Column(name="customized") + @Column(name = "customized") private boolean customized; - @Column(name="uuid") + @Column(name = "uuid") private String uuid; - @Column(name="sort_key") + @Column(name = "sort_key") int sortKey; - @Column(name="display_offering") + @Column(name = "display_offering") boolean displayOffering; public DiskOfferingVO() { - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } - public DiskOfferingVO(Long domainId, String name, String displayText, long diskSize, String tags, boolean isCustomized) { + public DiskOfferingVO(Long domainId, String name, String displayText, long diskSize, String tags, + boolean isCustomized) { this.domainId = domainId; this.name = name; this.displayText = displayText; @@ -117,10 +115,11 @@ public class DiskOfferingVO implements DiskOffering { this.type = Type.Disk; this.useLocalStorage = false; this.customized = isCustomized; - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } - public DiskOfferingVO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, boolean useLocalStorage, boolean systemUse, boolean customized) { + public DiskOfferingVO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, + boolean useLocalStorage, boolean systemUse, boolean customized) { this.domainId = null; this.type = Type.Service; this.name = name; @@ -130,11 +129,13 @@ public class DiskOfferingVO implements DiskOffering { this.useLocalStorage = useLocalStorage; this.systemUse = systemUse; this.customized = customized; - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } - //domain specific offerings constructor (null domainId implies public offering) - public DiskOfferingVO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, boolean useLocalStorage, boolean systemUse, boolean customized, Long domainId) { + // domain specific offerings constructor (null domainId implies public + // offering) + public DiskOfferingVO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, + boolean useLocalStorage, boolean systemUse, boolean customized, Long domainId) { this.type = Type.Service; this.name = name; this.displayText = displayText; @@ -144,7 +145,7 @@ public class DiskOfferingVO implements DiskOffering { this.systemUse = systemUse; this.customized = customized; this.domainId = domainId; - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } @Override @@ -154,14 +155,14 @@ public class DiskOfferingVO implements DiskOffering { @Override public boolean isCustomized() { - return customized; - } + return customized; + } - public void setCustomized(boolean customized) { - this.customized = customized; - } + public void setCustomized(boolean customized) { + this.customized = customized; + } - @Override + @Override public String getUniqueName() { return uniqueName; } @@ -197,7 +198,6 @@ public class DiskOfferingVO implements DiskOffering { this.name = name; } - @Override public boolean getSystemUse() { return systemUse; @@ -211,13 +211,14 @@ public class DiskOfferingVO implements DiskOffering { public String getDisplayText() { return displayText; } + public void setDisplayText(String displayText) { this.displayText = displayText; } @Override - public long getDiskSize(){ - return diskSize; + public long getDiskSize() { + return diskSize; } @Override @@ -229,10 +230,10 @@ public class DiskOfferingVO implements DiskOffering { return removed; } - @Override + @Override public Date getCreated() { - return created; - } + return created; + } protected void setTags(String tags) { this.tags = tags; @@ -290,9 +291,9 @@ public class DiskOfferingVO implements DiskOffering { setTags(buf.toString()); } - public void setUseLocalStorage(boolean useLocalStorage) { - this.useLocalStorage = useLocalStorage; - } + public void setUseLocalStorage(boolean useLocalStorage) { + this.useLocalStorage = useLocalStorage; + } public void setRemoved(Date removed) { this.removed = removed; @@ -300,25 +301,24 @@ public class DiskOfferingVO implements DiskOffering { @Override public String getUuid() { - return this.uuid; + return this.uuid; } public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } public void setSortKey(int key) { - sortKey = key; + sortKey = key; } public int getSortKey() { - return sortKey; - } - - public void setRecreatable(boolean recreatable) { - this.recreatable = recreatable; + return sortKey; } + public void setRecreatable(boolean recreatable) { + this.recreatable = recreatable; + } public boolean getDisplayOffering() { return displayOffering; diff --git a/engine/schema/src/com/cloud/storage/GuestOSCategoryVO.java b/engine/schema/src/com/cloud/storage/GuestOSCategoryVO.java index 03a74793001..36773e351e3 100644 --- a/engine/schema/src/com/cloud/storage/GuestOSCategoryVO.java +++ b/engine/schema/src/com/cloud/storage/GuestOSCategoryVO.java @@ -25,44 +25,41 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - @Entity -@Table(name="guest_os_category") +@Table(name = "guest_os_category") public class GuestOSCategoryVO implements GuestOsCategory { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") long id; - @Column(name="name") + @Column(name = "name") String name; - @Column(name="uuid") + @Column(name = "uuid") String uuid = UUID.randomUUID().toString(); @Override public long getId() { - return id; + return id; } @Override public String getName() { - return name; + return name; } @Override public void setName(String name) { - this.name = name; + this.name = name; } @Override public String getUuid() { - return this.uuid; + return this.uuid; } public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } } diff --git a/engine/schema/src/com/cloud/storage/GuestOSVO.java b/engine/schema/src/com/cloud/storage/GuestOSVO.java index 49e136d03c1..f34d831d7a5 100644 --- a/engine/schema/src/com/cloud/storage/GuestOSVO.java +++ b/engine/schema/src/com/cloud/storage/GuestOSVO.java @@ -25,66 +25,63 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - @Entity -@Table(name="guest_os") +@Table(name = "guest_os") public class GuestOSVO implements GuestOS { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") long id; - @Column(name="category_id") + @Column(name = "category_id") private long categoryId; - @Column(name="name") + @Column(name = "name") String name; - @Column(name="display_name") + @Column(name = "display_name") String displayName; - @Column(name="uuid") + @Column(name = "uuid") String uuid = UUID.randomUUID().toString(); @Override public long getId() { - return id; + return id; } public long getCategoryId() { - return categoryId; + return categoryId; } public void setCategoryId(long categoryId) { - this.categoryId = categoryId; + this.categoryId = categoryId; } @Override public String getName() { - return name; + return name; } public void setName(String name) { - this.name = name; + this.name = name; } @Override public String getDisplayName() { - return displayName; + return displayName; } public void setDisplayName(String displayName) { - this.displayName = displayName; + this.displayName = displayName; } @Override public String getUuid() { - return this.uuid; + return this.uuid; } public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } } diff --git a/engine/schema/src/com/cloud/storage/LaunchPermissionVO.java b/engine/schema/src/com/cloud/storage/LaunchPermissionVO.java index 992bac2365e..9082debbd51 100644 --- a/engine/schema/src/com/cloud/storage/LaunchPermissionVO.java +++ b/engine/schema/src/com/cloud/storage/LaunchPermissionVO.java @@ -24,19 +24,20 @@ import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(name="launch_permission") +@Table(name = "launch_permission") public class LaunchPermissionVO implements InternalIdentity { @Id - @Column(name="id") + @Column(name = "id") private Long id; - @Column(name="template_id") + @Column(name = "template_id") private long templateId; - @Column(name="account_id") + @Column(name = "account_id") private long accountId; - public LaunchPermissionVO() { } + public LaunchPermissionVO() { + } public LaunchPermissionVO(long templateId, long accountId) { this.templateId = templateId; diff --git a/engine/schema/src/com/cloud/storage/S3VO.java b/engine/schema/src/com/cloud/storage/S3VO.java index ec49bc92d74..6b2c23fc1ae 100644 --- a/engine/schema/src/com/cloud/storage/S3VO.java +++ b/engine/schema/src/com/cloud/storage/S3VO.java @@ -18,10 +18,7 @@ */ package com.cloud.storage; -import com.cloud.agent.api.to.S3TO; -import com.cloud.utils.db.GenericDao; -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; +import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; @@ -29,7 +26,9 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import java.util.Date; + +import com.cloud.agent.api.to.S3TO; +import com.cloud.utils.db.GenericDao; @Entity @Table(name = "s3") @@ -76,11 +75,9 @@ public class S3VO implements S3 { super(); } - public S3VO(final String uuid, final String accessKey, - final String secretKey, final String endPoint, - final String bucketName, final Boolean httpsFlag, - final Integer connectionTimeout, final Integer maxErrorRetry, - final Integer socketTimeout, final Date created) { + public S3VO(final String uuid, final String accessKey, final String secretKey, final String endPoint, + final String bucketName, final Boolean httpsFlag, final Integer connectionTimeout, + final Integer maxErrorRetry, final Integer socketTimeout, final Date created) { super(); @@ -111,10 +108,8 @@ public class S3VO implements S3 { httpsFlag = this.httpsFlag == 0 ? false : true; } - return new S3TO(this.id, this.uuid, this.accessKey, this.secretKey, - this.endPoint, this.bucketName, httpsFlag, - this.connectionTimeout, this.maxErrorRetry, this.socketTimeout, - this.created); + return new S3TO(this.id, this.uuid, this.accessKey, this.secretKey, this.endPoint, this.bucketName, httpsFlag, + this.connectionTimeout, this.maxErrorRetry, this.socketTimeout, this.created); } diff --git a/engine/schema/src/com/cloud/storage/SnapshotPolicyVO.java b/engine/schema/src/com/cloud/storage/SnapshotPolicyVO.java index 4eb4916afd3..fc6283d177f 100644 --- a/engine/schema/src/com/cloud/storage/SnapshotPolicyVO.java +++ b/engine/schema/src/com/cloud/storage/SnapshotPolicyVO.java @@ -25,53 +25,51 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import org.apache.cloudstack.api.Identity; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.utils.DateUtil.IntervalType; -import org.apache.cloudstack.api.InternalIdentity; @Entity -@Table(name="snapshot_policy") +@Table(name = "snapshot_policy") public class SnapshotPolicyVO implements SnapshotPolicy { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") long id; - @Column(name="volume_id") + @Column(name = "volume_id") long volumeId; - @Column(name="schedule") + @Column(name = "schedule") String schedule; - @Column(name="timezone") + @Column(name = "timezone") String timezone; - @Column(name="interval") + @Column(name = "interval") private short interval; - @Column(name="max_snaps") + @Column(name = "max_snaps") private int maxSnaps; - @Column(name="active") + @Column(name = "active") boolean active = false; - @Column(name="uuid") + @Column(name = "uuid") String uuid; public SnapshotPolicyVO() { - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } public SnapshotPolicyVO(long volumeId, String schedule, String timezone, IntervalType intvType, int maxSnaps) { - this.volumeId = volumeId; + this.volumeId = volumeId; this.schedule = schedule; this.timezone = timezone; - this.interval = (short)intvType.ordinal(); + this.interval = (short) intvType.ordinal(); this.maxSnaps = maxSnaps; this.active = true; - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } public long getId() { @@ -79,10 +77,10 @@ public class SnapshotPolicyVO implements SnapshotPolicy { } public long getVolumeId() { - return volumeId; - } + return volumeId; + } - public void setSchedule(String schedule) { + public void setSchedule(String schedule) { this.schedule = schedule; } @@ -124,10 +122,10 @@ public class SnapshotPolicyVO implements SnapshotPolicy { @Override public String getUuid() { - return this.uuid; + return this.uuid; } public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } } diff --git a/engine/schema/src/com/cloud/storage/SnapshotScheduleVO.java b/engine/schema/src/com/cloud/storage/SnapshotScheduleVO.java index 75757c6b22b..7adc136066f 100644 --- a/engine/schema/src/com/cloud/storage/SnapshotScheduleVO.java +++ b/engine/schema/src/com/cloud/storage/SnapshotScheduleVO.java @@ -28,40 +28,40 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.cloudstack.api.Identity; import com.cloud.storage.snapshot.SnapshotSchedule; -import org.apache.cloudstack.api.InternalIdentity; @Entity -@Table(name="snapshot_schedule") +@Table(name = "snapshot_schedule") public class SnapshotScheduleVO implements SnapshotSchedule { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - long id; + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; - // DB constraint: For a given volume and policyId, there will only be one entry in this table. - @Column(name="volume_id") + // DB constraint: For a given volume and policyId, there will only be one + // entry in this table. + @Column(name = "volume_id") long volumeId; - @Column(name="policy_id") + @Column(name = "policy_id") long policyId; - @Column(name="scheduled_timestamp") - @Temporal(value=TemporalType.TIMESTAMP) + @Column(name = "scheduled_timestamp") + @Temporal(value = TemporalType.TIMESTAMP) Date scheduledTimestamp; - @Column(name="async_job_id") + @Column(name = "async_job_id") Long asyncJobId; - @Column(name="snapshot_id") + @Column(name = "snapshot_id") Long snapshotId; - @Column(name="uuid") + @Column(name = "uuid") String uuid = UUID.randomUUID().toString(); - public SnapshotScheduleVO() { } + public SnapshotScheduleVO() { + } public SnapshotScheduleVO(long volumeId, long policyId, Date scheduledTimestamp) { this.volumeId = volumeId; @@ -83,43 +83,43 @@ public class SnapshotScheduleVO implements SnapshotSchedule { return policyId; } - public void setPolicyId(long policyId) { + public void setPolicyId(long policyId) { this.policyId = policyId; } /** - * @return the scheduledTimestamp - */ - public Date getScheduledTimestamp() { - return scheduledTimestamp; - } + * @return the scheduledTimestamp + */ + public Date getScheduledTimestamp() { + return scheduledTimestamp; + } - public void setScheduledTimestamp(Date scheduledTimestamp) { + public void setScheduledTimestamp(Date scheduledTimestamp) { this.scheduledTimestamp = scheduledTimestamp; } public Long getAsyncJobId() { - return asyncJobId; - } + return asyncJobId; + } - public void setAsyncJobId(Long asyncJobId) { - this.asyncJobId = asyncJobId; - } + public void setAsyncJobId(Long asyncJobId) { + this.asyncJobId = asyncJobId; + } - public Long getSnapshotId() { - return snapshotId; - } + public Long getSnapshotId() { + return snapshotId; + } - public void setSnapshotId(Long snapshotId) { - this.snapshotId = snapshotId; - } + public void setSnapshotId(Long snapshotId) { + this.snapshotId = snapshotId; + } - @Override - public String getUuid() { - return this.uuid; - } + @Override + public String getUuid() { + return this.uuid; + } - public void setUuid(String uuid) { - this.uuid = uuid; - } + public void setUuid(String uuid) { + this.uuid = uuid; + } } diff --git a/engine/schema/src/com/cloud/storage/SnapshotVO.java b/engine/schema/src/com/cloud/storage/SnapshotVO.java index 4fc195cfec4..e3912740a48 100644 --- a/engine/schema/src/com/cloud/storage/SnapshotVO.java +++ b/engine/schema/src/com/cloud/storage/SnapshotVO.java @@ -25,69 +25,70 @@ import java.util.Date; import java.util.UUID; @Entity -@Table(name="snapshots") +@Table(name = "snapshots") public class SnapshotVO implements Snapshot { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private long id; - @Column(name="data_center_id") + @Column(name = "data_center_id") long dataCenterId; - @Column(name="account_id") + @Column(name = "account_id") long accountId; - @Column(name="domain_id") + @Column(name = "domain_id") long domainId; - @Column(name="volume_id") + @Column(name = "volume_id") Long volumeId; - @Column(name="disk_offering_id") + @Column(name = "disk_offering_id") Long diskOfferingId; @Expose - @Column(name="name") + @Column(name = "name") String name; @Expose - @Column(name="status", updatable = true, nullable=false) - @Enumerated(value=EnumType.STRING) + @Column(name = "status", updatable = true, nullable = false) + @Enumerated(value = EnumType.STRING) private State state; - @Column(name="snapshot_type") + @Column(name = "snapshot_type") short snapshotType; - @Column(name="type_description") + @Column(name = "type_description") String typeDescription; - @Column(name="size") + @Column(name = "size") long size; - @Column(name=GenericDao.CREATED_COLUMN) + @Column(name = GenericDao.CREATED_COLUMN) Date created; - @Column(name=GenericDao.REMOVED_COLUMN) + @Column(name = GenericDao.REMOVED_COLUMN) Date removed; - @Column(name="hypervisor_type") - @Enumerated(value=EnumType.STRING) - HypervisorType hypervisorType; + @Column(name = "hypervisor_type") + @Enumerated(value = EnumType.STRING) + HypervisorType hypervisorType; @Expose - @Column(name="version") + @Column(name = "version") String version; - @Column(name="uuid") + @Column(name = "uuid") String uuid; public SnapshotVO() { this.uuid = UUID.randomUUID().toString(); } - public SnapshotVO(long dcId, long accountId, long domainId, Long volumeId, Long diskOfferingId, String name, short snapshotType, String typeDescription, long size, HypervisorType hypervisorType ) { + public SnapshotVO(long dcId, long accountId, long domainId, Long volumeId, Long diskOfferingId, String name, + short snapshotType, String typeDescription, long size, HypervisorType hypervisorType) { this.dataCenterId = dcId; this.accountId = accountId; this.domainId = domainId; @@ -135,11 +136,11 @@ public class SnapshotVO implements Snapshot { this.volumeId = volumeId; } - @Override public String getName() { return name; } + @Override public short getsnapshotType() { return snapshotType; @@ -163,8 +164,8 @@ public class SnapshotVO implements Snapshot { } @Override - public boolean isRecursive(){ - if ( snapshotType >= Type.HOURLY.ordinal() && snapshotType <= Type.MONTHLY.ordinal() ) { + public boolean isRecursive() { + if (snapshotType >= Type.HOURLY.ordinal() && snapshotType <= Type.MONTHLY.ordinal()) { return true; } return false; @@ -177,6 +178,7 @@ public class SnapshotVO implements Snapshot { public String getTypeDescription() { return typeDescription; } + public void setTypeDescription(String typeDescription) { this.typeDescription = typeDescription; } @@ -203,14 +205,13 @@ public class SnapshotVO implements Snapshot { return state; } - - public void setState(State state) { + public void setState(State state) { this.state = state; } public static Type getSnapshotType(String snapshotType) { - for ( Type type : Type.values()) { - if ( type.equals(snapshotType)) { + for (Type type : Type.values()) { + if (type.equals(snapshotType)) { return type; } } diff --git a/engine/schema/src/com/cloud/storage/StoragePoolHostAssoc.java b/engine/schema/src/com/cloud/storage/StoragePoolHostAssoc.java index 34326d963a6..1b20bf62c66 100644 --- a/engine/schema/src/com/cloud/storage/StoragePoolHostAssoc.java +++ b/engine/schema/src/com/cloud/storage/StoragePoolHostAssoc.java @@ -21,15 +21,15 @@ import org.apache.cloudstack.api.InternalIdentity; import java.util.Date; public interface StoragePoolHostAssoc extends InternalIdentity { - - long getHostId(); - - long getPoolId(); - - String getLocalPath(); - Date getCreated(); + long getHostId(); - Date getLastUpdated(); + long getPoolId(); + + String getLocalPath(); + + Date getCreated(); + + Date getLastUpdated(); } diff --git a/engine/schema/src/com/cloud/storage/StoragePoolHostVO.java b/engine/schema/src/com/cloud/storage/StoragePoolHostVO.java index 1b02f6d9754..3b70984e63c 100644 --- a/engine/schema/src/com/cloud/storage/StoragePoolHostVO.java +++ b/engine/schema/src/com/cloud/storage/StoragePoolHostVO.java @@ -31,79 +31,73 @@ import com.cloud.utils.db.GenericDaoBase; /** * Join table for storage pools and hosts - * + * */ @Entity -@Table(name="storage_pool_host_ref") +@Table(name = "storage_pool_host_ref") public class StoragePoolHostVO implements StoragePoolHostAssoc { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @Column(name="pool_id") - private long poolId; + @Column(name = "pool_id") + private long poolId; - @Column(name="host_id") - private long hostId; + @Column(name = "host_id") + private long hostId; - @Column(name="local_path") - private String localPath; + @Column(name = "local_path") + private String localPath; - @Column(name=GenericDaoBase.CREATED_COLUMN) + @Column(name = GenericDaoBase.CREATED_COLUMN) private Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) private Date lastUpdated = null; + public StoragePoolHostVO() { + super(); + } - public StoragePoolHostVO() { - super(); - } - - - public StoragePoolHostVO(long poolId, long hostId, String localPath) { - this.poolId = poolId; - this.hostId = hostId; - this.localPath = localPath; - } - - - @Override - public long getHostId() { - return hostId; - } + public StoragePoolHostVO(long poolId, long hostId, String localPath) { + this.poolId = poolId; + this.hostId = hostId; + this.localPath = localPath; + } + @Override + public long getHostId() { + return hostId; + } @Override public long getId() { return id; } + @Override + public String getLocalPath() { + return localPath; + } @Override - public String getLocalPath() { - return localPath; - } + public long getPoolId() { + return poolId; + } - @Override - public long getPoolId() { - return poolId; - } + @Override + public Date getCreated() { + return created; + } - @Override - public Date getCreated() { - return created; - } + @Override + public Date getLastUpdated() { + return lastUpdated; + } - @Override - public Date getLastUpdated() { - return lastUpdated; - } - - - public void setLocalPath(String localPath) { - this.localPath = localPath; - } + public void setLocalPath(String localPath) { + this.localPath = localPath; + } } diff --git a/engine/schema/src/com/cloud/storage/StoragePoolWorkVO.java b/engine/schema/src/com/cloud/storage/StoragePoolWorkVO.java index 440065da66b..56d57ec1e33 100644 --- a/engine/schema/src/com/cloud/storage/StoragePoolWorkVO.java +++ b/engine/schema/src/com/cloud/storage/StoragePoolWorkVO.java @@ -27,9 +27,9 @@ import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(name="storage_pool_work") +@Table(name = "storage_pool_work") public class StoragePoolWorkVO implements InternalIdentity { - + public long getId() { return id; } @@ -42,22 +42,18 @@ public class StoragePoolWorkVO implements InternalIdentity { return poolId; } - public void setPoolId(Long poolId) { this.poolId = poolId; } - public boolean isStoppedForMaintenance() { return stoppedForMaintenance; } - public void setStoppedForMaintenance(boolean stoppedForMaintenance) { this.stoppedForMaintenance = stoppedForMaintenance; } - public boolean isStartedAfterMaintenance() { return startedAfterMaintenance; } @@ -73,7 +69,7 @@ public class StoragePoolWorkVO implements InternalIdentity { public void setVmId(Long vmId) { this.vmId = vmId; } - + public Long getManagementServerId() { return managementServerId; } @@ -83,27 +79,27 @@ public class StoragePoolWorkVO implements InternalIdentity { } @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private Long id; - - @Column(name="pool_id") + + @Column(name = "pool_id") private Long poolId; - @Column(name="vm_id") + @Column(name = "vm_id") private Long vmId; - - @Column(name="stopped_for_maintenance") + + @Column(name = "stopped_for_maintenance") private boolean stoppedForMaintenance; - - @Column(name="started_after_maintenance") + + @Column(name = "started_after_maintenance") private boolean startedAfterMaintenance; - @Column(name="mgmt_server_id") + @Column(name = "mgmt_server_id") private Long managementServerId; - - public StoragePoolWorkVO(long vmId, long poolId, boolean stoppedForMaintenance, boolean startedAfterMaintenance, long mgmtServerId) { + public StoragePoolWorkVO(long vmId, long poolId, boolean stoppedForMaintenance, boolean startedAfterMaintenance, + long mgmtServerId) { super(); this.vmId = vmId; this.poolId = poolId; @@ -111,8 +107,8 @@ public class StoragePoolWorkVO implements InternalIdentity { this.startedAfterMaintenance = startedAfterMaintenance; this.managementServerId = mgmtServerId; } - + public StoragePoolWorkVO() { - + } } diff --git a/engine/schema/src/com/cloud/storage/SwiftVO.java b/engine/schema/src/com/cloud/storage/SwiftVO.java index c99f0efc702..4136a224b3c 100644 --- a/engine/schema/src/com/cloud/storage/SwiftVO.java +++ b/engine/schema/src/com/cloud/storage/SwiftVO.java @@ -26,39 +26,40 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.agent.api.to.SwiftTO; -import org.apache.cloudstack.api.Identity; -import com.cloud.utils.db.GenericDao; import org.apache.cloudstack.api.InternalIdentity; +import com.cloud.agent.api.to.SwiftTO; +import com.cloud.utils.db.GenericDao; + @Entity -@Table(name="swift") +@Table(name = "swift") public class SwiftVO implements Swift, InternalIdentity { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private long id; - @Column(name="url") + @Column(name = "url") String url; - @Column(name="account") + @Column(name = "account") String account; - @Column(name="username") + @Column(name = "username") String userName; - @Column(name="key") + @Column(name = "key") String key; - @Column(name="uuid") + @Column(name = "uuid") String uuid = UUID.randomUUID().toString(); @Column(name = GenericDao.CREATED_COLUMN) private Date created; - public SwiftVO() { } + public SwiftVO() { + } public SwiftVO(String url, String account, String userName, String key) { this.url = url; @@ -71,18 +72,22 @@ public class SwiftVO implements Swift, InternalIdentity { public long getId() { return id; } + @Override public String getUrl() { return url; } + @Override public String getAccount() { return account; } + @Override public String getUserName() { return userName; } + @Override public String getKey() { return key; @@ -99,10 +104,10 @@ public class SwiftVO implements Swift, InternalIdentity { @Override public String getUuid() { - return this.uuid; + return this.uuid; } public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } } diff --git a/engine/schema/src/com/cloud/storage/UploadVO.java b/engine/schema/src/com/cloud/storage/UploadVO.java index fe8b81280fd..63fadfac3e8 100755 --- a/engine/schema/src/com/cloud/storage/UploadVO.java +++ b/engine/schema/src/com/cloud/storage/UploadVO.java @@ -34,112 +34,109 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDaoBase; @Entity -@Table(name="upload") +@Table(name = "upload") public class UploadVO implements Upload { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + long id; - @Column(name="uuid") - private String uuid; + @Column(name = "uuid") + private String uuid; - @Column(name="host_id") - private long storeId; + @Column(name = "host_id") + private long storeId; - @Column(name="type_id") - private long typeId; + @Column(name = "type_id") + private long typeId; - @Column(name=GenericDaoBase.CREATED_COLUMN) - private Date created = null; + @Column(name = GenericDaoBase.CREATED_COLUMN) + private Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastUpdated = null; - @Column (name="upload_pct") - private int uploadPercent; + @Column(name = "upload_pct") + private int uploadPercent; - @Column (name="type") - @Enumerated(EnumType.STRING) - private Type type; + @Column(name = "type") + @Enumerated(EnumType.STRING) + private Type type; - @Column (name="mode") + @Column(name = "mode") @Enumerated(EnumType.STRING) private Mode mode = Mode.FTP_UPLOAD; - @Column (name="upload_state") - @Enumerated(EnumType.STRING) - private Status uploadState; + @Column(name = "upload_state") + @Enumerated(EnumType.STRING) + private Status uploadState; - @Column (name="error_str") - private String errorString; + @Column(name = "error_str") + private String errorString; - @Column (name="job_id") - private String jobId; + @Column(name = "job_id") + private String jobId; - @Column (name="url") - private String uploadUrl; + @Column(name = "url") + private String uploadUrl; - @Column (name="install_path") - private String installPath; + @Column(name = "install_path") + private String installPath; - @Override + @Override public long getDataStoreId() { - return storeId; - } + return storeId; + } - public void setDataStoreId(long hostId) { - this.storeId = hostId; - } + public void setDataStoreId(long hostId) { + this.storeId = hostId; + } - @Override + @Override public long getId() { - return id; - } + return id; + } - - @Override + @Override public String getUuid() { return uuid; } @Override public Date getCreated() { - return created; - } + return created; + } - @Override + @Override public Date getLastUpdated() { - return lastUpdated; - } + return lastUpdated; + } - public void setLastUpdated(Date date) { - lastUpdated = date; - } + public void setLastUpdated(Date date) { + lastUpdated = date; + } - public UploadVO(long hostId, long templateId) { - super(); - this.storeId = hostId; - this.typeId = templateId; - this.uuid = UUID.randomUUID().toString(); - } - - public UploadVO(long hostId, long typeId, Date lastUpdated, - Status uploadState, Type type, - String uploadUrl, Mode mode) { - super(); - this.storeId = hostId; - this.typeId = typeId; - this.lastUpdated = lastUpdated; - this.uploadState = uploadState; - this.mode = mode; - this.type = type; - this.uploadUrl = uploadUrl; + public UploadVO(long hostId, long templateId) { + super(); + this.storeId = hostId; + this.typeId = templateId; this.uuid = UUID.randomUUID().toString(); - } + } - public UploadVO(long hostId, long typeId, Date lastUpdated, - Status uploadState, int uploadPercent, Type type, + public UploadVO(long hostId, long typeId, Date lastUpdated, Status uploadState, Type type, String uploadUrl, + Mode mode) { + super(); + this.storeId = hostId; + this.typeId = typeId; + this.lastUpdated = lastUpdated; + this.uploadState = uploadState; + this.mode = mode; + this.type = type; + this.uploadUrl = uploadUrl; + this.uuid = UUID.randomUUID().toString(); + } + + public UploadVO(long hostId, long typeId, Date lastUpdated, Status uploadState, int uploadPercent, Type type, Mode mode) { super(); this.storeId = hostId; @@ -153,82 +150,83 @@ public class UploadVO implements Upload { } - protected UploadVO() { - } + protected UploadVO() { + } - public UploadVO(Long uploadId) { - this.id = uploadId; - } + public UploadVO(Long uploadId) { + this.id = uploadId; + } - public void setErrorString(String errorString) { - this.errorString = errorString; - } + public void setErrorString(String errorString) { + this.errorString = errorString; + } - @Override + @Override public String getErrorString() { - return errorString; - } + return errorString; + } - public void setJobId(String jobId) { - this.jobId = jobId; - } + public void setJobId(String jobId) { + this.jobId = jobId; + } - @Override + @Override public String getJobId() { - return jobId; - } + return jobId; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof UploadVO) { - UploadVO other = (UploadVO)obj; - return (this.typeId==other.getTypeId() && this.storeId==other.getDataStoreId() && this.type == other.getType()); - } - return false; - } + @Override + public boolean equals(Object obj) { + if (obj instanceof UploadVO) { + UploadVO other = (UploadVO) obj; + return (this.typeId == other.getTypeId() && this.storeId == other.getDataStoreId() && this.type == other + .getType()); + } + return false; + } - @Override - public int hashCode() { - return NumbersUtil.hash(id); - } + @Override + public int hashCode() { + return NumbersUtil.hash(id); + } - @Override + @Override public int getUploadPercent() { - return uploadPercent; - } + return uploadPercent; + } - public void setUploadPercent(int uploadPercent) { - this.uploadPercent = uploadPercent; - } + public void setUploadPercent(int uploadPercent) { + this.uploadPercent = uploadPercent; + } - @Override + @Override public Status getUploadState() { - return uploadState; - } + return uploadState; + } - public void setUploadState(Status uploadState) { - this.uploadState = uploadState; - } + public void setUploadState(Status uploadState) { + this.uploadState = uploadState; + } - @Override + @Override public long getTypeId() { - return typeId; - } + return typeId; + } - public void setTypeId(long typeId) { - this.typeId = typeId; - } + public void setTypeId(long typeId) { + this.typeId = typeId; + } - @Override + @Override public Type getType() { - return type; - } + return type; + } - public void setType(Type type) { - this.type = type; - } + public void setType(Type type) { + this.type = type; + } - @Override + @Override public Mode getMode() { return mode; } @@ -239,22 +237,22 @@ public class UploadVO implements Upload { @Override public String getUploadUrl() { - return uploadUrl; - } + return uploadUrl; + } - public void setUploadUrl(String uploadUrl) { - this.uploadUrl = uploadUrl; - } + public void setUploadUrl(String uploadUrl) { + this.uploadUrl = uploadUrl; + } - @Override + @Override public void setId(Long id) { - this.id = id; - } + this.id = id; + } - @Override + @Override public void setCreated(Date created) { - this.created = created; - } + this.created = created; + } @Override public String getInstallPath() { diff --git a/engine/schema/src/com/cloud/storage/VMTemplateDetailVO.java b/engine/schema/src/com/cloud/storage/VMTemplateDetailVO.java index c007802db3f..3d4c7ef30db 100644 --- a/engine/schema/src/com/cloud/storage/VMTemplateDetailVO.java +++ b/engine/schema/src/com/cloud/storage/VMTemplateDetailVO.java @@ -26,59 +26,60 @@ import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(name="vm_template_details") +@Table(name = "vm_template_details") public class VMTemplateDetailVO implements InternalIdentity { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private long id; - - @Column(name="template_id") + + @Column(name = "template_id") private long templateId; - - @Column(name="name") + + @Column(name = "name") private String name; - - @Column(name="value", length=1024) + + @Column(name = "value", length = 1024) private String value; - - public VMTemplateDetailVO() {} - - public VMTemplateDetailVO(long templateId, String name, String value) { - this.templateId = templateId; - this.name = name; - this.value = value; + + public VMTemplateDetailVO() { } - public long getId() { - return id; - } + public VMTemplateDetailVO(long templateId, String name, String value) { + this.templateId = templateId; + this.name = name; + this.value = value; + } - public long getTemplateId() { - return templateId; - } + public long getId() { + return id; + } - public String getName() { - return name; - } + public long getTemplateId() { + return templateId; + } - public String getValue() { - return value; - } + public String getName() { + return name; + } - public void setId(long id) { - this.id = id; - } + public String getValue() { + return value; + } - public void setTemplateId(long templateId) { - this.templateId = templateId; - } + public void setId(long id) { + this.id = id; + } - public void setName(String name) { - this.name = name; - } + public void setTemplateId(long templateId) { + this.templateId = templateId; + } - public void setValue(String value) { - this.value = value; - } + public void setName(String name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } } diff --git a/engine/schema/src/com/cloud/storage/VMTemplateHostVO.java b/engine/schema/src/com/cloud/storage/VMTemplateHostVO.java index 227394248b3..33732a419c9 100755 --- a/engine/schema/src/com/cloud/storage/VMTemplateHostVO.java +++ b/engine/schema/src/com/cloud/storage/VMTemplateHostVO.java @@ -37,63 +37,63 @@ import com.cloud.utils.db.GenericDaoBase; /** * Join table for storage hosts and templates - * + * */ @Entity -@Table(name="template_host_ref") +@Table(name = "template_host_ref") public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc, DataObjectInStore { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Long id; - @Column(name="host_id") - private long hostId; + @Column(name = "host_id") + private long hostId; - @Column(name="template_id") - private long templateId; + @Column(name = "template_id") + private long templateId; - @Column(name=GenericDaoBase.CREATED_COLUMN) - private Date created = null; + @Column(name = GenericDaoBase.CREATED_COLUMN) + private Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastUpdated = null; - @Column (name="download_pct") - private int downloadPercent; + @Column(name = "download_pct") + private int downloadPercent; - @Column (name="size") - private long size; + @Column(name = "size") + private long size; - @Column (name="physical_size") - private long physicalSize; + @Column(name = "physical_size") + private long physicalSize; - @Column (name="download_state") - @Enumerated(EnumType.STRING) - private Status downloadState; + @Column(name = "download_state") + @Enumerated(EnumType.STRING) + private Status downloadState; - @Column (name="local_path") - private String localDownloadPath; + @Column(name = "local_path") + private String localDownloadPath; - @Column (name="error_str") - private String errorString; + @Column(name = "error_str") + private String errorString; - @Column (name="job_id") - private String jobId; + @Column(name = "job_id") + private String jobId; - @Column (name="install_path") + @Column(name = "install_path") private String installPath; - @Column (name="url") - private String downloadUrl; + @Column(name = "url") + private String downloadUrl; - @Column(name="is_copy") - private boolean isCopy = false; + @Column(name = "is_copy") + private boolean isCopy = false; - @Column(name="destroyed") + @Column(name = "destroyed") boolean destroyed = false; - @Column(name="update_count", updatable = true, nullable=false) + @Column(name = "update_count", updatable = true, nullable = false) protected long updatedCount; @Column(name = "updated") @@ -104,148 +104,145 @@ public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc, DataObj @Enumerated(EnumType.STRING) ObjectInDataStoreStateMachine.State state; - - @Override + @Override public String getInstallPath() { - return installPath; - } + return installPath; + } - public long getHostId() { - return hostId; - } + public long getHostId() { + return hostId; + } - public void setHostId(long hostId) { - this.hostId = hostId; - } + public void setHostId(long hostId) { + this.hostId = hostId; + } - @Override + @Override public long getTemplateId() { - return templateId; - } + return templateId; + } - @Override + @Override public void setTemplateId(long templateId) { - this.templateId = templateId; - } + this.templateId = templateId; + } - @Override + @Override public int getDownloadPercent() { - return downloadPercent; - } + return downloadPercent; + } - @Override + @Override public void setDownloadPercent(int downloadPercent) { - this.downloadPercent = downloadPercent; - } + this.downloadPercent = downloadPercent; + } - @Override + @Override public void setDownloadState(Status downloadState) { - this.downloadState = downloadState; - } + this.downloadState = downloadState; + } - @Override + @Override public long getId() { - return id; - } + return id; + } - @Override + @Override public Date getCreated() { - return created; - } + return created; + } - @Override + @Override public Date getLastUpdated() { - return lastUpdated; - } + return lastUpdated; + } - @Override + @Override public void setLastUpdated(Date date) { - lastUpdated = date; - } + lastUpdated = date; + } - @Override + @Override public void setInstallPath(String installPath) { - this.installPath = installPath; - } + this.installPath = installPath; + } - @Override + @Override public Status getDownloadState() { - return downloadState; - } + return downloadState; + } - public VMTemplateHostVO(long hostId, long templateId) { - super(); - this.hostId = hostId; - this.templateId = templateId; - this.state = ObjectInDataStoreStateMachine.State.Allocated; - } + public VMTemplateHostVO(long hostId, long templateId) { + super(); + this.hostId = hostId; + this.templateId = templateId; + this.state = ObjectInDataStoreStateMachine.State.Allocated; + } - public VMTemplateHostVO(long hostId, long templateId, Date lastUpdated, - int downloadPercent, Status downloadState, - String localDownloadPath, String errorString, String jobId, - String installPath, String downloadUrl) { - super(); - this.hostId = hostId; - this.templateId = templateId; - this.lastUpdated = lastUpdated; - this.downloadPercent = downloadPercent; - this.downloadState = downloadState; - this.localDownloadPath = localDownloadPath; - this.errorString = errorString; - this.jobId = jobId; - this.installPath = installPath; - this.setDownloadUrl(downloadUrl); - } + public VMTemplateHostVO(long hostId, long templateId, Date lastUpdated, int downloadPercent, Status downloadState, + String localDownloadPath, String errorString, String jobId, String installPath, String downloadUrl) { + super(); + this.hostId = hostId; + this.templateId = templateId; + this.lastUpdated = lastUpdated; + this.downloadPercent = downloadPercent; + this.downloadState = downloadState; + this.localDownloadPath = localDownloadPath; + this.errorString = errorString; + this.jobId = jobId; + this.installPath = installPath; + this.setDownloadUrl(downloadUrl); + } - protected VMTemplateHostVO() { + protected VMTemplateHostVO() { - } + } - @Override + @Override public void setLocalDownloadPath(String localPath) { - this.localDownloadPath = localPath; - } + this.localDownloadPath = localPath; + } - @Override + @Override public String getLocalDownloadPath() { - return localDownloadPath; - } + return localDownloadPath; + } - @Override + @Override public void setErrorString(String errorString) { - this.errorString = errorString; - } + this.errorString = errorString; + } - @Override + @Override public String getErrorString() { - return errorString; - } + return errorString; + } - @Override + @Override public void setJobId(String jobId) { - this.jobId = jobId; - } + this.jobId = jobId; + } - @Override + @Override public String getJobId() { - return jobId; - } + return jobId; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof VMTemplateHostVO) { - VMTemplateHostVO other = (VMTemplateHostVO)obj; - return (this.templateId==other.getTemplateId() && this.hostId==other.getHostId()); - } - return false; - } + @Override + public boolean equals(Object obj) { + if (obj instanceof VMTemplateHostVO) { + VMTemplateHostVO other = (VMTemplateHostVO) obj; + return (this.templateId == other.getTemplateId() && this.hostId == other.getHostId()); + } + return false; + } - @Override - public int hashCode() { - Long tid = new Long(templateId); - Long hid = new Long(hostId); - return tid.hashCode()+hid.hashCode(); - } + @Override + public int hashCode() { + Long tid = new Long(templateId); + Long hid = new Long(hostId); + return tid.hashCode() + hid.hashCode(); + } public void setSize(long size) { this.size = size; @@ -255,7 +252,6 @@ public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc, DataObj return size; } - public void setPhysicalSize(long physicalSize) { this.physicalSize = physicalSize; } @@ -265,38 +261,39 @@ public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc, DataObj } public void setDestroyed(boolean destroyed) { - this.destroyed = destroyed; + this.destroyed = destroyed; } public boolean getDestroyed() { - return destroyed; + return destroyed; } - public void setDownloadUrl(String downloadUrl) { - this.downloadUrl = downloadUrl; - } + public void setDownloadUrl(String downloadUrl) { + this.downloadUrl = downloadUrl; + } - public String getDownloadUrl() { - return downloadUrl; - } + public String getDownloadUrl() { + return downloadUrl; + } - public void setCopy(boolean isCopy) { - this.isCopy = isCopy; - } + public void setCopy(boolean isCopy) { + this.isCopy = isCopy; + } - public boolean isCopy() { - return isCopy; - } + public boolean isCopy() { + return isCopy; + } - @Override + @Override public long getTemplateSize() { - return -1; - } + return -1; + } - @Override + @Override public String toString() { - return new StringBuilder("TmplHost[").append(id).append("-").append(templateId).append("-").append(hostId).append(installPath).append("]").toString(); - } + return new StringBuilder("TmplHost[").append(id).append("-").append(templateId).append("-").append(hostId) + .append(installPath).append("]").toString(); + } @Override public ObjectInDataStoreStateMachine.State getState() { @@ -335,5 +332,4 @@ public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc, DataObj return this.state; } - } diff --git a/engine/schema/src/com/cloud/storage/VMTemplateS3VO.java b/engine/schema/src/com/cloud/storage/VMTemplateS3VO.java index 02f3ff5cf7f..e106bf7d1a5 100644 --- a/engine/schema/src/com/cloud/storage/VMTemplateS3VO.java +++ b/engine/schema/src/com/cloud/storage/VMTemplateS3VO.java @@ -62,8 +62,8 @@ public class VMTemplateS3VO implements InternalIdentity { super(); } - public VMTemplateS3VO(final long s3Id, final long templateId, - final Date created, final Long size, final Long physicalSize) { + public VMTemplateS3VO(final long s3Id, final long templateId, final Date created, final Long size, + final Long physicalSize) { super(); @@ -100,19 +100,16 @@ public class VMTemplateS3VO implements InternalIdentity { return false; } - if (this.created != null ? !created.equals(thatVMTemplateS3VO.created) - : thatVMTemplateS3VO.created != null) { + if (this.created != null ? !created.equals(thatVMTemplateS3VO.created) : thatVMTemplateS3VO.created != null) { return false; } - if (this.physicalSize != null ? !physicalSize - .equals(thatVMTemplateS3VO.physicalSize) + if (this.physicalSize != null ? !physicalSize.equals(thatVMTemplateS3VO.physicalSize) : thatVMTemplateS3VO.physicalSize != null) { return false; } - if (this.size != null ? !size.equals(thatVMTemplateS3VO.size) - : thatVMTemplateS3VO.size != null) { + if (this.size != null ? !size.equals(thatVMTemplateS3VO.size) : thatVMTemplateS3VO.size != null) { return false; } @@ -125,14 +122,10 @@ public class VMTemplateS3VO implements InternalIdentity { int result = (int) (this.id ^ (this.id >>> 32)); result = 31 * result + (int) (this.s3Id ^ (this.s3Id >>> 32)); - result = 31 * result - + (int) (this.templateId ^ (this.templateId >>> 32)); - result = 31 * result - + (this.created != null ? this.created.hashCode() : 0); + result = 31 * result + (int) (this.templateId ^ (this.templateId >>> 32)); + result = 31 * result + (this.created != null ? this.created.hashCode() : 0); result = 31 * result + (this.size != null ? this.size.hashCode() : 0); - result = 31 - * result - + (this.physicalSize != null ? this.physicalSize.hashCode() : 0); + result = 31 * result + (this.physicalSize != null ? this.physicalSize.hashCode() : 0); return result; @@ -189,13 +182,10 @@ public class VMTemplateS3VO implements InternalIdentity { @Override public String toString() { - final StringBuilder stringBuilder = new StringBuilder( - "VMTemplateS3VO [ id: ").append(id).append(", created: ") - .append(DateFormat.getDateTimeInstance().format(created)) - .append(", physicalSize: ").append(physicalSize) - .append(", size: ").append(size).append(", templateId: ") - .append(templateId).append(", s3Id: ").append(s3Id) - .append(" ]"); + final StringBuilder stringBuilder = new StringBuilder("VMTemplateS3VO [ id: ").append(id).append(", created: ") + .append(DateFormat.getDateTimeInstance().format(created)).append(", physicalSize: ") + .append(physicalSize).append(", size: ").append(size).append(", templateId: ").append(templateId) + .append(", s3Id: ").append(s3Id).append(" ]"); return stringBuilder.toString(); diff --git a/engine/schema/src/com/cloud/storage/VMTemplateStoragePoolVO.java b/engine/schema/src/com/cloud/storage/VMTemplateStoragePoolVO.java index 4c6a758ca90..10ced67244f 100644 --- a/engine/schema/src/com/cloud/storage/VMTemplateStoragePoolVO.java +++ b/engine/schema/src/com/cloud/storage/VMTemplateStoragePoolVO.java @@ -37,218 +37,229 @@ import com.cloud.utils.db.GenericDaoBase; /** * Join table for storage pools and templates - * + * */ @Entity -@Table(name="template_spool_ref") +@Table(name = "template_spool_ref") public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc, DataObjectInStore { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + long id; - @Column(name="pool_id") - private long poolId; + @Column(name = "pool_id") + private long poolId; - @Column(name="template_id") long templateId; + @Column(name = "template_id") + long templateId; - @Column(name=GenericDaoBase.CREATED_COLUMN) Date created = null; + @Column(name = GenericDaoBase.CREATED_COLUMN) + Date created = null; - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) Date lastUpdated = null; + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + Date lastUpdated = null; - @Column (name="download_pct") int downloadPercent; + @Column(name = "download_pct") + int downloadPercent; - @Column (name="download_state") - @Enumerated(EnumType.STRING) Status downloadState; + @Column(name = "download_state") + @Enumerated(EnumType.STRING) + Status downloadState; - @Column (name="local_path") String localDownloadPath; + @Column(name = "local_path") + String localDownloadPath; - @Column (name="error_str") String errorString; + @Column(name = "error_str") + String errorString; - @Column (name="job_id") String jobId; + @Column(name = "job_id") + String jobId; - @Column (name="install_path") String installPath; + @Column(name = "install_path") + String installPath; - @Column (name="template_size") long templateSize; + @Column(name = "template_size") + long templateSize; - @Column (name="marked_for_gc") boolean markedForGC; + @Column(name = "marked_for_gc") + boolean markedForGC; - @Column(name="update_count", updatable = true, nullable=false) - protected long updatedCount; + @Column(name = "update_count", updatable = true, nullable = false) + protected long updatedCount; - @Column(name = "updated") - @Temporal(value = TemporalType.TIMESTAMP) - Date updated; + @Column(name = "updated") + @Temporal(value = TemporalType.TIMESTAMP) + Date updated; - @Column(name = "state") - @Enumerated(EnumType.STRING) - ObjectInDataStoreStateMachine.State state; + @Column(name = "state") + @Enumerated(EnumType.STRING) + ObjectInDataStoreStateMachine.State state; - @Override + @Override public String getInstallPath() { - return installPath; - } + return installPath; + } - @Override + @Override public long getTemplateSize() { - return templateSize; - } + return templateSize; + } - public long getPoolId() { - return poolId; - } + public long getPoolId() { + return poolId; + } - public void setpoolId(long poolId) { - this.poolId = poolId; - } + public void setpoolId(long poolId) { + this.poolId = poolId; + } - @Override + @Override public long getTemplateId() { - return templateId; - } + return templateId; + } - @Override + @Override public void setTemplateId(long templateId) { - this.templateId = templateId; - } + this.templateId = templateId; + } - @Override + @Override public int getDownloadPercent() { - return downloadPercent; - } + return downloadPercent; + } - @Override + @Override public void setDownloadPercent(int downloadPercent) { - this.downloadPercent = downloadPercent; - } + this.downloadPercent = downloadPercent; + } - @Override + @Override public void setDownloadState(Status downloadState) { - this.downloadState = downloadState; - } + this.downloadState = downloadState; + } - @Override + @Override public long getId() { - return id; - } + return id; + } - @Override + @Override public Date getCreated() { - return created; - } + return created; + } - @Override + @Override public Date getLastUpdated() { - return lastUpdated; - } + return lastUpdated; + } - @Override + @Override public void setLastUpdated(Date date) { - lastUpdated = date; - } + lastUpdated = date; + } - @Override + @Override public void setInstallPath(String installPath) { - this.installPath = installPath; - } + this.installPath = installPath; + } - @Override + @Override public Status getDownloadState() { - return downloadState; - } + return downloadState; + } - public VMTemplateStoragePoolVO(long poolId, long templateId) { - super(); - this.poolId = poolId; - this.templateId = templateId; - this.downloadState = Status.NOT_DOWNLOADED; - this.state = ObjectInDataStoreStateMachine.State.Allocated; - this.markedForGC = false; - } + public VMTemplateStoragePoolVO(long poolId, long templateId) { + super(); + this.poolId = poolId; + this.templateId = templateId; + this.downloadState = Status.NOT_DOWNLOADED; + this.state = ObjectInDataStoreStateMachine.State.Allocated; + this.markedForGC = false; + } - public VMTemplateStoragePoolVO(long poolId, long templateId, Date lastUpdated, - int downloadPercent, Status downloadState, - String localDownloadPath, String errorString, String jobId, - String installPath, long templateSize) { - super(); - this.poolId = poolId; - this.templateId = templateId; - this.lastUpdated = lastUpdated; - this.downloadPercent = downloadPercent; - this.downloadState = downloadState; - this.localDownloadPath = localDownloadPath; - this.errorString = errorString; - this.jobId = jobId; - this.installPath = installPath; - this.templateSize = templateSize; - } + public VMTemplateStoragePoolVO(long poolId, long templateId, Date lastUpdated, int downloadPercent, + Status downloadState, String localDownloadPath, String errorString, String jobId, String installPath, + long templateSize) { + super(); + this.poolId = poolId; + this.templateId = templateId; + this.lastUpdated = lastUpdated; + this.downloadPercent = downloadPercent; + this.downloadState = downloadState; + this.localDownloadPath = localDownloadPath; + this.errorString = errorString; + this.jobId = jobId; + this.installPath = installPath; + this.templateSize = templateSize; + } - protected VMTemplateStoragePoolVO() { + protected VMTemplateStoragePoolVO() { - } + } - @Override + @Override public void setLocalDownloadPath(String localPath) { - this.localDownloadPath = localPath; - } + this.localDownloadPath = localPath; + } - @Override + @Override public String getLocalDownloadPath() { - return localDownloadPath; - } + return localDownloadPath; + } - @Override + @Override public void setErrorString(String errorString) { - this.errorString = errorString; - } + this.errorString = errorString; + } - @Override + @Override public String getErrorString() { - return errorString; - } + return errorString; + } - @Override + @Override public void setJobId(String jobId) { - this.jobId = jobId; - } + this.jobId = jobId; + } - @Override + @Override public String getJobId() { - return jobId; - } + return jobId; + } - public void setTemplateSize(long templateSize) { - this.templateSize = templateSize; - } + public void setTemplateSize(long templateSize) { + this.templateSize = templateSize; + } - public boolean getMarkedForGC() { - return markedForGC; - } + public boolean getMarkedForGC() { + return markedForGC; + } - public void setMarkedForGC(boolean markedForGC) { - this.markedForGC = markedForGC; - } + public void setMarkedForGC(boolean markedForGC) { + this.markedForGC = markedForGC; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof VMTemplateStoragePoolVO) { - VMTemplateStoragePoolVO other = (VMTemplateStoragePoolVO)obj; - return (this.templateId==other.getTemplateId() && this.poolId==other.getPoolId()); - } - return false; - } + @Override + public boolean equals(Object obj) { + if (obj instanceof VMTemplateStoragePoolVO) { + VMTemplateStoragePoolVO other = (VMTemplateStoragePoolVO) obj; + return (this.templateId == other.getTemplateId() && this.poolId == other.getPoolId()); + } + return false; + } - @Override - public int hashCode() { - Long tid = new Long(templateId); - Long hid = new Long(poolId); - return tid.hashCode()+hid.hashCode(); - } + @Override + public int hashCode() { + Long tid = new Long(templateId); + Long hid = new Long(poolId); + return tid.hashCode() + hid.hashCode(); + } - @Override + @Override public String toString() { - return new StringBuilder("TmplPool[").append(id).append("-").append(templateId).append("-").append("poolId").append("-").append(installPath).append("]").toString(); - } + return new StringBuilder("TmplPool[").append(id).append("-").append(templateId).append("-").append("poolId") + .append("-").append(installPath).append("]").toString(); + } @Override public State getState() { @@ -286,5 +297,4 @@ public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc, return this.state; } - } diff --git a/engine/schema/src/com/cloud/storage/VMTemplateSwiftVO.java b/engine/schema/src/com/cloud/storage/VMTemplateSwiftVO.java index 6c7a73d3c05..de55fb6622f 100755 --- a/engine/schema/src/com/cloud/storage/VMTemplateSwiftVO.java +++ b/engine/schema/src/com/cloud/storage/VMTemplateSwiftVO.java @@ -101,7 +101,8 @@ public class VMTemplateSwiftVO implements InternalIdentity { @Override public String toString() { - return new StringBuilder("TmplSwift[").append(id).append("-").append(templateId).append("-").append(swiftId).append("]").toString(); + return new StringBuilder("TmplSwift[").append(id).append("-").append(templateId).append("-").append(swiftId) + .append("]").toString(); } } diff --git a/engine/schema/src/com/cloud/storage/VMTemplateVO.java b/engine/schema/src/com/cloud/storage/VMTemplateVO.java index e64c83a8b5b..00c394fa1fa 100755 --- a/engine/schema/src/com/cloud/storage/VMTemplateVO.java +++ b/engine/schema/src/com/cloud/storage/VMTemplateVO.java @@ -41,92 +41,93 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateObject; @Entity -@Table(name="vm_template") +@Table(name = "vm_template") public class VMTemplateVO implements VirtualMachineTemplate, StateObject { @Id - @TableGenerator(name="vm_template_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_template_seq", allocationSize=1) - @Column(name="id", nullable = false) + @TableGenerator(name = "vm_template_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", + pkColumnValue = "vm_template_seq", allocationSize = 1) + @Column(name = "id", nullable = false) private long id; - @Column(name="format") + @Column(name = "format") private Storage.ImageFormat format; - @Column(name="unique_name") + @Column(name = "unique_name") private String uniqueName; - @Column(name="name") + @Column(name = "name") private String name = null; - @Column(name="public") + @Column(name = "public") private boolean publicTemplate = true; - @Column(name="featured") + @Column(name = "featured") private boolean featured; - @Column(name="type") + @Column(name = "type") private Storage.TemplateType templateType; - @Column(name="url") + @Column(name = "url") private String url = null; - @Column(name="hvm") + @Column(name = "hvm") private boolean requiresHvm; - @Column(name="bits") + @Column(name = "bits") private int bits; - @Temporal(value=TemporalType.TIMESTAMP) - @Column(name=GenericDao.CREATED_COLUMN) + @Temporal(value = TemporalType.TIMESTAMP) + @Column(name = GenericDao.CREATED_COLUMN) private Date created = null; - @Column(name=GenericDao.REMOVED) + @Column(name = GenericDao.REMOVED) @Temporal(TemporalType.TIMESTAMP) private Date removed; - @Column(name="account_id") + @Column(name = "account_id") private long accountId; - @Column(name="checksum") + @Column(name = "checksum") private String checksum; - @Column(name="display_text", length=4096) + @Column(name = "display_text", length = 4096) private String displayText; - @Column(name="enable_password") + @Column(name = "enable_password") private boolean enablePassword; - @Column(name="guest_os_id") + @Column(name = "guest_os_id") private long guestOSId; - @Column(name="bootable") + @Column(name = "bootable") private boolean bootable = true; - @Column(name="prepopulate") + @Column(name = "prepopulate") private boolean prepopulate = false; - @Column(name="cross_zones") + @Column(name = "cross_zones") private boolean crossZones = false; - @Column(name="hypervisor_type") - @Enumerated(value=EnumType.STRING) + @Column(name = "hypervisor_type") + @Enumerated(value = EnumType.STRING) private HypervisorType hypervisorType; - @Column(name="extractable") + @Column(name = "extractable") private boolean extractable = true; - @Column(name="source_template_id") + @Column(name = "source_template_id") private Long sourceTemplateId; - @Column(name="template_tag") + @Column(name = "template_tag") private String templateTag; - @Column(name="uuid") + @Column(name = "uuid") private String uuid; - @Column(name="sort_key") + @Column(name = "sort_key") private int sortKey; - @Column(name="enable_sshkey") + @Column(name = "enable_sshkey") private boolean enableSshKey; @Column(name = "size") @@ -135,7 +136,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, StateObject { List listByDomainId(long domainId); + List findPrivateDiskOffering(); - List findPublicDiskOfferings(); + + List findPublicDiskOfferings(); + DiskOfferingVO findByUniqueName(String uniqueName); + DiskOfferingVO persistDeafultDiskOffering(DiskOfferingVO offering); - + } diff --git a/engine/schema/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java index 1f68c5082ff..0c77a8a8600 100644 --- a/engine/schema/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/DiskOfferingDaoImpl.java @@ -22,7 +22,6 @@ import java.util.List; import javax.ejb.Local; import javax.persistence.EntityExistsException; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.storage.DiskOfferingVO; @@ -35,10 +34,8 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; @Component -@Local(value={DiskOfferingDao.class}) +@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; @@ -46,25 +43,27 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im private final Attribute _typeAttr; protected DiskOfferingDaoImpl() { - DomainIdSearch = createSearchBuilder(); + DomainIdSearch = createSearchBuilder(); DomainIdSearch.and("domainId", DomainIdSearch.entity().getDomainId(), SearchCriteria.Op.EQ); DomainIdSearch.and("removed", DomainIdSearch.entity().getRemoved(), SearchCriteria.Op.NULL); DomainIdSearch.done(); - - PrivateDiskOfferingSearch = createSearchBuilder(); - PrivateDiskOfferingSearch.and("diskSize", PrivateDiskOfferingSearch.entity().getDiskSize(), SearchCriteria.Op.EQ); + + PrivateDiskOfferingSearch = createSearchBuilder(); + PrivateDiskOfferingSearch.and("diskSize", PrivateDiskOfferingSearch.entity().getDiskSize(), + SearchCriteria.Op.EQ); PrivateDiskOfferingSearch.done(); - + PublicDiskOfferingSearch = createSearchBuilder(); - PublicDiskOfferingSearch.and("domainId", PublicDiskOfferingSearch.entity().getDomainId(), SearchCriteria.Op.NULL); + PublicDiskOfferingSearch.and("domainId", PublicDiskOfferingSearch.entity().getDomainId(), + SearchCriteria.Op.NULL); PublicDiskOfferingSearch.and("system", PublicDiskOfferingSearch.entity().getSystemUse(), SearchCriteria.Op.EQ); PublicDiskOfferingSearch.and("removed", PublicDiskOfferingSearch.entity().getRemoved(), SearchCriteria.Op.NULL); PublicDiskOfferingSearch.done(); - + UniqueNameSearch = createSearchBuilder(); UniqueNameSearch.and("name", UniqueNameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ); UniqueNameSearch.done(); - + _typeAttr = _allAttributes.get("type"); } @@ -72,29 +71,31 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im 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 + // FIXME: this should not be exact match, but instead should find all + // available disk offerings from parent domains return listBy(sc); } - + @Override public List findPrivateDiskOffering() { SearchCriteria sc = PrivateDiskOfferingSearch.create(); sc.setParameters("diskSize", 0); return listBy(sc); } - + @Override - public List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache) { + public List searchIncludingRemoved(SearchCriteria sc, final Filter filter, + final Boolean lock, final boolean cache) { sc.addAnd(_typeAttr, Op.EQ, Type.Disk); return super.searchIncludingRemoved(sc, filter, lock, cache); } - + @Override public List customSearchIncludingRemoved(SearchCriteria sc, final Filter filter) { sc.addAnd(_typeAttr, Op.EQ, Type.Disk); return super.customSearchIncludingRemoved(sc, filter); } - + @Override protected List executeList(final String sql, final Object... params) { StringBuilder builder = new StringBuilder(sql); @@ -104,17 +105,17 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im } else { builder.insert(index + 6, "type=? "); } - + return super.executeList(sql, Type.Disk, params); } - + @Override - public List findPublicDiskOfferings(){ - SearchCriteria sc = PublicDiskOfferingSearch.create(); - sc.setParameters("system", false); - return listBy(sc); + public List findPublicDiskOfferings() { + SearchCriteria sc = PublicDiskOfferingSearch.create(); + sc.setParameters("system", false); + return listBy(sc); } - + @Override public DiskOfferingVO findByUniqueName(String uniqueName) { SearchCriteria sc = UniqueNameSearch.create(); @@ -123,10 +124,10 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im if (vos.size() == 0) { return null; } - + return vos.get(0); } - + @Override public DiskOfferingVO persistDeafultDiskOffering(DiskOfferingVO offering) { assert offering.getUniqueName() != null : "unique name shouldn't be null for the disk offering"; @@ -141,7 +142,7 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im return findByUniqueName(offering.getUniqueName()); } } - + @Override public boolean remove(Long id) { DiskOfferingVO diskOffering = createForUpdate(); diff --git a/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDao.java b/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDao.java index 0f7ea327f15..61fec36d526 100644 --- a/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDao.java +++ b/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDao.java @@ -20,5 +20,5 @@ import com.cloud.storage.GuestOSCategoryVO; import com.cloud.utils.db.GenericDao; public interface GuestOSCategoryDao extends GenericDao { - + } diff --git a/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDaoImpl.java index d017b996d5d..0637ecbf4ff 100644 --- a/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/GuestOSCategoryDaoImpl.java @@ -24,11 +24,11 @@ import com.cloud.storage.GuestOSCategoryVO; import com.cloud.utils.db.GenericDaoBase; @Component -@Local (value={GuestOSCategoryDao.class}) +@Local(value = { GuestOSCategoryDao.class }) public class GuestOSCategoryDaoImpl extends GenericDaoBase implements GuestOSCategoryDao { - - protected GuestOSCategoryDaoImpl() { - } - + protected GuestOSCategoryDaoImpl() { + + } + } diff --git a/engine/schema/src/com/cloud/storage/dao/GuestOSDao.java b/engine/schema/src/com/cloud/storage/dao/GuestOSDao.java index 19e423bfefd..a9d0cdb8279 100755 --- a/engine/schema/src/com/cloud/storage/dao/GuestOSDao.java +++ b/engine/schema/src/com/cloud/storage/dao/GuestOSDao.java @@ -22,5 +22,5 @@ import com.cloud.utils.db.GenericDao; public interface GuestOSDao extends GenericDao { GuestOSVO listByDisplayName(String displayName); - + } diff --git a/engine/schema/src/com/cloud/storage/dao/GuestOSDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/GuestOSDaoImpl.java index c39fae8ea8d..618578524c6 100755 --- a/engine/schema/src/com/cloud/storage/dao/GuestOSDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/GuestOSDaoImpl.java @@ -16,32 +16,28 @@ // under the License. package com.cloud.storage.dao; -import java.util.List; - import javax.ejb.Local; import org.springframework.stereotype.Component; import com.cloud.storage.GuestOSVO; -import com.cloud.storage.VMTemplateHostVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @Component -@Local (value={GuestOSDao.class}) +@Local(value = { GuestOSDao.class }) public class GuestOSDaoImpl extends GenericDaoBase implements GuestOSDao { - - + protected final SearchBuilder Search; - - protected GuestOSDaoImpl() { + + protected GuestOSDaoImpl() { Search = createSearchBuilder(); Search.and("display_name", Search.entity().getDisplayName(), SearchCriteria.Op.EQ); Search.done(); - } - - @Override + } + + @Override public GuestOSVO listByDisplayName(String displayName) { SearchCriteria sc = Search.create(); sc.setParameters("display_name", displayName); diff --git a/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDao.java b/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDao.java index 0ad60b50ee8..146e180fd07 100644 --- a/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDao.java +++ b/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDao.java @@ -18,42 +18,54 @@ 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 + * 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 + * + * @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 + * + * @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 + * List all templates for which permission to launch instances has been + * granted to the given account + * * @param accountId * @return */ diff --git a/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java index 286b1d9ce3f..3e32f1a9529 100644 --- a/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/LaunchPermissionDaoImpl.java @@ -39,26 +39,27 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @Component -@Local(value={LaunchPermissionDao.class}) +@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 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 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.and("templateId", TemplateAndAccountSearch.entity().getTemplateId(), + SearchCriteria.Op.EQ); + TemplateAndAccountSearch.and("accountId", TemplateAndAccountSearch.entity().getAccountId(), + SearchCriteria.Op.EQ); TemplateAndAccountSearch.done(); TemplateIdSearch = createSearchBuilder(); @@ -138,9 +139,13 @@ public class LaunchPermissionDaoImpl extends GenericDaoBase implements S3Dao { } - // NOTE: Excluded listAll / shuffle operation implemented in SwiftDaoImpl ... + // NOTE: Excluded listAll / shuffle operation implemented in + // SwiftDaoImpl ... return null; diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java b/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java index 46f2fa9396b..a58902121cc 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java @@ -27,24 +27,40 @@ import com.cloud.utils.fsm.StateDao; import java.util.List; public interface SnapshotDao extends GenericDao, StateDao { - List listByVolumeId(long volumeId); - List listByVolumeId(Filter filter, long volumeId); - SnapshotVO findNextSnapshot(long parentSnapId); - long getLastSnapshot(long volumeId, DataStoreRole role); + List listByVolumeId(long volumeId); + + List listByVolumeId(Filter filter, long volumeId); + + SnapshotVO findNextSnapshot(long parentSnapId); + + long getLastSnapshot(long volumeId, DataStoreRole role); + List listByVolumeIdType(long volumeId, Type type); + List listByVolumeIdIncludingRemoved(long volumeId); + List listByBackupUuid(long volumeId, String backupUuid); + long updateSnapshotVersion(long volumeId, String from, String to); + List listByVolumeIdVersion(long volumeId, String version); + Long getSecHostId(long volumeId); + long updateSnapshotSecHost(long dcId, long secHostId); + public Long countSnapshotsForAccount(long accountId); + List listByInstanceId(long instanceId, Snapshot.State... status); + List listByStatus(long volumeId, Snapshot.State... status); + List listAllByStatus(Snapshot.State... status); + /** - * Gets the Total Secondary Storage space (in bytes) used by snapshots allocated for an account - * + * Gets the Total Secondary Storage space (in bytes) used by snapshots + * allocated for an account + * * @param account * @return total Secondary Storage space allocated */ diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java index a3493890a59..f5319ea120a 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java @@ -52,10 +52,10 @@ import com.cloud.vm.VMInstanceVO; import com.cloud.vm.dao.VMInstanceDao; @Component -@Local (value={SnapshotDao.class}) +@Local(value = { SnapshotDao.class }) public class SnapshotDaoImpl extends GenericDaoBase implements SnapshotDao { public static final Logger s_logger = Logger.getLogger(SnapshotDaoImpl.class.getName()); - //TODO: we should remove these direct sqls + // TODO: we should remove these direct sqls private static final String GET_LAST_SNAPSHOT = "SELECT snapshots.id FROM snapshot_store_ref, snapshots where snapshots.id = snapshot_store_ref.snapshot_id AND snapshosts.volume_id = ? AND snapshot_store_ref.role = ? ORDER BY created DESC"; private static final String UPDATE_SNAPSHOT_VERSION = "UPDATE snapshots SET version = ? WHERE volume_id = ? AND version = ?"; private static final String GET_SECHOST_ID = "SELECT store_id FROM snapshots, snapshot_store_ref where snapshots.id = snapshot_store_ref.snapshot_id AND volume_id = ? AND backup_snap_id IS NOT NULL AND sechost_id IS NOT NULL LIMIT 1"; @@ -71,9 +71,12 @@ public class SnapshotDaoImpl extends GenericDaoBase implements private SearchBuilder StatusSearch; private GenericSearchBuilder CountSnapshotsByAccount; private GenericSearchBuilder secondaryStorageSearch; - @Inject ResourceTagDao _tagsDao; - @Inject protected VMInstanceDao _instanceDao; - @Inject protected VolumeDao _volumeDao; + @Inject + ResourceTagDao _tagsDao; + @Inject + protected VMInstanceDao _instanceDao; + @Inject + protected VolumeDao _volumeDao; @Override public SnapshotVO findNextSnapshot(long snapshotId) { @@ -83,20 +86,19 @@ public class SnapshotDaoImpl extends GenericDaoBase implements } @Override - public List listByBackupUuid(long volumeId, String backupUuid) { + public List listByBackupUuid(long volumeId, String backupUuid) { SearchCriteria sc = backupUuidSearch.create(); sc.setParameters("backupUuid", backupUuid); return listBy(sc, null); } @Override - public List listByVolumeIdType(long volumeId, Type type ) { + public List listByVolumeIdType(long volumeId, Type type) { return listByVolumeIdType(null, volumeId, type); } - @Override - public List listByVolumeIdVersion(long volumeId, String version ) { + public List listByVolumeIdVersion(long volumeId, String version) { return listByVolumeIdVersion(null, volumeId, version); } @@ -106,27 +108,27 @@ public class SnapshotDaoImpl extends GenericDaoBase implements } @Override - public List listByVolumeId(Filter filter, long volumeId ) { + public List listByVolumeId(Filter filter, long volumeId) { SearchCriteria sc = VolumeIdSearch.create(); sc.setParameters("volumeId", volumeId); return listBy(sc, filter); } - @Override + @Override public List listByVolumeIdIncludingRemoved(long volumeId) { SearchCriteria sc = VolumeIdSearch.create(); sc.setParameters("volumeId", volumeId); return listIncludingRemovedBy(sc, null); } - public List listByVolumeIdType(Filter filter, long volumeId, Type type ) { + public List listByVolumeIdType(Filter filter, long volumeId, Type type) { SearchCriteria sc = VolumeIdTypeSearch.create(); sc.setParameters("volumeId", volumeId); sc.setParameters("type", type.ordinal()); return listBy(sc, filter); } - public List listByVolumeIdVersion(Filter filter, long volumeId, String version ) { + public List listByVolumeIdVersion(Filter filter, long volumeId, String version) { SearchCriteria sc = VolumeIdVersionSearch.create(); sc.setParameters("volumeId", volumeId); sc.setParameters("version", version); @@ -151,15 +153,17 @@ public class SnapshotDaoImpl extends GenericDaoBase implements VolumeIdVersionSearch.and("volumeId", VolumeIdVersionSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); VolumeIdVersionSearch.and("version", VolumeIdVersionSearch.entity().getVersion(), SearchCriteria.Op.EQ); VolumeIdVersionSearch.done(); -/* - ParentIdSearch = createSearchBuilder(); - ParentIdSearch.and("prevSnapshotId", ParentIdSearch.entity().getPrevSnapshotId(), SearchCriteria.Op.EQ); - ParentIdSearch.done(); - - backupUuidSearch = createSearchBuilder(); - backupUuidSearch.and("backupUuid", backupUuidSearch.entity().getBackupSnapshotId(), SearchCriteria.Op.EQ); - backupUuidSearch.done(); -*/ + /* + * ParentIdSearch = createSearchBuilder(); + * ParentIdSearch.and("prevSnapshotId", + * ParentIdSearch.entity().getPrevSnapshotId(), SearchCriteria.Op.EQ); + * ParentIdSearch.done(); + * + * backupUuidSearch = createSearchBuilder(); + * backupUuidSearch.and("backupUuid", + * backupUuidSearch.entity().getBackupSnapshotId(), + * SearchCriteria.Op.EQ); backupUuidSearch.done(); + */ AccountIdSearch = createSearchBuilder(); AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountIdSearch.done(); @@ -183,9 +187,11 @@ public class SnapshotDaoImpl extends GenericDaoBase implements SearchBuilder volumeSearch = _volumeDao.createSearchBuilder(); volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ); - volumeSearch.join("instanceVolumes", instanceSearch, instanceSearch.entity().getId(), volumeSearch.entity().getInstanceId(), JoinType.INNER); + volumeSearch.join("instanceVolumes", instanceSearch, instanceSearch.entity().getId(), volumeSearch.entity() + .getInstanceId(), JoinType.INNER); - InstanceIdSearch.join("instanceSnapshots", volumeSearch, volumeSearch.entity().getId(), InstanceIdSearch.entity().getVolumeId(), JoinType.INNER); + InstanceIdSearch.join("instanceSnapshots", volumeSearch, volumeSearch.entity().getId(), InstanceIdSearch + .entity().getVolumeId(), JoinType.INNER); InstanceIdSearch.done(); secondaryStorageSearch = createSearchBuilder(SumCount.class); @@ -212,6 +218,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements } return null; } + @Override public long getLastSnapshot(long volumeId, DataStoreRole role) { Transaction txn = Transaction.currentTxn(); @@ -268,30 +275,30 @@ public class SnapshotDaoImpl extends GenericDaoBase implements @Override public Long countSnapshotsForAccount(long accountId) { - SearchCriteria sc = CountSnapshotsByAccount.create(); + SearchCriteria sc = CountSnapshotsByAccount.create(); sc.setParameters("account", accountId); return customSearch(sc, null).get(0); } @Override - public List listByInstanceId(long instanceId, Snapshot.State... status) { - SearchCriteria sc = this.InstanceIdSearch.create(); + public List listByInstanceId(long instanceId, Snapshot.State... status) { + SearchCriteria sc = this.InstanceIdSearch.create(); - if (status != null && status.length != 0) { - sc.setParameters("status", (Object[])status); - } + if (status != null && status.length != 0) { + sc.setParameters("status", (Object[]) status); + } - sc.setJoinParameters("instanceSnapshots", "state", Volume.State.Ready); - sc.setJoinParameters("instanceVolumes", "instanceId", instanceId); + sc.setJoinParameters("instanceSnapshots", "state", Volume.State.Ready); + sc.setJoinParameters("instanceVolumes", "instanceId", instanceId); return listBy(sc, null); } @Override public List listByStatus(long volumeId, Snapshot.State... status) { - SearchCriteria sc = this.StatusSearch.create(); - sc.setParameters("volumeId", volumeId); - sc.setParameters("status", (Object[])status); - return listBy(sc, null); + SearchCriteria sc = this.StatusSearch.create(); + sc.setParameters("volumeId", volumeId); + sc.setParameters("status", (Object[]) status); + return listBy(sc, null); } @Override @@ -311,7 +318,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements @Override public List listAllByStatus(Snapshot.State... status) { SearchCriteria sc = this.StatusSearch.create(); - sc.setParameters("status", (Object[])status); + sc.setParameters("status", (Object[]) status); return listBy(sc, null); } @@ -319,7 +326,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements public boolean updateState(State currentState, Event event, State nextState, SnapshotVO snapshot, Object data) { Transaction txn = Transaction.currentTxn(); txn.start(); - SnapshotVO snapshotVO = (SnapshotVO)snapshot; + SnapshotVO snapshotVO = (SnapshotVO) snapshot; snapshotVO.setState(nextState); super.update(snapshotVO.getId(), snapshotVO); txn.commit(); diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDao.java b/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDao.java index 467d491d779..f65b5839f75 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDao.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDao.java @@ -28,11 +28,17 @@ 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); + List listByVolumeId(long volumeId); + + List listByVolumeId(long volumeId, Filter filter); + Pair, Integer> listAndCountByVolumeId(long volumeId); + Pair, Integer> listAndCountByVolumeId(long volumeId, Filter filter); - SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType); + + SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType); + List listActivePolicies(); + SnapshotPolicyVO findOneByVolume(long volumeId); } diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java index 3f894a22640..662ad4354a4 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.storage.dao; - import java.util.List; import javax.ejb.Local; @@ -32,33 +31,33 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @Component -@Local (value={SnapshotPolicyDao.class}) +@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(); + 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); - } - - @Override + return findOneBy(sc); + } + + @Override public SnapshotPolicyVO findOneByVolume(long volumeId) { SearchCriteria sc = VolumeIdSearch.create(); sc.setParameters("volumeId", volumeId); sc.setParameters("active", true); return findOneBy(sc); } - - @Override - public List listByVolumeId(long volumeId) { - return listByVolumeId(volumeId, null); - } - + + @Override + public List listByVolumeId(long volumeId) { + return listByVolumeId(volumeId, null); + } + @Override public List listByVolumeId(long volumeId, Filter filter) { SearchCriteria sc = VolumeIdSearch.create(); @@ -66,7 +65,7 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase, Integer> listAndCountByVolumeId(long volumeId) { return listAndCountByVolumeId(volumeId, null); @@ -85,12 +84,12 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase sc = ActivePolicySearch.create(); sc.setParameters("active", true); return listIncludingRemovedBy(sc); - } + } } \ No newline at end of file diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDao.java b/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDao.java index 0419e2836a0..7ca0a3915f5 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDao.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDao.java @@ -16,10 +16,9 @@ // under the License. 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; @@ -28,7 +27,7 @@ import com.cloud.utils.db.GenericDao; */ public interface SnapshotScheduleDao extends GenericDao { - List getCoincidingSnapshotSchedules(long volumeId, Date date); + List getCoincidingSnapshotSchedules(long volumeId, Date date); List getSchedulesToExecute(Date currentTimestamp); diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java index c01644e0918..72d47fa4dcc 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java @@ -30,60 +30,63 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @Component -@Local (value={SnapshotScheduleDao.class}) +@Local(value = { SnapshotScheduleDao.class }) public class SnapshotScheduleDaoImpl extends GenericDaoBase implements SnapshotScheduleDao { - protected final SearchBuilder executableSchedulesSearch; - protected final SearchBuilder coincidingSchedulesSearch; + protected final SearchBuilder executableSchedulesSearch; + protected final SearchBuilder coincidingSchedulesSearch; private final SearchBuilder VolumeIdSearch; private final SearchBuilder VolumeIdPolicyIdSearch; - - - protected SnapshotScheduleDaoImpl() { - - executableSchedulesSearch = createSearchBuilder(); - executableSchedulesSearch.and("scheduledTimestamp", executableSchedulesSearch.entity().getScheduledTimestamp(), SearchCriteria.Op.LT); - executableSchedulesSearch.and("asyncJobId", executableSchedulesSearch.entity().getAsyncJobId(), SearchCriteria.Op.NULL); + + protected SnapshotScheduleDaoImpl() { + + executableSchedulesSearch = createSearchBuilder(); + executableSchedulesSearch.and("scheduledTimestamp", executableSchedulesSearch.entity().getScheduledTimestamp(), + SearchCriteria.Op.LT); + executableSchedulesSearch.and("asyncJobId", executableSchedulesSearch.entity().getAsyncJobId(), + SearchCriteria.Op.NULL); executableSchedulesSearch.done(); - + coincidingSchedulesSearch = createSearchBuilder(); - coincidingSchedulesSearch.and("volumeId", coincidingSchedulesSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); - coincidingSchedulesSearch.and("scheduledTimestamp", coincidingSchedulesSearch.entity().getScheduledTimestamp(), SearchCriteria.Op.LT); - coincidingSchedulesSearch.and("asyncJobId", coincidingSchedulesSearch.entity().getAsyncJobId(), SearchCriteria.Op.NULL); + coincidingSchedulesSearch.and("volumeId", coincidingSchedulesSearch.entity().getVolumeId(), + SearchCriteria.Op.EQ); + coincidingSchedulesSearch.and("scheduledTimestamp", coincidingSchedulesSearch.entity().getScheduledTimestamp(), + SearchCriteria.Op.LT); + coincidingSchedulesSearch.and("asyncJobId", coincidingSchedulesSearch.entity().getAsyncJobId(), + SearchCriteria.Op.NULL); coincidingSchedulesSearch.done(); - + VolumeIdSearch = createSearchBuilder(); VolumeIdSearch.and("volumeId", VolumeIdSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); VolumeIdSearch.done(); - + VolumeIdPolicyIdSearch = createSearchBuilder(); VolumeIdPolicyIdSearch.and("volumeId", VolumeIdPolicyIdSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); VolumeIdPolicyIdSearch.and("policyId", VolumeIdPolicyIdSearch.entity().getPolicyId(), SearchCriteria.Op.EQ); VolumeIdPolicyIdSearch.done(); - - } - - /** - * {@inheritDoc} - */ - @Override - public List getCoincidingSnapshotSchedules(long volumeId, Date date) { - SearchCriteria sc = coincidingSchedulesSearch.create(); - sc.setParameters("volumeId", volumeId); - sc.setParameters("scheduledTimestamp", date); - // Don't return manual snapshots. They will be executed through another code path. + + } + + /** + * {@inheritDoc} + */ + @Override + public List getCoincidingSnapshotSchedules(long volumeId, Date date) { + SearchCriteria sc = coincidingSchedulesSearch.create(); + sc.setParameters("volumeId", volumeId); + sc.setParameters("scheduledTimestamp", date); + // Don't return manual snapshots. They will be executed through another + // code path. sc.addAnd("policyId", SearchCriteria.Op.NEQ, 1L); return listBy(sc); - } + } - @Override public SnapshotScheduleVO findOneByVolume(long volumeId) { SearchCriteria sc = VolumeIdSearch.create(); sc.setParameters("volumeId", volumeId); return findOneBy(sc); } - - + @Override public SnapshotScheduleVO findOneByVolumePolicy(long volumeId, long policyId) { SearchCriteria sc = VolumeIdPolicyIdSearch.create(); @@ -91,8 +94,9 @@ public class SnapshotScheduleDaoImpl extends GenericDaoBase getSchedulesToExecute(Date currentTimestamp) { @@ -100,9 +104,9 @@ public class SnapshotScheduleDaoImpl extends GenericDaoBase snapshotSchedules = listBy(sc); - // This will return only one schedule because of a DB uniqueness constraint. + // This will return only one schedule because of a DB uniqueness + // constraint. assert (snapshotSchedules.size() <= 1); if (snapshotSchedules.isEmpty()) { return null; - } - else { + } else { return snapshotSchedules.get(0); } } - + } \ No newline at end of file diff --git a/engine/schema/src/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java index 38b525330f2..8952e6cb154 100644 --- a/engine/schema/src/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java @@ -32,11 +32,12 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @Component -@Local(value=StoragePoolDetailsDao.class) -public class StoragePoolDetailsDaoImpl extends GenericDaoBase implements StoragePoolDetailsDao { - +@Local(value = StoragePoolDetailsDao.class) +public class StoragePoolDetailsDaoImpl extends GenericDaoBase implements + StoragePoolDetailsDao { + protected final SearchBuilder PoolSearch; - + protected StoragePoolDetailsDaoImpl() { super(); PoolSearch = createSearchBuilder(); @@ -44,13 +45,13 @@ public class StoragePoolDetailsDaoImpl extends GenericDaoBase details) { Transaction txn = Transaction.currentTxn(); SearchCriteria sc = PoolSearch.create(); sc.setParameters("pool", poolId); - + txn.start(); expunge(sc); for (Map.Entry entry : details.entrySet()) { @@ -59,19 +60,19 @@ public class StoragePoolDetailsDaoImpl extends GenericDaoBase getDetails(long poolId) { - SearchCriteria sc = PoolSearch.create(); - sc.setParameters("pool", poolId); - - List details = listBy(sc); - Map detailsMap = new HashMap(); - for (StoragePoolDetailVO detail : details) { - detailsMap.put(detail.getName(), detail.getValue()); - } - - return detailsMap; + SearchCriteria sc = PoolSearch.create(); + sc.setParameters("pool", poolId); + + List details = listBy(sc); + Map detailsMap = new HashMap(); + for (StoragePoolDetailVO detail : details) { + detailsMap.put(detail.getName(), detail.getValue()); + } + + return detailsMap; } @Override diff --git a/engine/schema/src/com/cloud/storage/dao/StoragePoolHostDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/StoragePoolHostDaoImpl.java index 4f509d14041..730216b82b0 100644 --- a/engine/schema/src/com/cloud/storage/dao/StoragePoolHostDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/StoragePoolHostDaoImpl.java @@ -46,13 +46,16 @@ public class StoragePoolHostDaoImpl extends GenericDaoBase listByHostId(long hostId) { SearchCriteria sc = HostSearch.create(); @@ -113,7 +116,8 @@ public class StoragePoolHostDaoImpl extends GenericDaoBase void removePendingJobsOnMsRestart(long msId, long poolId); List searchForPoolIdsForPendingWorkJobs(long msId); - + } diff --git a/engine/schema/src/com/cloud/storage/dao/StoragePoolWorkDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/StoragePoolWorkDaoImpl.java index 360a814f59a..052bae4fc78 100644 --- a/engine/schema/src/com/cloud/storage/dao/StoragePoolWorkDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/StoragePoolWorkDaoImpl.java @@ -35,43 +35,53 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @Component -@Local(value={StoragePoolWorkDao.class}) @DB(txn=false) -public class StoragePoolWorkDaoImpl extends GenericDaoBase implements StoragePoolWorkDao { +@Local(value = { StoragePoolWorkDao.class }) +@DB(txn = false) +public class StoragePoolWorkDaoImpl extends GenericDaoBase implements StoragePoolWorkDao { protected final SearchBuilder PendingWorkForPrepareForMaintenanceSearch; protected final SearchBuilder PendingWorkForCancelMaintenanceSearch; protected final SearchBuilder PoolAndVmIdSearch; protected final SearchBuilder PendingJobsForDeadMs; - + private final String FindPoolIds = "SELECT distinct storage_pool_work.pool_id FROM storage_pool_work WHERE mgmt_server_id = ?"; - + protected StoragePoolWorkDaoImpl() { PendingWorkForPrepareForMaintenanceSearch = createSearchBuilder(); - PendingWorkForPrepareForMaintenanceSearch.and("poolId", PendingWorkForPrepareForMaintenanceSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - PendingWorkForPrepareForMaintenanceSearch.and("stoppedForMaintenance", PendingWorkForPrepareForMaintenanceSearch.entity().isStoppedForMaintenance(), SearchCriteria.Op.EQ); - PendingWorkForPrepareForMaintenanceSearch.and("startedAfterMaintenance", PendingWorkForPrepareForMaintenanceSearch.entity().isStartedAfterMaintenance(), SearchCriteria.Op.EQ); + PendingWorkForPrepareForMaintenanceSearch.and("poolId", PendingWorkForPrepareForMaintenanceSearch.entity() + .getPoolId(), SearchCriteria.Op.EQ); + PendingWorkForPrepareForMaintenanceSearch.and("stoppedForMaintenance", + PendingWorkForPrepareForMaintenanceSearch.entity().isStoppedForMaintenance(), SearchCriteria.Op.EQ); + PendingWorkForPrepareForMaintenanceSearch.and("startedAfterMaintenance", + PendingWorkForPrepareForMaintenanceSearch.entity().isStartedAfterMaintenance(), SearchCriteria.Op.EQ); PendingWorkForPrepareForMaintenanceSearch.done(); - + PendingWorkForCancelMaintenanceSearch = createSearchBuilder(); - PendingWorkForCancelMaintenanceSearch.and("poolId", PendingWorkForCancelMaintenanceSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - PendingWorkForCancelMaintenanceSearch.and("stoppedForMaintenance", PendingWorkForCancelMaintenanceSearch.entity().isStoppedForMaintenance(), SearchCriteria.Op.EQ); - PendingWorkForCancelMaintenanceSearch.and("startedAfterMaintenance", PendingWorkForCancelMaintenanceSearch.entity().isStartedAfterMaintenance(), SearchCriteria.Op.EQ); + PendingWorkForCancelMaintenanceSearch.and("poolId", PendingWorkForCancelMaintenanceSearch.entity().getPoolId(), + SearchCriteria.Op.EQ); + PendingWorkForCancelMaintenanceSearch.and("stoppedForMaintenance", PendingWorkForCancelMaintenanceSearch + .entity().isStoppedForMaintenance(), SearchCriteria.Op.EQ); + PendingWorkForCancelMaintenanceSearch.and("startedAfterMaintenance", PendingWorkForCancelMaintenanceSearch + .entity().isStartedAfterMaintenance(), SearchCriteria.Op.EQ); PendingWorkForCancelMaintenanceSearch.done(); PoolAndVmIdSearch = createSearchBuilder(); PoolAndVmIdSearch.and("poolId", PoolAndVmIdSearch.entity().getPoolId(), SearchCriteria.Op.EQ); PoolAndVmIdSearch.and("vmId", PoolAndVmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); PoolAndVmIdSearch.done(); - + PendingJobsForDeadMs = createSearchBuilder(); - PendingJobsForDeadMs.and("managementServerId", PendingJobsForDeadMs.entity().getManagementServerId(), SearchCriteria.Op.EQ); + PendingJobsForDeadMs.and("managementServerId", PendingJobsForDeadMs.entity().getManagementServerId(), + SearchCriteria.Op.EQ); PendingJobsForDeadMs.and("poolId", PendingJobsForDeadMs.entity().getPoolId(), SearchCriteria.Op.EQ); - PendingJobsForDeadMs.and("stoppedForMaintenance", PendingJobsForDeadMs.entity().isStoppedForMaintenance(), SearchCriteria.Op.EQ); - PendingJobsForDeadMs.and("startedAfterMaintenance", PendingJobsForDeadMs.entity().isStartedAfterMaintenance(), SearchCriteria.Op.EQ); + PendingJobsForDeadMs.and("stoppedForMaintenance", PendingJobsForDeadMs.entity().isStoppedForMaintenance(), + SearchCriteria.Op.EQ); + PendingJobsForDeadMs.and("startedAfterMaintenance", PendingJobsForDeadMs.entity().isStartedAfterMaintenance(), + SearchCriteria.Op.EQ); PendingJobsForDeadMs.done(); - + } - + @Override public List listPendingWorkForPrepareForMaintenanceByPoolId(long poolId) { SearchCriteria sc = PendingWorkForPrepareForMaintenanceSearch.create(); @@ -80,7 +90,7 @@ public class StoragePoolWorkDaoImpl extends GenericDaoBase listPendingWorkForCancelMaintenanceByPoolId(long poolId) { SearchCriteria sc = PendingWorkForCancelMaintenanceSearch.create(); @@ -89,7 +99,7 @@ public class StoragePoolWorkDaoImpl extends GenericDaoBase sc = PoolAndVmIdSearch.create(); @@ -97,22 +107,22 @@ public class StoragePoolWorkDaoImpl extends GenericDaoBase sc = PendingJobsForDeadMs.create(); sc.setParameters("managementServerId", msId); sc.setParameters("poolId", poolId); sc.setParameters("stoppedForMaintenance", true); - sc.setParameters("startedAfterMaintenance", false); + sc.setParameters("startedAfterMaintenance", false); remove(sc); } - + @Override @DB - public List searchForPoolIdsForPendingWorkJobs(long msId){ - + public List searchForPoolIdsForPendingWorkJobs(long msId) { + StringBuilder sql = new StringBuilder(FindPoolIds); Transaction txn = Transaction.currentTxn(); @@ -126,7 +136,7 @@ public class StoragePoolWorkDaoImpl extends GenericDaoBase implements SwiftDao { public static final Logger s_logger = Logger.getLogger(SwiftDaoImpl.class.getName()); diff --git a/engine/schema/src/com/cloud/storage/dao/UploadDao.java b/engine/schema/src/com/cloud/storage/dao/UploadDao.java index 06336ae04cc..0defb36ebb5 100755 --- a/engine/schema/src/com/cloud/storage/dao/UploadDao.java +++ b/engine/schema/src/com/cloud/storage/dao/UploadDao.java @@ -24,13 +24,12 @@ import com.cloud.storage.Upload.Type; import com.cloud.storage.Upload.Mode; import com.cloud.utils.db.GenericDao; -public interface UploadDao extends GenericDao { +public interface UploadDao extends GenericDao { - List listByTypeUploadStatus(long typeId, Type type, - Status uploadState); + List listByTypeUploadStatus(long typeId, Type type, Status uploadState); - List listByHostAndUploadStatus(long sserverId, Status uploadInProgress); - - List listByModeAndStatus(Mode mode, Status uploadState); + List listByHostAndUploadStatus(long sserverId, Status uploadInProgress); + + List listByModeAndStatus(Mode mode, Status uploadState); } diff --git a/engine/schema/src/com/cloud/storage/dao/UploadDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/UploadDaoImpl.java index 4c6da393eb3..8e112bff17f 100755 --- a/engine/schema/src/com/cloud/storage/dao/UploadDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/UploadDaoImpl.java @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. package com.cloud.storage.dao; + import java.util.List; import javax.ejb.Local; @@ -29,64 +30,64 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @Component -@Local(value={UploadDao.class}) +@Local(value = { UploadDao.class }) public class UploadDaoImpl extends GenericDaoBase implements UploadDao { - public static final Logger s_logger = Logger.getLogger(UploadDaoImpl.class.getName()); - protected final SearchBuilder typeUploadStatusSearch; - protected final SearchBuilder typeHostAndUploadStatusSearch; - protected final SearchBuilder typeModeAndStatusSearch; - - protected static final String UPDATE_UPLOAD_INFO = - "UPDATE upload SET upload_state = ?, upload_pct= ?, last_updated = ? " - + ", upload_error_str = ?, upload_job_id = ? " - + "WHERE host_id = ? and type_id = ? and type = ?"; - - protected static final String UPLOADS_STATE_DC= - "SELECT * FROM upload t, host h where t.host_id = h.id and h.data_center_id=? " - + " and t.type_id=? and t.upload_state = ?" ; - - - public UploadDaoImpl() { - typeUploadStatusSearch = createSearchBuilder(); - typeUploadStatusSearch.and("type_id", typeUploadStatusSearch.entity().getTypeId(), SearchCriteria.Op.EQ); - typeUploadStatusSearch.and("upload_state", typeUploadStatusSearch.entity().getUploadState(), SearchCriteria.Op.EQ); - typeUploadStatusSearch.and("type", typeUploadStatusSearch.entity().getType(), SearchCriteria.Op.EQ); - typeUploadStatusSearch.done(); - - typeHostAndUploadStatusSearch = createSearchBuilder(); - typeHostAndUploadStatusSearch.and("host_id", typeHostAndUploadStatusSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ); - typeHostAndUploadStatusSearch.and("upload_state", typeHostAndUploadStatusSearch.entity().getUploadState(), SearchCriteria.Op.EQ); - typeHostAndUploadStatusSearch.done(); - - typeModeAndStatusSearch = createSearchBuilder(); - typeModeAndStatusSearch.and("mode", typeModeAndStatusSearch.entity().getMode(), SearchCriteria.Op.EQ); - typeModeAndStatusSearch.and("upload_state", typeModeAndStatusSearch.entity().getUploadState(), SearchCriteria.Op.EQ); - typeModeAndStatusSearch.done(); - - } - - @Override - public List listByTypeUploadStatus(long typeId, UploadVO.Type type, UploadVO.Status uploadState) { - SearchCriteria sc = typeUploadStatusSearch.create(); - sc.setParameters("type_id", typeId); - sc.setParameters("type", type); - sc.setParameters("upload_state", uploadState.toString()); - return listBy(sc); - } - - @Override - public List listByHostAndUploadStatus(long sserverId, Status uploadState){ + public static final Logger s_logger = Logger.getLogger(UploadDaoImpl.class.getName()); + protected final SearchBuilder typeUploadStatusSearch; + protected final SearchBuilder typeHostAndUploadStatusSearch; + protected final SearchBuilder typeModeAndStatusSearch; + + protected static final String UPDATE_UPLOAD_INFO = "UPDATE upload SET upload_state = ?, upload_pct= ?, last_updated = ? " + + ", upload_error_str = ?, upload_job_id = ? " + "WHERE host_id = ? and type_id = ? and type = ?"; + + protected static final String UPLOADS_STATE_DC = "SELECT * FROM upload t, host h where t.host_id = h.id and h.data_center_id=? " + + " and t.type_id=? and t.upload_state = ?"; + + public UploadDaoImpl() { + typeUploadStatusSearch = createSearchBuilder(); + typeUploadStatusSearch.and("type_id", typeUploadStatusSearch.entity().getTypeId(), SearchCriteria.Op.EQ); + typeUploadStatusSearch.and("upload_state", typeUploadStatusSearch.entity().getUploadState(), + SearchCriteria.Op.EQ); + typeUploadStatusSearch.and("type", typeUploadStatusSearch.entity().getType(), SearchCriteria.Op.EQ); + typeUploadStatusSearch.done(); + + typeHostAndUploadStatusSearch = createSearchBuilder(); + typeHostAndUploadStatusSearch.and("host_id", typeHostAndUploadStatusSearch.entity().getDataStoreId(), + SearchCriteria.Op.EQ); + typeHostAndUploadStatusSearch.and("upload_state", typeHostAndUploadStatusSearch.entity().getUploadState(), + SearchCriteria.Op.EQ); + typeHostAndUploadStatusSearch.done(); + + typeModeAndStatusSearch = createSearchBuilder(); + typeModeAndStatusSearch.and("mode", typeModeAndStatusSearch.entity().getMode(), SearchCriteria.Op.EQ); + typeModeAndStatusSearch.and("upload_state", typeModeAndStatusSearch.entity().getUploadState(), + SearchCriteria.Op.EQ); + typeModeAndStatusSearch.done(); + + } + + @Override + public List listByTypeUploadStatus(long typeId, UploadVO.Type type, UploadVO.Status uploadState) { + SearchCriteria sc = typeUploadStatusSearch.create(); + sc.setParameters("type_id", typeId); + sc.setParameters("type", type); + sc.setParameters("upload_state", uploadState.toString()); + return listBy(sc); + } + + @Override + public List listByHostAndUploadStatus(long sserverId, Status uploadState) { SearchCriteria sc = typeHostAndUploadStatusSearch.create(); sc.setParameters("host_id", sserverId); sc.setParameters("upload_state", uploadState.toString()); return listBy(sc); - } - - @Override - public List listByModeAndStatus(Mode mode, Status uploadState){ - SearchCriteria sc = typeModeAndStatusSearch.create(); - sc.setParameters("mode", mode.toString()); - sc.setParameters("upload_state", uploadState.toString()); - return listBy(sc); - } + } + + @Override + public List listByModeAndStatus(Mode mode, Status uploadState) { + SearchCriteria sc = typeModeAndStatusSearch.create(); + sc.setParameters("mode", mode.toString()); + sc.setParameters("upload_state", uploadState.toString()); + return listBy(sc); + } } \ No newline at end of file diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateDao.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateDao.java index b4376fd550e..b80ad3a01bf 100755 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateDao.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateDao.java @@ -30,36 +30,49 @@ import com.cloud.utils.fsm.StateDao; /* * Data Access Object for vm_templates table */ -public interface VMTemplateDao extends GenericDao, StateDao { +public interface VMTemplateDao extends GenericDao, + StateDao { + public List listByPublic(); - public List listByPublic(); - public VMTemplateVO findByName(String templateName); - public VMTemplateVO findByTemplateName(String templateName); + public VMTemplateVO findByName(String templateName); - //public void update(VMTemplateVO template); + public VMTemplateVO findByTemplateName(String templateName); + // public void update(VMTemplateVO template); - public List listAllSystemVMTemplates(); + 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 List listDefaultBuiltinTemplates(); - public long addTemplateToZone(VMTemplateVO tmplt, long zoneId); - public List listAllInZone(long dataCenterId); - public List listAllActive(); + public String getRoutingTemplateUniqueName(); + + public List findIsosByIdAndPath(Long domainId, Long accountId, String path); + + public List listReadyTemplates(); + + public List listByAccountId(long accountId); + + public long addTemplateToZone(VMTemplateVO tmplt, long zoneId); + + public List listAllInZone(long dataCenterId); + + public List listAllActive(); public List listByHypervisorType(List hyperTypes); - public List publicIsoSearch(Boolean bootable, boolean listRemoved, Map tags); - public List userIsoSearch(boolean listRemoved); + + public List publicIsoSearch(Boolean bootable, boolean listRemoved, Map tags); + + public List userIsoSearch(boolean listRemoved); + VMTemplateVO findSystemVMTemplate(long zoneId); + VMTemplateVO findSystemVMTemplate(long zoneId, HypervisorType hType); VMTemplateVO findRoutingTemplate(HypervisorType type, String templateName); + List listPrivateTemplatesByHost(Long hostId); + public Long countTemplatesForAccount(long accountId); List findTemplatesToSyncToS3(); diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateDaoImpl.java index 7bd8b6d88dc..21dd0adce4e 100755 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateDaoImpl.java @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; + import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; @@ -61,7 +62,7 @@ import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; @Component -@Local(value={VMTemplateDao.class}) +@Local(value = { VMTemplateDao.class }) public class VMTemplateDaoImpl extends GenericDaoBase implements VMTemplateDao { private static final Logger s_logger = Logger.getLogger(VMTemplateDaoImpl.class); @@ -71,35 +72,20 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem VMTemplateDetailsDao _templateDetailsDao; @Inject - ConfigurationDao _configDao; + ConfigurationDao _configDao; @Inject - HostDao _hostDao; + HostDao _hostDao; @Inject DomainDao _domainDao; @Inject DataCenterDao _dcDao; - /* TODO: these direct sql should go away with recent QueryService refactoring to handle listTemplatesCmd. Keep here just for - * potential bug reference. - private final String SELECT_TEMPLATE_HOST_REF = "SELECT t.id, h.data_center_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"; - - private final String SELECT_TEMPLATE_ZONE_REF = "SELECT t.id, tzr.zone_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 INNER JOIN template_zone_ref tzr on (t.id = tzr.template_id) "; - - 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"; - - private final String SELECT_TEMPLATE_S3_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"; - */ - - private static final String SELECT_S3_CANDIDATE_TEMPLATES = "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 JOIN template_host_ref r ON t.id=r.template_id JOIN host h ON h.id=r.host_id " + - "WHERE t.hypervisor_type IN (SELECT hypervisor_type FROM host) AND r.download_state = 'DOWNLOADED' AND " + - "r.template_id NOT IN (SELECT template_id FROM template_s3_ref) AND r.destroyed = 0 AND t.type <> 'PERHOST'"; + private static final String SELECT_S3_CANDIDATE_TEMPLATES = "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 JOIN template_host_ref r ON t.id=r.template_id JOIN host h ON h.id=r.host_id " + + "WHERE t.hypervisor_type IN (SELECT hypervisor_type FROM host) AND r.download_state = 'DOWNLOADED' AND " + + "r.template_id NOT IN (SELECT template_id FROM template_s3_ref) AND r.destroyed = 0 AND t.type <> 'PERHOST'"; protected SearchBuilder TemplateNameSearch; protected SearchBuilder UniqueNameSearch; @@ -118,8 +104,8 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem private GenericSearchBuilder CountTemplatesByAccount; private SearchBuilder updateStateSearch; - @Inject ResourceTagDao _tagsDao; - + @Inject + ResourceTagDao _tagsDao; private String routerTmpltName; private String consoleProxyTmpltName; @@ -129,27 +115,27 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem @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); - } - - @Override - public VMTemplateVO findByTemplateName(String templateName) { - SearchCriteria sc = NameSearch.create(); - sc.setParameters("name", templateName); - return findOneIncludingRemovedBy(sc); - } + SearchCriteria sc = PublicSearch.create(); + sc.setParameters("public", 1); + return listBy(sc); + } @Override - public List publicIsoSearch(Boolean bootable, boolean listRemoved, Map tags){ + public VMTemplateVO findByName(String templateName) { + SearchCriteria sc = UniqueNameSearch.create(); + sc.setParameters("uniqueName", templateName); + return findOneIncludingRemovedBy(sc); + } + + @Override + public VMTemplateVO findByTemplateName(String templateName) { + SearchCriteria sc = NameSearch.create(); + sc.setParameters("name", templateName); + return findOneIncludingRemovedBy(sc); + } + + @Override + public List publicIsoSearch(Boolean bootable, boolean listRemoved, Map tags) { SearchBuilder sb = null; if (tags == null || tags.isEmpty()) { @@ -163,30 +149,31 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.EQ); SearchBuilder tagSearch = _tagsDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { + for (int count = 0; count < tags.size(); count++) { tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); tagSearch.cp(); } tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), + JoinBuilder.JoinType.INNER); } SearchCriteria sc = sb.create(); - sc.setParameters("public", 1); - sc.setParameters("format", "ISO"); - sc.setParameters("type", TemplateType.PERHOST.toString()); - if (bootable != null) { - sc.setParameters("bootable", bootable); - } + sc.setParameters("public", 1); + sc.setParameters("format", "ISO"); + sc.setParameters("type", TemplateType.PERHOST.toString()); + if (bootable != null) { + sc.setParameters("bootable", bootable); + } - if (!listRemoved) { - sc.setParameters("removed", (Object)null); - } + if (!listRemoved) { + sc.setParameters("removed", (Object) null); + } - if (tags != null && !tags.isEmpty()) { + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.ISO.toString()); for (String key : tags.keySet()) { @@ -200,7 +187,7 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } @Override - public List userIsoSearch(boolean listRemoved){ + public List userIsoSearch(boolean listRemoved) { SearchBuilder sb = null; sb = UserIsoSearch; @@ -210,25 +197,26 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem sc.setParameters("type", TemplateType.USER.toString()); if (!listRemoved) { - sc.setParameters("removed", (Object)null); + sc.setParameters("removed", (Object) null); } return listBy(sc); } - @Override - public List listAllSystemVMTemplates() { - SearchCriteria sc = tmpltTypeSearch.create(); - sc.setParameters("templateType", Storage.TemplateType.SYSTEM); - Filter filter = new Filter(VMTemplateVO.class, "id", false, null, null); - return listBy(sc, filter); - } + @Override + public List listAllSystemVMTemplates() { + SearchCriteria sc = tmpltTypeSearch.create(); + sc.setParameters("templateType", Storage.TemplateType.SYSTEM); + + Filter filter = new Filter(VMTemplateVO.class, "id", false, null, null); + return listBy(sc, filter); + } @Override public List listPrivateTemplatesByHost(Long hostId) { String sql = "select * from template_host_ref as thr INNER JOIN vm_template as t ON t.id=thr.template_id " - + "where thr.host_id=? and t.public=0 and t.featured=0 and t.type='USER' and t.removed is NULL"; + + "where thr.host_id=? and t.public=0 and t.featured=0 and t.type='USER' and t.removed is NULL"; List l = new ArrayList(); @@ -248,136 +236,138 @@ 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 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) { + @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) { + if (accountId != null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } - if (path != null) { + if (path != null) { sc.addAnd("path", SearchCriteria.Op.EQ, path); } - return listIncludingRemovedBy(sc); - } + return listIncludingRemovedBy(sc); + } - @Override - public List listByAccountId(long accountId) { + @Override + public List listByAccountId(long accountId) { SearchCriteria sc = AccountIdSearch.create(); sc.setParameters("accountId", accountId); return listBy(sc); - } + } - @Override + @Override public List listByHypervisorType(List hyperTypes) { - SearchCriteria sc = createSearchCriteria(); + SearchCriteria sc = createSearchCriteria(); hyperTypes.add(HypervisorType.None); sc.addAnd("hypervisorType", SearchCriteria.Op.IN, hyperTypes.toArray()); - return listBy(sc); - } + return listBy(sc); + } - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - boolean result = super.configure(name, params); + @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); + PublicSearch = createSearchBuilder(); + PublicSearch.and("public", PublicSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); - routerTmpltName = (String)params.get("routing.uniquename"); + routerTmpltName = (String) params.get("routing.uniquename"); - s_logger.debug("Found parameter routing unique name " + routerTmpltName); - if (routerTmpltName==null) { - routerTmpltName="routing"; - } + s_logger.debug("Found parameter routing unique name " + routerTmpltName); + if (routerTmpltName == null) { + routerTmpltName = "routing"; + } - consoleProxyTmpltName = (String)params.get("consoleproxy.uniquename"); - if(consoleProxyTmpltName == null) { + consoleProxyTmpltName = (String) params.get("consoleproxy.uniquename"); + if (consoleProxyTmpltName == null) { consoleProxyTmpltName = "routing"; } - if(s_logger.isDebugEnabled()) { + if (s_logger.isDebugEnabled()) { s_logger.debug("Use console proxy template : " + consoleProxyTmpltName); } - UniqueNameSearch = createSearchBuilder(); - UniqueNameSearch.and("uniqueName", UniqueNameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ); - NameSearch = createSearchBuilder(); - NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); + UniqueNameSearch = createSearchBuilder(); + UniqueNameSearch.and("uniqueName", UniqueNameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ); + NameSearch = createSearchBuilder(); + NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); - NameAccountIdSearch = createSearchBuilder(); - NameAccountIdSearch.and("name", NameAccountIdSearch.entity().getName(), SearchCriteria.Op.EQ); - NameAccountIdSearch.and("accountId", NameAccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + NameAccountIdSearch = createSearchBuilder(); + NameAccountIdSearch.and("name", NameAccountIdSearch.entity().getName(), SearchCriteria.Op.EQ); + NameAccountIdSearch.and("accountId", NameAccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - PublicIsoSearch = createSearchBuilder(); - PublicIsoSearch.and("public", PublicIsoSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); - PublicIsoSearch.and("format", PublicIsoSearch.entity().getFormat(), SearchCriteria.Op.EQ); - PublicIsoSearch.and("type", PublicIsoSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); - PublicIsoSearch.and("bootable", PublicIsoSearch.entity().isBootable(), SearchCriteria.Op.EQ); - PublicIsoSearch.and("removed", PublicIsoSearch.entity().getRemoved(), SearchCriteria.Op.EQ); + PublicIsoSearch = createSearchBuilder(); + PublicIsoSearch.and("public", PublicIsoSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); + PublicIsoSearch.and("format", PublicIsoSearch.entity().getFormat(), SearchCriteria.Op.EQ); + PublicIsoSearch.and("type", PublicIsoSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + PublicIsoSearch.and("bootable", PublicIsoSearch.entity().isBootable(), SearchCriteria.Op.EQ); + PublicIsoSearch.and("removed", PublicIsoSearch.entity().getRemoved(), SearchCriteria.Op.EQ); - UserIsoSearch = createSearchBuilder(); - UserIsoSearch.and("format", UserIsoSearch.entity().getFormat(), SearchCriteria.Op.EQ); - UserIsoSearch.and("type", UserIsoSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); - UserIsoSearch.and("removed", UserIsoSearch.entity().getRemoved(), SearchCriteria.Op.EQ); + UserIsoSearch = createSearchBuilder(); + UserIsoSearch.and("format", UserIsoSearch.entity().getFormat(), SearchCriteria.Op.EQ); + UserIsoSearch.and("type", UserIsoSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + UserIsoSearch.and("removed", UserIsoSearch.entity().getRemoved(), SearchCriteria.Op.EQ); - tmpltTypeHyperSearch = createSearchBuilder(); - tmpltTypeHyperSearch.and("templateType", tmpltTypeHyperSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); - SearchBuilder hostHyperSearch = _hostDao.createSearchBuilder(); - hostHyperSearch.and("type", hostHyperSearch.entity().getType(), SearchCriteria.Op.EQ); - hostHyperSearch.and("zoneId", hostHyperSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - hostHyperSearch.groupBy(hostHyperSearch.entity().getHypervisorType()); + tmpltTypeHyperSearch = createSearchBuilder(); + tmpltTypeHyperSearch.and("templateType", tmpltTypeHyperSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + SearchBuilder hostHyperSearch = _hostDao.createSearchBuilder(); + hostHyperSearch.and("type", hostHyperSearch.entity().getType(), SearchCriteria.Op.EQ); + hostHyperSearch.and("zoneId", hostHyperSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + hostHyperSearch.groupBy(hostHyperSearch.entity().getHypervisorType()); - tmpltTypeHyperSearch.join("tmplHyper", hostHyperSearch, hostHyperSearch.entity().getHypervisorType(), tmpltTypeHyperSearch.entity().getHypervisorType(), JoinBuilder.JoinType.INNER); - hostHyperSearch.done(); - tmpltTypeHyperSearch.done(); + tmpltTypeHyperSearch.join("tmplHyper", hostHyperSearch, hostHyperSearch.entity().getHypervisorType(), + tmpltTypeHyperSearch.entity().getHypervisorType(), JoinBuilder.JoinType.INNER); + hostHyperSearch.done(); + tmpltTypeHyperSearch.done(); - tmpltTypeHyperSearch2 = createSearchBuilder(); - tmpltTypeHyperSearch2.and("templateType", tmpltTypeHyperSearch2.entity().getTemplateType(), SearchCriteria.Op.EQ); - tmpltTypeHyperSearch2.and("hypervisorType", tmpltTypeHyperSearch2.entity().getHypervisorType(), SearchCriteria.Op.EQ); + tmpltTypeHyperSearch2 = createSearchBuilder(); + tmpltTypeHyperSearch2.and("templateType", tmpltTypeHyperSearch2.entity().getTemplateType(), + SearchCriteria.Op.EQ); + tmpltTypeHyperSearch2.and("hypervisorType", tmpltTypeHyperSearch2.entity().getHypervisorType(), + SearchCriteria.Op.EQ); tmpltTypeHyperSearch2.and("templateName", tmpltTypeHyperSearch2.entity().getName(), SearchCriteria.Op.EQ); - - tmpltTypeSearch = createSearchBuilder(); + tmpltTypeSearch = createSearchBuilder(); tmpltTypeSearch.and("removed", tmpltTypeSearch.entity().getRemoved(), SearchCriteria.Op.NULL); - tmpltTypeSearch.and("templateType", tmpltTypeSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + tmpltTypeSearch.and("templateType", tmpltTypeSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); - AccountIdSearch = createSearchBuilder(); - AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), 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(); + AccountIdSearch.done(); - SearchBuilder tmpltZoneSearch = _templateZoneDao.createSearchBuilder(); - tmpltZoneSearch.and("removed", tmpltZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL); - tmpltZoneSearch.and("zoneId", tmpltZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + SearchBuilder tmpltZoneSearch = _templateZoneDao.createSearchBuilder(); + tmpltZoneSearch.and("removed", tmpltZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + tmpltZoneSearch.and("zoneId", tmpltZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); - TmpltsInZoneSearch = createSearchBuilder(); - TmpltsInZoneSearch.and("removed", TmpltsInZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL); - TmpltsInZoneSearch.and().op("avoidtype", TmpltsInZoneSearch.entity().getTemplateType(), SearchCriteria.Op.NEQ); - TmpltsInZoneSearch.or("templateType", TmpltsInZoneSearch.entity().getTemplateType(), SearchCriteria.Op.NULL); - TmpltsInZoneSearch.cp(); - TmpltsInZoneSearch.join("tmpltzone", tmpltZoneSearch, tmpltZoneSearch.entity().getTemplateId(), TmpltsInZoneSearch.entity().getId(), JoinBuilder.JoinType.INNER); - tmpltZoneSearch.done(); - TmpltsInZoneSearch.done(); + TmpltsInZoneSearch = createSearchBuilder(); + TmpltsInZoneSearch.and("removed", TmpltsInZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + TmpltsInZoneSearch.and().op("avoidtype", TmpltsInZoneSearch.entity().getTemplateType(), SearchCriteria.Op.NEQ); + TmpltsInZoneSearch.or("templateType", TmpltsInZoneSearch.entity().getTemplateType(), SearchCriteria.Op.NULL); + TmpltsInZoneSearch.cp(); + TmpltsInZoneSearch.join("tmpltzone", tmpltZoneSearch, tmpltZoneSearch.entity().getTemplateId(), + TmpltsInZoneSearch.entity().getId(), JoinBuilder.JoinType.INNER); + tmpltZoneSearch.done(); + TmpltsInZoneSearch.done(); ActiveTmpltSearch = createSearchBuilder(); ActiveTmpltSearch.and("removed", ActiveTmpltSearch.entity().getRemoved(), SearchCriteria.Op.NULL); - - CountTemplatesByAccount = createSearchBuilder(Long.class); - CountTemplatesByAccount.select(null, Func.COUNT, null); - CountTemplatesByAccount.and("account", CountTemplatesByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); - CountTemplatesByAccount.and("removed", CountTemplatesByAccount.entity().getRemoved(), SearchCriteria.Op.NULL); - CountTemplatesByAccount.done(); + CountTemplatesByAccount = createSearchBuilder(Long.class); + CountTemplatesByAccount.select(null, Func.COUNT, null); + CountTemplatesByAccount.and("account", CountTemplatesByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); + CountTemplatesByAccount.and("removed", CountTemplatesByAccount.entity().getRemoved(), SearchCriteria.Op.NULL); + CountTemplatesByAccount.done(); updateStateSearch = this.createSearchBuilder(); updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ); @@ -385,543 +375,388 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ); updateStateSearch.done(); - return result; - } - - @Override - public String getRoutingTemplateUniqueName() { - return routerTmpltName; - } - - /* - @Override - public Set> searchSwiftTemplates(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, Map tags) { - - StringBuilder builder = new StringBuilder(); - if (!permittedAccounts.isEmpty()) { - for (Account permittedAccount : permittedAccounts) { - builder.append(permittedAccount.getAccountId() + ","); - } - } - - String permittedAccountsStr = builder.toString(); - - if (permittedAccountsStr.length() > 0) { - // chop the "," off - permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length() - 1); - } - - Transaction txn = Transaction.currentTxn(); - txn.start(); - - Set> templateZonePairList = new HashSet>(); - PreparedStatement pstmt = null; - ResultSet rs = null; - String sql = SELECT_TEMPLATE_SWIFT_REF; - try { - String joinClause = ""; - String whereClause = " WHERE t.removed IS NULL"; - - if (isIso) { - whereClause += " AND t.format = 'ISO'"; - if (!hyperType.equals(HypervisorType.None)) { - joinClause = " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) "; - whereClause += " AND goh.hypervisor_type = '" + hyperType.toString() + "'"; - } - } else { - whereClause += " AND t.format <> 'ISO'"; - if (hypers.isEmpty()) { - return templateZonePairList; - } else { - StringBuilder relatedHypers = new StringBuilder(); - for (HypervisorType hyper : hypers) { - relatedHypers.append("'"); - relatedHypers.append(hyper.toString()); - relatedHypers.append("'"); - relatedHypers.append(","); - } - relatedHypers.setLength(relatedHypers.length() - 1); - whereClause += " AND t.hypervisor_type IN (" + relatedHypers + ")"; - } - } - joinClause += " INNER JOIN template_swift_ref tsr on (t.id = tsr.template_id)"; - if (keyword != null) { - whereClause += " AND t.name LIKE \"%" + keyword + "%\""; - } else if (name != null) { - whereClause += " AND t.name LIKE \"%" + name + "%\""; - } - - if (bootable != null) { - whereClause += " AND t.bootable = " + bootable; - } - - if (!showDomr) { - whereClause += " AND t.type != '" + Storage.TemplateType.SYSTEM.toString() + "'"; - } - - if (templateFilter == TemplateFilter.featured) { - whereClause += " AND t.public = 1 AND t.featured = 1"; - } else if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - joinClause += " INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)"; - whereClause += " AND d.path LIKE '" + domain.getPath() + "%'"; - } else { - whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")"; - } - } else if ((templateFilter == TemplateFilter.shared || templateFilter == TemplateFilter.sharedexecutable) && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { - joinClause += " LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE" + " (t.account_id IN (" + permittedAccountsStr + ") OR" + " lp.account_id IN (" - + permittedAccountsStr + "))"; - } else { - joinClause += " INNER JOIN account a on (t.account_id = a.id) "; - } - } else if (templateFilter == TemplateFilter.executable && !permittedAccounts.isEmpty()) { - whereClause += " AND (t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))"; - } else if (templateFilter == TemplateFilter.community) { - whereClause += " AND t.public = 1 AND t.featured = 0"; - } else if (templateFilter == TemplateFilter.all && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - return templateZonePairList; - } - - sql += joinClause + whereClause + getOrderByLimit(pageSize, startIndex); - pstmt = txn.prepareStatement(sql); - rs = pstmt.executeQuery(); - while (rs.next()) { - Pair templateZonePair = new Pair(rs.getLong(1), -1L); - templateZonePairList.add(templateZonePair); - } - - } catch (Exception e) { - s_logger.warn("Error listing templates", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - txn.commit(); - } catch (SQLException sqle) { - s_logger.warn("Error in cleaning up", sqle); - } - } - - return templateZonePairList; + return result; } + @Override + public String getRoutingTemplateUniqueName() { + return routerTmpltName; + } - @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, Map tags, String zoneType) { - StringBuilder builder = new StringBuilder(); - if (!permittedAccounts.isEmpty()) { - for (Account permittedAccount : permittedAccounts) { - builder.append(permittedAccount.getAccountId() + ","); - } - } + /* + * @Override public Set> searchSwiftTemplates(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, Map tags) { + * + * StringBuilder builder = new StringBuilder(); if + * (!permittedAccounts.isEmpty()) { for (Account permittedAccount : + * permittedAccounts) { builder.append(permittedAccount.getAccountId() + + * ","); } } + * + * String permittedAccountsStr = builder.toString(); + * + * if (permittedAccountsStr.length() > 0) { // chop the "," off + * permittedAccountsStr = permittedAccountsStr.substring(0, + * permittedAccountsStr.length() - 1); } + * + * Transaction txn = Transaction.currentTxn(); txn.start(); + * + * Set> templateZonePairList = new HashSet>(); PreparedStatement pstmt = null; ResultSet rs = null; String sql + * = SELECT_TEMPLATE_SWIFT_REF; try { String joinClause = ""; String + * whereClause = " WHERE t.removed IS NULL"; + * + * if (isIso) { whereClause += " AND t.format = 'ISO'"; if + * (!hyperType.equals(HypervisorType.None)) { joinClause = + * " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) " + * ; whereClause += " AND goh.hypervisor_type = '" + hyperType.toString() + + * "'"; } } else { whereClause += " AND t.format <> 'ISO'"; if + * (hypers.isEmpty()) { return templateZonePairList; } else { StringBuilder + * relatedHypers = new StringBuilder(); for (HypervisorType hyper : hypers) + * { relatedHypers.append("'"); relatedHypers.append(hyper.toString()); + * relatedHypers.append("'"); relatedHypers.append(","); } + * relatedHypers.setLength(relatedHypers.length() - 1); whereClause += + * " AND t.hypervisor_type IN (" + relatedHypers + ")"; } } joinClause += + * " INNER JOIN template_swift_ref tsr on (t.id = tsr.template_id)"; if + * (keyword != null) { whereClause += " AND t.name LIKE \"%" + keyword + + * "%\""; } else if (name != null) { whereClause += " AND t.name LIKE \"%" + + * name + "%\""; } + * + * if (bootable != null) { whereClause += " AND t.bootable = " + bootable; } + * + * if (!showDomr) { whereClause += " AND t.type != '" + + * Storage.TemplateType.SYSTEM.toString() + "'"; } + * + * if (templateFilter == TemplateFilter.featured) { whereClause += + * " AND t.public = 1 AND t.featured = 1"; } else if ((templateFilter == + * TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) + * && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { if (caller.getType() + * == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == + * Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { joinClause += + * " INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)" + * ; whereClause += " AND d.path LIKE '" + domain.getPath() + "%'"; } else + * { whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")"; } + * } else if ((templateFilter == TemplateFilter.shared || templateFilter == + * TemplateFilter.sharedexecutable) && caller.getType() != + * Account.ACCOUNT_TYPE_ADMIN) { if (caller.getType() == + * Account.ACCOUNT_TYPE_NORMAL) { joinClause += + * " LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE" + + * " (t.account_id IN (" + permittedAccountsStr + ") OR" + + * " lp.account_id IN (" + permittedAccountsStr + "))"; } else { joinClause + * += " INNER JOIN account a on (t.account_id = a.id) "; } } else if + * (templateFilter == TemplateFilter.executable && + * !permittedAccounts.isEmpty()) { whereClause += + * " AND (t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))"; + * } else if (templateFilter == TemplateFilter.community) { whereClause += + * " AND t.public = 1 AND t.featured = 0"; } else if (templateFilter == + * TemplateFilter.all && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { } + * else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { return + * templateZonePairList; } + * + * sql += joinClause + whereClause + getOrderByLimit(pageSize, startIndex); + * pstmt = txn.prepareStatement(sql); rs = pstmt.executeQuery(); while + * (rs.next()) { Pair templateZonePair = new Pair(rs.getLong(1), -1L); templateZonePairList.add(templateZonePair); } + * + * } catch (Exception e) { s_logger.warn("Error listing templates", e); } + * finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { + * pstmt.close(); } txn.commit(); } catch (SQLException sqle) { + * s_logger.warn("Error in cleaning up", sqle); } } + * + * return templateZonePairList; } + * + * + * @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, + * Map tags, String zoneType) { StringBuilder builder = new + * StringBuilder(); if (!permittedAccounts.isEmpty()) { for (Account + * permittedAccount : permittedAccounts) { + * builder.append(permittedAccount.getAccountId() + ","); } } + * + * String permittedAccountsStr = builder.toString(); + * + * if (permittedAccountsStr.length() > 0) { //chop the "," off + * permittedAccountsStr = permittedAccountsStr.substring(0, + * permittedAccountsStr.length()-1); } + * + * Transaction txn = Transaction.currentTxn(); txn.start(); + * + * // Use LinkedHashSet here to guarantee iteration order Set> templateZonePairList = new LinkedHashSet>(); + * PreparedStatement pstmt = null; ResultSet rs = null; StringBuilder + * relatedDomainIds = new StringBuilder(); String sql = + * SELECT_TEMPLATE_ZONE_REF; String groupByClause = ""; try { //short + * accountType; //String accountId = null; String guestOSJoin = ""; + * StringBuilder templateHostRefJoin = new StringBuilder(); String + * dataCenterJoin = "", lpjoin = ""; String tagsJoin = ""; + * + * if (isIso && !hyperType.equals(HypervisorType.None)) { guestOSJoin = + * " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) " + * ; } if (onlyReady){ templateHostRefJoin.append( + * " INNER JOIN template_host_ref thr on (t.id = thr.template_id) INNER JOIN host h on (thr.host_id = h.id)" + * ); sql = SELECT_TEMPLATE_HOST_REF; groupByClause = + * " GROUP BY t.id, h.data_center_id "; } if ((templateFilter == + * TemplateFilter.featured) || (templateFilter == TemplateFilter.community)) + * { dataCenterJoin = + * " INNER JOIN data_center dc on (h.data_center_id = dc.id)"; } + * + * if (zoneType != null) { dataCenterJoin = + * " INNER JOIN template_host_ref thr on (t.id = thr.template_id) INNER JOIN host h on (thr.host_id = h.id)" + * ; dataCenterJoin += + * " INNER JOIN data_center dc on (h.data_center_id = dc.id)"; } + * + * if (templateFilter == TemplateFilter.sharedexecutable || templateFilter + * == TemplateFilter.shared ){ lpjoin = + * " INNER JOIN launch_permission lp ON t.id = lp.template_id "; } + * + * if (tags != null && !tags.isEmpty()) { tagsJoin = + * " INNER JOIN resource_tags r ON t.id = r.resource_id "; } + * + * sql += guestOSJoin + templateHostRefJoin + dataCenterJoin + lpjoin + + * tagsJoin; String whereClause = ""; + * + * //All joins have to be made before we start setting the condition + * settings if ((listProjectResourcesCriteria == + * ListProjectResourcesCriteria.SkipProjectResources || + * (!permittedAccounts.isEmpty() && !(templateFilter == + * TemplateFilter.community || templateFilter == TemplateFilter.featured))) + * && !(caller.getType() != Account.ACCOUNT_TYPE_NORMAL && templateFilter == + * TemplateFilter.all)) { whereClause += + * " INNER JOIN account a on (t.account_id = a.id)"; if ((templateFilter == + * TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) + * && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || + * caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) { + * whereClause += + * " INNER JOIN domain d on (a.domain_id = d.id) WHERE d.path LIKE '" + + * domain.getPath() + "%'"; if (listProjectResourcesCriteria == + * ListProjectResourcesCriteria.SkipProjectResources) { whereClause += + * " AND a.type != " + Account.ACCOUNT_TYPE_PROJECT; } } else if + * (listProjectResourcesCriteria == + * ListProjectResourcesCriteria.SkipProjectResources) { whereClause += + * " WHERE a.type != " + Account.ACCOUNT_TYPE_PROJECT; } } + * + * if (!permittedAccounts.isEmpty()) { for (Account account : + * permittedAccounts) { //accountType = account.getType(); //accountId = + * Long.toString(account.getId()); DomainVO accountDomain = + * _domainDao.findById(account.getDomainId()); + * + * // get all parent domain ID's all the way till root domain DomainVO + * domainTreeNode = accountDomain; while (true) { + * relatedDomainIds.append(domainTreeNode.getId()); + * relatedDomainIds.append(","); if (domainTreeNode.getParent() != null) { + * domainTreeNode = _domainDao.findById(domainTreeNode.getParent()); } else + * { break; } } + * + * // get all child domain ID's if (isAdmin(account.getType()) ) { + * List allChildDomains = + * _domainDao.findAllChildren(accountDomain.getPath(), + * accountDomain.getId()); for (DomainVO childDomain : allChildDomains) { + * relatedDomainIds.append(childDomain.getId()); + * relatedDomainIds.append(","); } } + * relatedDomainIds.setLength(relatedDomainIds.length()-1); } } + * + * String attr = " AND "; if (whereClause.endsWith(" WHERE ")) { attr += + * " WHERE "; } + * + * if (!isIso) { if ( hypers.isEmpty() ) { return templateZonePairList; } + * else { StringBuilder relatedHypers = new StringBuilder(); for + * (HypervisorType hyper : hypers ) { relatedHypers.append("'"); + * relatedHypers.append(hyper.toString()); relatedHypers.append("'"); + * relatedHypers.append(","); } + * relatedHypers.setLength(relatedHypers.length()-1); whereClause += attr + + * " t.hypervisor_type IN (" + relatedHypers + ")"; } } + * + * if (!permittedAccounts.isEmpty() && !(templateFilter == + * TemplateFilter.featured || templateFilter == TemplateFilter.community || + * templateFilter == TemplateFilter.executable || templateFilter == + * TemplateFilter.shared || templateFilter == + * TemplateFilter.sharedexecutable) && !isAdmin(caller.getType()) ) { + * whereClause += attr + "t.account_id IN (" + permittedAccountsStr + ")"; } + * + * if (templateFilter == TemplateFilter.featured) { whereClause += attr + + * "t.public = 1 AND t.featured = 1"; if (!permittedAccounts.isEmpty()) { + * whereClause += attr + "(dc.domain_id IN (" + relatedDomainIds + + * ") OR dc.domain_id is NULL)"; } } else if (templateFilter == + * TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) { + * whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")"; } + * else if (templateFilter == TemplateFilter.sharedexecutable || + * templateFilter == TemplateFilter.shared ) { whereClause += " AND " + + * " (t.account_id IN (" + permittedAccountsStr + ") OR" + + * " lp.account_id IN (" + permittedAccountsStr + "))"; } else if + * (templateFilter == TemplateFilter.executable && + * !permittedAccounts.isEmpty()) { whereClause += attr + + * "(t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))"; } + * else if (templateFilter == TemplateFilter.community) { whereClause += + * attr + "t.public = 1 AND t.featured = 0"; if + * (!permittedAccounts.isEmpty()) { whereClause += attr + + * "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)"; } + * } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && !isIso) { + * return templateZonePairList; } + * + * if (tags != null && !tags.isEmpty()) { whereClause += " AND ("; boolean + * first = true; for (String key : tags.keySet()) { if (!first) { + * whereClause += " OR "; } whereClause += "(r.key=\"" + key + + * "\" and r.value=\"" + tags.get(key) + "\")"; first = false; } whereClause + * += ")"; } + * + * if (whereClause.equals("")) { whereClause += " WHERE "; } else if + * (!whereClause.equals(" WHERE ")) { whereClause += " AND "; } + * + * sql += whereClause + getExtrasWhere(templateFilter, name, keyword, isIso, + * bootable, hyperType, zoneId, onlyReady, showDomr, zoneType) + + * groupByClause + getOrderByLimit(pageSize, startIndex); + * + * pstmt = txn.prepareStatement(sql); rs = pstmt.executeQuery(); + * + * while (rs.next()) { Pair templateZonePair = new Pair(rs.getLong(1), rs.getLong(2)); + * templateZonePairList.add(templateZonePair); } //for now, defaulting + * pageSize to a large val if null; may need to revisit post 2.2RC2 if(isIso + * && templateZonePairList.size() < (pageSize != null ? pageSize : 500) && + * templateFilter != TemplateFilter.community && !(templateFilter == + * TemplateFilter.self && !BaseCmd.isRootAdmin(caller.getType())) ){ + * //evaluates to true If root admin and filter=self + * + * List publicIsos = publicIsoSearch(bootable, false, tags); + * List userIsos = userIsoSearch(false); + * + * //Listing the ISOs according to the page size.Restricting the total no. + * of ISOs on a page //to be less than or equal to the pageSize parameter + * + * int i=0; + * + * if (startIndex > userIsos.size()) { i=(int) (startIndex - + * userIsos.size()); } + * + * for (; i < publicIsos.size(); i++) { if(templateZonePairList.size() >= + * pageSize){ break; } else { if (keyword != null && + * publicIsos.get(i).getName().contains(keyword)) { + * templateZonePairList.add(new Pair(publicIsos.get(i).getId(), + * null)); continue; } else if (name != null && + * publicIsos.get(i).getName().contains(name)) { + * templateZonePairList.add(new Pair(publicIsos.get(i).getId(), + * null)); continue; } else if (keyword == null && name == null){ + * templateZonePairList.add(new Pair(publicIsos.get(i).getId(), + * null)); } } } } } catch (Exception e) { + * s_logger.warn("Error listing templates", e); } finally { try { if (rs != + * null) { rs.close(); } if (pstmt != null) { pstmt.close(); } txn.commit(); + * } catch( SQLException sqle) { s_logger.warn("Error in cleaning up", + * sqle); } } + * + * return templateZonePairList; } + */ - String permittedAccountsStr = builder.toString(); + /* + * private String getExtrasWhere(TemplateFilter templateFilter, String name, + * String keyword, boolean isIso, Boolean bootable, HypervisorType + * hyperType, Long zoneId, boolean onlyReady, boolean showDomr, String + * zoneType) { 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 { + * 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 (onlyReady){ sql += " AND thr.download_state = '" + * +Status.DOWNLOADED.toString() + "'" + " AND thr.destroyed=0 "; if (zoneId + * != null){ sql += " AND h.data_center_id = " +zoneId; } }else if (zoneId + * != null){ sql += " AND tzr.zone_id = " +zoneId+ + * " AND tzr.removed is null" ; }else{ sql += " AND tzr.removed is null "; } + * + * if (zoneType != null){ sql += " AND dc.networktype = '" + zoneType + "'"; + * } + * + * if (!showDomr){ sql += " AND t.type != '" + * +Storage.TemplateType.SYSTEM.toString() + "'"; } + * + * 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); + * + * String sql; if (isAscending) { sql = " ORDER BY t.sort_key ASC"; } else { + * sql = " ORDER BY t.sort_key DESC"; } + * + * if ((pageSize != null) && (startIndex != null)) { sql += " LIMIT " + + * startIndex.toString() + "," + pageSize.toString(); } return sql; } + */ - if (permittedAccountsStr.length() > 0) { - //chop the "," off - permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length()-1); - } - - Transaction txn = Transaction.currentTxn(); + @SuppressWarnings("unchecked") + @Override + @DB + public long addTemplateToZone(VMTemplateVO tmplt, long zoneId) { + Transaction txn = Transaction.currentTxn(); txn.start(); - - // Use LinkedHashSet here to guarantee iteration order - Set> templateZonePairList = new LinkedHashSet>(); - PreparedStatement pstmt = null; - ResultSet rs = null; - StringBuilder relatedDomainIds = new StringBuilder(); - String sql = SELECT_TEMPLATE_ZONE_REF; - String groupByClause = ""; - try { - //short accountType; - //String accountId = null; - String guestOSJoin = ""; - StringBuilder templateHostRefJoin = new StringBuilder(); - String dataCenterJoin = "", lpjoin = ""; - String tagsJoin = ""; - - if (isIso && !hyperType.equals(HypervisorType.None)) { - guestOSJoin = " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) "; - } - if (onlyReady){ - templateHostRefJoin.append(" INNER JOIN template_host_ref thr on (t.id = thr.template_id) INNER JOIN host h on (thr.host_id = h.id)"); - sql = SELECT_TEMPLATE_HOST_REF; - groupByClause = " GROUP BY t.id, h.data_center_id "; - } - if ((templateFilter == TemplateFilter.featured) || (templateFilter == TemplateFilter.community)) { - dataCenterJoin = " INNER JOIN data_center dc on (h.data_center_id = dc.id)"; - } - - if (zoneType != null) { - dataCenterJoin = " INNER JOIN template_host_ref thr on (t.id = thr.template_id) INNER JOIN host h on (thr.host_id = h.id)"; - dataCenterJoin += " INNER JOIN data_center dc on (h.data_center_id = dc.id)"; + VMTemplateVO tmplt2 = findById(tmplt.getId()); + if (tmplt2 == null) { + if (persist(tmplt) == null) { + throw new CloudRuntimeException("Failed to persist the template " + tmplt); } - - if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared ){ - lpjoin = " INNER JOIN launch_permission lp ON t.id = lp.template_id "; - } - - if (tags != null && !tags.isEmpty()) { - tagsJoin = " INNER JOIN resource_tags r ON t.id = r.resource_id "; - } - - sql += guestOSJoin + templateHostRefJoin + dataCenterJoin + lpjoin + tagsJoin; - String whereClause = ""; - - //All joins have to be made before we start setting the condition settings - if ((listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources - || (!permittedAccounts.isEmpty() && !(templateFilter == TemplateFilter.community || templateFilter == TemplateFilter.featured))) && - !(caller.getType() != Account.ACCOUNT_TYPE_NORMAL && templateFilter == TemplateFilter.all)) { - whereClause += " INNER JOIN account a on (t.account_id = a.id)"; - if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) { - whereClause += " INNER JOIN domain d on (a.domain_id = d.id) WHERE d.path LIKE '" + domain.getPath() + "%'"; - if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) { - whereClause += " AND a.type != " + Account.ACCOUNT_TYPE_PROJECT; - } - } else - if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) { - whereClause += " WHERE a.type != " + Account.ACCOUNT_TYPE_PROJECT; - } - } - - if (!permittedAccounts.isEmpty()) { - for (Account account : permittedAccounts) { - //accountType = account.getType(); - //accountId = Long.toString(account.getId()); - DomainVO accountDomain = _domainDao.findById(account.getDomainId()); - - // get all parent domain ID's all the way till root domain - DomainVO domainTreeNode = accountDomain; - while (true) { - relatedDomainIds.append(domainTreeNode.getId()); - relatedDomainIds.append(","); - if (domainTreeNode.getParent() != null) { - domainTreeNode = _domainDao.findById(domainTreeNode.getParent()); - } else { - break; - } - } - - // get all child domain ID's - if (isAdmin(account.getType()) ) { - List allChildDomains = _domainDao.findAllChildren(accountDomain.getPath(), accountDomain.getId()); - for (DomainVO childDomain : allChildDomains) { - relatedDomainIds.append(childDomain.getId()); - relatedDomainIds.append(","); - } - } - relatedDomainIds.setLength(relatedDomainIds.length()-1); - } + if (tmplt.getDetails() != null) { + _templateDetailsDao.persist(tmplt.getId(), tmplt.getDetails()); } - - String attr = " AND "; - if (whereClause.endsWith(" WHERE ")) { - attr += " WHERE "; - } - - if (!isIso) { - if ( hypers.isEmpty() ) { - return templateZonePairList; - } else { - StringBuilder relatedHypers = new StringBuilder(); - for (HypervisorType hyper : hypers ) { - relatedHypers.append("'"); - relatedHypers.append(hyper.toString()); - relatedHypers.append("'"); - relatedHypers.append(","); - } - relatedHypers.setLength(relatedHypers.length()-1); - whereClause += attr + " t.hypervisor_type IN (" + relatedHypers + ")"; - } - } - - if (!permittedAccounts.isEmpty() && !(templateFilter == TemplateFilter.featured || - templateFilter == TemplateFilter.community || templateFilter == TemplateFilter.executable - || templateFilter == TemplateFilter.shared || templateFilter == TemplateFilter.sharedexecutable) && !isAdmin(caller.getType()) ) { - whereClause += attr + "t.account_id IN (" + permittedAccountsStr + ")"; - } - - if (templateFilter == TemplateFilter.featured) { - whereClause += attr + "t.public = 1 AND t.featured = 1"; - if (!permittedAccounts.isEmpty()) { - whereClause += attr + "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)"; - } - } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) { - whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")"; - } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared ) { - whereClause += " AND " + - " (t.account_id IN (" + permittedAccountsStr + ") OR" + - " lp.account_id IN (" + permittedAccountsStr + "))"; - } else if (templateFilter == TemplateFilter.executable && !permittedAccounts.isEmpty()) { - whereClause += attr + "(t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))"; - } else if (templateFilter == TemplateFilter.community) { - whereClause += attr + "t.public = 1 AND t.featured = 0"; - if (!permittedAccounts.isEmpty()) { - whereClause += attr + "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)"; - } - } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && !isIso) { - return templateZonePairList; - } - - if (tags != null && !tags.isEmpty()) { - whereClause += " AND ("; - boolean first = true; - for (String key : tags.keySet()) { - if (!first) { - whereClause += " OR "; - } - whereClause += "(r.key=\"" + key + "\" and r.value=\"" + tags.get(key) + "\")"; - first = false; - } - whereClause += ")"; - } - - if (whereClause.equals("")) { - whereClause += " WHERE "; - } else if (!whereClause.equals(" WHERE ")) { - whereClause += " AND "; - } - - sql += whereClause + getExtrasWhere(templateFilter, name, keyword, isIso, bootable, hyperType, zoneId, - onlyReady, showDomr, zoneType) + groupByClause + getOrderByLimit(pageSize, startIndex); - - pstmt = txn.prepareStatement(sql); - rs = pstmt.executeQuery(); - - while (rs.next()) { - Pair templateZonePair = new Pair(rs.getLong(1), rs.getLong(2)); - templateZonePairList.add(templateZonePair); - } - //for now, defaulting pageSize to a large val if null; may need to revisit post 2.2RC2 - if(isIso && templateZonePairList.size() < (pageSize != null ? pageSize : 500) - && templateFilter != TemplateFilter.community - && !(templateFilter == TemplateFilter.self && !BaseCmd.isRootAdmin(caller.getType())) ){ //evaluates to true If root admin and filter=self - - List publicIsos = publicIsoSearch(bootable, false, tags); - List userIsos = userIsoSearch(false); - - //Listing the ISOs according to the page size.Restricting the total no. of ISOs on a page - //to be less than or equal to the pageSize parameter - - int i=0; - - if (startIndex > userIsos.size()) { - i=(int) (startIndex - userIsos.size()); - } - - for (; i < publicIsos.size(); i++) { - if(templateZonePairList.size() >= pageSize){ - break; - } else { - if (keyword != null && publicIsos.get(i).getName().contains(keyword)) { - templateZonePairList.add(new Pair(publicIsos.get(i).getId(), null)); - continue; - } else if (name != null && publicIsos.get(i).getName().contains(name)) { - templateZonePairList.add(new Pair(publicIsos.get(i).getId(), null)); - continue; - } else if (keyword == null && name == null){ - templateZonePairList.add(new Pair(publicIsos.get(i).getId(), null)); - } - } - } - } - } catch (Exception e) { - s_logger.warn("Error listing templates", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - txn.commit(); - } catch( SQLException sqle) { - s_logger.warn("Error in cleaning up", sqle); - } } - - return templateZonePairList; - } - */ - - /* - private String getExtrasWhere(TemplateFilter templateFilter, String name, String keyword, boolean isIso, Boolean bootable, HypervisorType hyperType, Long zoneId, boolean onlyReady, boolean showDomr, String zoneType) { - 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() + "'"; - } + VMTemplateZoneVO tmpltZoneVO = _templateZoneDao.findByZoneTemplate(zoneId, tmplt.getId()); + if (tmpltZoneVO == null) { + tmpltZoneVO = new VMTemplateZoneVO(zoneId, tmplt.getId(), new Date()); + _templateZoneDao.persist(tmpltZoneVO); } else { - sql += " t.format <> 'ISO'"; - if (!hyperType.equals(HypervisorType.None)) { - sql += " AND t.hypervisor_type = '" + hyperType.toString() + "'"; - } + tmpltZoneVO.setRemoved(null); + tmpltZoneVO.setLastUpdated(new Date()); + _templateZoneDao.update(tmpltZoneVO.getId(), tmpltZoneVO); } + txn.commit(); - if (bootable != null) { - sql += " AND t.bootable = " + bootable; - } + return tmplt.getId(); + } - if (onlyReady){ - sql += " AND thr.download_state = '" +Status.DOWNLOADED.toString() + "'" + " AND thr.destroyed=0 "; - if (zoneId != null){ - sql += " AND h.data_center_id = " +zoneId; - } - }else if (zoneId != null){ - sql += " AND tzr.zone_id = " +zoneId+ " AND tzr.removed is null" ; - }else{ - sql += " AND tzr.removed is null "; - } + @Override + @DB + public List listAllInZone(long dataCenterId) { + SearchCriteria sc = TmpltsInZoneSearch.create(); + sc.setParameters("avoidtype", TemplateType.PERHOST.toString()); + sc.setJoinParameters("tmpltzone", "zoneId", dataCenterId); + return listBy(sc); + } - if (zoneType != null){ - sql += " AND dc.networktype = '" + zoneType + "'"; - } - - if (!showDomr){ - sql += " AND t.type != '" +Storage.TemplateType.SYSTEM.toString() + "'"; - } - - 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); - - String sql; - if (isAscending) { - sql = " ORDER BY t.sort_key ASC"; - } else { - sql = " ORDER BY t.sort_key DESC"; - } - - if ((pageSize != null) && (startIndex != null)) { - sql += " LIMIT " + startIndex.toString() + "," + pageSize.toString(); - } - return sql; - } - */ - - @Override - @DB - public long addTemplateToZone(VMTemplateVO tmplt, long zoneId) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - VMTemplateVO tmplt2 = findById(tmplt.getId()); - if (tmplt2 == null){ - if (persist(tmplt) == null) { - throw new CloudRuntimeException("Failed to persist the template " + tmplt); - } - if(tmplt.getDetails() != null) { - _templateDetailsDao.persist(tmplt.getId(), tmplt.getDetails()); - } - } - VMTemplateZoneVO tmpltZoneVO = _templateZoneDao.findByZoneTemplate(zoneId, tmplt.getId()); - if (tmpltZoneVO == null ) { - tmpltZoneVO = new VMTemplateZoneVO(zoneId, tmplt.getId(), new Date()); - _templateZoneDao.persist(tmpltZoneVO); - } else { - tmpltZoneVO.setRemoved(null); - tmpltZoneVO.setLastUpdated(new Date()); - _templateZoneDao.update(tmpltZoneVO.getId(), tmpltZoneVO); - } - txn.commit(); - - return tmplt.getId(); - } - - @Override - @DB - public List listAllInZone(long dataCenterId) { - SearchCriteria sc = TmpltsInZoneSearch.create(); - sc.setParameters("avoidtype", TemplateType.PERHOST.toString()); - sc.setJoinParameters("tmpltzone", "zoneId", dataCenterId); - return listBy(sc); - } - - - - @Override + @Override public List listAllActive() { SearchCriteria sc = ActiveTmpltSearch.create(); return listBy(sc); } @Override - public List listDefaultBuiltinTemplates() { - SearchCriteria sc = tmpltTypeSearch.create(); - sc.setParameters("templateType", Storage.TemplateType.BUILTIN); - return listBy(sc); - } + public List listDefaultBuiltinTemplates() { + SearchCriteria sc = tmpltTypeSearch.create(); + sc.setParameters("templateType", Storage.TemplateType.BUILTIN); + return listBy(sc); + } - @Override - public VMTemplateVO findSystemVMTemplate(long zoneId) { - SearchCriteria sc = tmpltTypeHyperSearch.create(); - sc.setParameters("templateType", Storage.TemplateType.SYSTEM); - sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing); - sc.setJoinParameters("tmplHyper", "zoneId", zoneId); - - //order by descending order of id and select the first (this is going to be the latest) - List tmplts = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, 1l)); - - if (tmplts.size() > 0) { - return tmplts.get(0); - } else { - return null; - } - } - - @Override - public VMTemplateVO findSystemVMTemplate(long zoneId, HypervisorType hType) { - SearchCriteria sc = tmpltTypeHyperSearch.create(); - sc.setParameters("templateType", Storage.TemplateType.SYSTEM); - sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing); - sc.setJoinParameters("tmplHyper", "zoneId", zoneId); - - //order by descending order of id - List tmplts = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, null)); - - for (VMTemplateVO tmplt: tmplts) { - if (tmplt.getHypervisorType() == hType) { - return tmplt; - } - } - if (tmplts.size() > 0 && hType == HypervisorType.Any) { - return tmplts.get(0); - } - return null; - } - - @Override - public VMTemplateVO findRoutingTemplate(HypervisorType hType, String templateName) { - SearchCriteria sc = tmpltTypeHyperSearch2.create(); + @Override + public VMTemplateVO findSystemVMTemplate(long zoneId) { + SearchCriteria sc = tmpltTypeHyperSearch.create(); sc.setParameters("templateType", Storage.TemplateType.SYSTEM); - sc.setParameters("hypervisorType", hType); - if (templateName != null) { - sc.setParameters("templateName", templateName); - } + sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing); + sc.setJoinParameters("tmplHyper", "zoneId", zoneId); - //order by descending order of id and select the first (this is going to be the latest) + // order by descending order of id and select the first (this is going + // to be the latest) List tmplts = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, 1l)); if (tmplts.size() > 0) { @@ -929,11 +764,52 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } else { return null; } - } + } + + @Override + public VMTemplateVO findSystemVMTemplate(long zoneId, HypervisorType hType) { + SearchCriteria sc = tmpltTypeHyperSearch.create(); + sc.setParameters("templateType", Storage.TemplateType.SYSTEM); + sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing); + sc.setJoinParameters("tmplHyper", "zoneId", zoneId); + + // order by descending order of id + List tmplts = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, null)); + + for (VMTemplateVO tmplt : tmplts) { + if (tmplt.getHypervisorType() == hType) { + return tmplt; + } + } + if (tmplts.size() > 0 && hType == HypervisorType.Any) { + return tmplts.get(0); + } + return null; + } + + @Override + public VMTemplateVO findRoutingTemplate(HypervisorType hType, String templateName) { + SearchCriteria sc = tmpltTypeHyperSearch2.create(); + sc.setParameters("templateType", Storage.TemplateType.SYSTEM); + sc.setParameters("hypervisorType", hType); + if (templateName != null) { + sc.setParameters("templateName", templateName); + } + + // order by descending order of id and select the first (this is going + // to be the latest) + List tmplts = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, 1l)); + + if (tmplts.size() > 0) { + return tmplts.get(0); + } else { + return null; + } + } @Override public Long countTemplatesForAccount(long accountId) { - SearchCriteria sc = CountTemplatesByAccount.create(); + SearchCriteria sc = CountTemplatesByAccount.create(); sc.setParameters("account", accountId); return customSearch(sc, null).get(0); } @@ -960,156 +836,108 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem return result; } - - @Override public List findTemplatesToSyncToS3() { return executeList(SELECT_S3_CANDIDATE_TEMPLATES, new Object[] {}); } /* - @Override - public Set> searchS3Templates(final String name, - final String keyword, final TemplateFilter templateFilter, - final boolean isIso, final List hypers, - final Boolean bootable, final DomainVO domain, final Long pageSize, - final Long startIndex, final Long zoneId, - final HypervisorType hyperType, final boolean onlyReady, - final boolean showDomr, final List permittedAccounts, - final Account caller, final Map tags) { - - final String permittedAccountsStr = join(",", permittedAccounts); - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - - Set> templateZonePairList = new HashSet>(); - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - - final StringBuilder joinClause = new StringBuilder(); - final StringBuilder whereClause = new StringBuilder(" WHERE t.removed IS NULL"); - - if (isIso) { - whereClause.append(" AND t.format = 'ISO'"); - if (!hyperType.equals(HypervisorType.None)) { - joinClause.append(" INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) "); - whereClause.append(" AND goh.hypervisor_type = '"); - whereClause.append(hyperType); - whereClause.append("'"); - } - } else { - whereClause.append(" AND t.format <> 'ISO'"); - if (hypers.isEmpty()) { - return templateZonePairList; - } else { - final StringBuilder relatedHypers = new StringBuilder(); - for (HypervisorType hyper : hypers) { - relatedHypers.append("'"); - relatedHypers.append(hyper.toString()); - relatedHypers.append("'"); - relatedHypers.append(","); - } - relatedHypers.setLength(relatedHypers.length() - 1); - whereClause.append(" AND t.hypervisor_type IN ("); - whereClause.append(relatedHypers); - whereClause.append(")"); - } - } - - joinClause.append(" INNER JOIN template_s3_ref tsr on (t.id = tsr.template_id)"); - - whereClause.append("AND t.name LIKE \"%"); - whereClause.append(keyword == null ? keyword : name); - whereClause.append("%\""); - - if (bootable != null) { - whereClause.append(" AND t.bootable = "); - whereClause.append(bootable); - } - - if (!showDomr) { - whereClause.append(" AND t.type != '"); - whereClause.append(Storage.TemplateType.SYSTEM); - whereClause.append("'"); - } - - if (templateFilter == TemplateFilter.featured) { - whereClause.append(" AND t.public = 1 AND t.featured = 1"); - } else if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) - && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN - || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - joinClause.append(" INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)"); - whereClause.append(" AND d.path LIKE '"); - whereClause.append(domain.getPath()); - whereClause.append("%'"); - } else { - whereClause.append(" AND t.account_id IN ("); - whereClause.append(permittedAccountsStr); - whereClause.append(")"); - } - } else if (templateFilter == TemplateFilter.sharedexecutable - && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { - joinClause.append(" LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE (t.account_id IN ("); - joinClause.append(permittedAccountsStr); - joinClause.append(") OR lp.account_id IN ("); - joinClause.append(permittedAccountsStr); - joinClause.append("))"); - } else { - joinClause.append(" INNER JOIN account a on (t.account_id = a.id) "); - } - } else if (templateFilter == TemplateFilter.executable - && !permittedAccounts.isEmpty()) { - whereClause.append(" AND (t.public = 1 OR t.account_id IN ("); - whereClause.append(permittedAccountsStr); - whereClause.append("))"); - } else if (templateFilter == TemplateFilter.community) { - whereClause.append(" AND t.public = 1 AND t.featured = 0"); - } else if (templateFilter == TemplateFilter.all - && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - return templateZonePairList; - } - - final StringBuilder sql = new StringBuilder(SELECT_TEMPLATE_S3_REF); - sql.append(joinClause); - sql.append(whereClause); - sql.append(getOrderByLimit(pageSize, startIndex)); - - pstmt = txn.prepareStatement(sql.toString()); - rs = pstmt.executeQuery(); - while (rs.next()) { - final Pair templateZonePair = new Pair( - rs.getLong(1), -1L); - templateZonePairList.add(templateZonePair); - } - txn.commit(); - } catch (Exception e) { - s_logger.warn("Error listing S3 templates", e); - if (txn != null) { - txn.rollback(); - } - } finally { - closeResources(pstmt, rs); - if (txn != null) { - txn.close(); - } - } - - return templateZonePairList; - } -*/ + * @Override public Set> searchS3Templates(final String + * name, final String keyword, final TemplateFilter templateFilter, final + * boolean isIso, final List hypers, final Boolean bootable, + * final DomainVO domain, final Long pageSize, final Long startIndex, final + * Long zoneId, final HypervisorType hyperType, final boolean onlyReady, + * final boolean showDomr, final List permittedAccounts, final + * Account caller, final Map tags) { + * + * final String permittedAccountsStr = join(",", permittedAccounts); + * + * final Transaction txn = Transaction.currentTxn(); txn.start(); + * + * Set> templateZonePairList = new HashSet>(); PreparedStatement pstmt = null; ResultSet rs = null; try { + * + * final StringBuilder joinClause = new StringBuilder(); final StringBuilder + * whereClause = new StringBuilder(" WHERE t.removed IS NULL"); + * + * if (isIso) { whereClause.append(" AND t.format = 'ISO'"); if + * (!hyperType.equals(HypervisorType.None)) { joinClause.append( + * " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) " + * ); whereClause.append(" AND goh.hypervisor_type = '"); + * whereClause.append(hyperType); whereClause.append("'"); } } else { + * whereClause.append(" AND t.format <> 'ISO'"); if (hypers.isEmpty()) { + * return templateZonePairList; } else { final StringBuilder relatedHypers = + * new StringBuilder(); for (HypervisorType hyper : hypers) { + * relatedHypers.append("'"); relatedHypers.append(hyper.toString()); + * relatedHypers.append("'"); relatedHypers.append(","); } + * relatedHypers.setLength(relatedHypers.length() - 1); + * whereClause.append(" AND t.hypervisor_type IN ("); + * whereClause.append(relatedHypers); whereClause.append(")"); } } + * + * joinClause.append( + * " INNER JOIN template_s3_ref tsr on (t.id = tsr.template_id)"); + * + * whereClause.append("AND t.name LIKE \"%"); whereClause.append(keyword == + * null ? keyword : name); whereClause.append("%\""); + * + * if (bootable != null) { whereClause.append(" AND t.bootable = "); + * whereClause.append(bootable); } + * + * if (!showDomr) { whereClause.append(" AND t.type != '"); + * whereClause.append(Storage.TemplateType.SYSTEM); whereClause.append("'"); + * } + * + * if (templateFilter == TemplateFilter.featured) { + * whereClause.append(" AND t.public = 1 AND t.featured = 1"); } else if + * ((templateFilter == TemplateFilter.self || templateFilter == + * TemplateFilter.selfexecutable) && caller.getType() != + * Account.ACCOUNT_TYPE_ADMIN) { if (caller.getType() == + * Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == + * Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { joinClause.append( + * " INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)" + * ); whereClause.append(" AND d.path LIKE '"); + * whereClause.append(domain.getPath()); whereClause.append("%'"); } else { + * whereClause.append(" AND t.account_id IN ("); + * whereClause.append(permittedAccountsStr); whereClause.append(")"); } } + * else if (templateFilter == TemplateFilter.sharedexecutable && + * caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { if (caller.getType() == + * Account.ACCOUNT_TYPE_NORMAL) { joinClause.append( + * " LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE (t.account_id IN (" + * ); joinClause.append(permittedAccountsStr); + * joinClause.append(") OR lp.account_id IN ("); + * joinClause.append(permittedAccountsStr); joinClause.append("))"); } else + * { joinClause.append(" INNER JOIN account a on (t.account_id = a.id) "); } + * } else if (templateFilter == TemplateFilter.executable && + * !permittedAccounts.isEmpty()) { + * whereClause.append(" AND (t.public = 1 OR t.account_id IN ("); + * whereClause.append(permittedAccountsStr); whereClause.append("))"); } + * else if (templateFilter == TemplateFilter.community) { + * whereClause.append(" AND t.public = 1 AND t.featured = 0"); } else if + * (templateFilter == TemplateFilter.all && caller.getType() == + * Account.ACCOUNT_TYPE_ADMIN) { } else if (caller.getType() != + * Account.ACCOUNT_TYPE_ADMIN) { return templateZonePairList; } + * + * final StringBuilder sql = new StringBuilder(SELECT_TEMPLATE_S3_REF); + * sql.append(joinClause); sql.append(whereClause); + * sql.append(getOrderByLimit(pageSize, startIndex)); + * + * pstmt = txn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); + * while (rs.next()) { final Pair templateZonePair = new + * Pair( rs.getLong(1), -1L); + * templateZonePairList.add(templateZonePair); } txn.commit(); } catch + * (Exception e) { s_logger.warn("Error listing S3 templates", e); if (txn + * != null) { txn.rollback(); } } finally { closeResources(pstmt, rs); if + * (txn != null) { txn.close(); } } + * + * return templateZonePairList; } + */ @Override - public boolean updateState(TemplateState currentState, TemplateEvent event, - TemplateState nextState, VMTemplateVO vo, Object data) { + public boolean updateState(TemplateState currentState, TemplateEvent event, TemplateState nextState, + VMTemplateVO vo, Object data) { Long oldUpdated = vo.getUpdatedCount(); Date oldUpdatedTime = vo.getUpdated(); - SearchCriteria sc = updateStateSearch.create(); sc.setParameters("id", vo.getId()); sc.setParameters("state", currentState); @@ -1126,14 +954,18 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem VMTemplateVO dbVol = findByIdIncludingRemoved(vo.getId()); if (dbVol != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); - str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=") + str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()) + .append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=") .append(dbVol.getUpdated()); - str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()) + str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState) + .append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()) .append("; updatedTime=").append(vo.getUpdated()); - str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated) + str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState) + .append("; event=").append(event).append("; updatecount=").append(oldUpdated) .append("; updatedTime=").append(oldUpdatedTime); } else { - s_logger.debug("Unable to update objectIndatastore: id=" + vo.getId() + ", as there is no such object exists in the database anymore"); + s_logger.debug("Unable to update objectIndatastore: id=" + vo.getId() + + ", as there is no such object exists in the database anymore"); } } return rows > 0; diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDao.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDao.java index 5edea8e5586..552f8f00a86 100644 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDao.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDao.java @@ -21,12 +21,12 @@ import java.util.Map; import com.cloud.storage.VMTemplateDetailVO; import com.cloud.utils.db.GenericDao; -public interface VMTemplateDetailsDao extends 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); + + void deleteDetails(long vmId); } diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java index 04b553c2f8b..33b96c45bcc 100644 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateDetailsDaoImpl.java @@ -31,69 +31,69 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @Component -@Local(value=VMTemplateDetailsDao.class) +@Local(value = VMTemplateDetailsDao.class) public class VMTemplateDetailsDaoImpl extends GenericDaoBase implements VMTemplateDetailsDao { protected final SearchBuilder TemplateSearch; protected final SearchBuilder DetailSearch; - - public VMTemplateDetailsDaoImpl() { - TemplateSearch = createSearchBuilder(); - TemplateSearch.and("templateId", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateSearch.done(); - - DetailSearch = createSearchBuilder(); + + public 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) { + } + + @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()); - } - } + remove(result.getId()); + } + } - @Override - public VMTemplateDetailVO findDetail(long templateId, String name) { + @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) { + 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) { + 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(); - } + txn.commit(); + } } diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDao.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDao.java index 23241cd17da..72072fa9325 100755 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDao.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDao.java @@ -26,28 +26,31 @@ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface VMTemplateHostDao extends GenericDao, StateDao { +public interface VMTemplateHostDao extends GenericDao, + StateDao { List listByHostId(long id); List listByTemplateId(long templateId); - + List listByOnlyTemplateId(long templateId); VMTemplateHostVO findByHostTemplate(long hostId, long templateId); - + VMTemplateHostVO findByTemplateId(long templateId); VMTemplateHostVO findByHostTemplate(long hostId, long templateId, boolean lock); List listByHostTemplate(long hostId, long templateId); - void update(VMTemplateHostVO instance); + void update(VMTemplateHostVO instance); List listByTemplateStatus(long templateId, VMTemplateHostVO.Status downloadState); - List listByTemplateStatus(long templateId, long datacenterId, VMTemplateHostVO.Status downloadState); + List listByTemplateStatus(long templateId, long datacenterId, + VMTemplateHostVO.Status downloadState); - List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateHostVO.Status downloadState); + List listByTemplateStatus(long templateId, long datacenterId, long podId, + VMTemplateHostVO.Status downloadState); List listByTemplateStates(long templateId, VMTemplateHostVO.Status... states); diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java index 7f35eabfaa7..85d8348e36e 100755 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java @@ -50,67 +50,61 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; @Component -@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; - protected final SearchBuilder HostTemplateSearch; - protected final SearchBuilder HostTemplateStateSearch; - protected final SearchBuilder HostDestroyedSearch; - protected final SearchBuilder TemplateStatusSearch; - protected final SearchBuilder TemplateStatesSearch; - protected final SearchBuilder updateStateSearch; - protected SearchBuilder ZONE_TEMPLATE_SEARCH; - protected SearchBuilder LOCAL_SECONDARY_STORAGE_SEARCH; + 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 TemplateStatesSearch; + protected final SearchBuilder updateStateSearch; + protected SearchBuilder ZONE_TEMPLATE_SEARCH; + protected SearchBuilder LOCAL_SECONDARY_STORAGE_SEARCH; - - protected static final String UPDATE_TEMPLATE_HOST_REF = - "UPDATE template_host_ref SET download_state = ?, download_pct= ?, last_updated = ? " - + ", error_str = ?, local_path = ?, job_id = ? " - + "WHERE host_id = ? and type_id = ?"; - - protected static final String DOWNLOADS_STATE_DC= - "SELECT t.id, t.host_id, t.template_id, t.created, t.last_updated, t.job_id, " - + "t.download_pct, t.size, t.physical_size, t.download_state, t.error_str, t.local_path, " - + "t.install_path, t.url, t.destroyed, t.is_copy FROM template_host_ref t, host h " - + "where t.host_id = h.id and h.data_center_id=? " - + " and t.template_id=? and t.download_state = ?" ; - - protected static final String DOWNLOADS_STATE_DC_POD= - "SELECT * FROM template_host_ref t, host h where t.host_id = h.id and h.data_center_id=? and h.pod_id=? " - + " and t.template_id=? and t.download_state=?" ; - - protected static final String DOWNLOADS_STATE= - "SELECT * FROM template_host_ref t " - + " where t.template_id=? and t.download_state=?"; - - public VMTemplateHostDaoImpl () { - HostSearch = createSearchBuilder(); - HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostSearch.done(); - - TemplateSearch = createSearchBuilder(); - TemplateSearch.and("template_id", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateSearch.and("destroyed", TemplateSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - TemplateSearch.done(); - - HostTemplateSearch = createSearchBuilder(); - HostTemplateSearch.and("host_id", HostTemplateSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostTemplateSearch.and("template_id", HostTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + protected static final String UPDATE_TEMPLATE_HOST_REF = "UPDATE template_host_ref SET download_state = ?, download_pct= ?, last_updated = ? " + + ", error_str = ?, local_path = ?, job_id = ? " + "WHERE host_id = ? and type_id = ?"; + + protected static final String DOWNLOADS_STATE_DC = "SELECT t.id, t.host_id, t.template_id, t.created, t.last_updated, t.job_id, " + + "t.download_pct, t.size, t.physical_size, t.download_state, t.error_str, t.local_path, " + + "t.install_path, t.url, t.destroyed, t.is_copy FROM template_host_ref t, host h " + + "where t.host_id = h.id and h.data_center_id=? " + " and t.template_id=? and t.download_state = ?"; + + protected static final String DOWNLOADS_STATE_DC_POD = "SELECT * FROM template_host_ref t, host h where t.host_id = h.id and h.data_center_id=? and h.pod_id=? " + + " and t.template_id=? and t.download_state=?"; + + protected static final String DOWNLOADS_STATE = "SELECT * FROM template_host_ref t " + + " where t.template_id=? and t.download_state=?"; + + public VMTemplateHostDaoImpl() { + HostSearch = createSearchBuilder(); + HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostSearch.done(); + + TemplateSearch = createSearchBuilder(); + TemplateSearch.and("template_id", TemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateSearch.and("destroyed", TemplateSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + TemplateSearch.done(); + + HostTemplateSearch = createSearchBuilder(); + HostTemplateSearch.and("host_id", HostTemplateSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostTemplateSearch.and("template_id", HostTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); HostTemplateSearch.and("destroyed", HostTemplateSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); HostTemplateSearch.done(); - - HostDestroyedSearch = createSearchBuilder(); - HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ); - HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - HostDestroyedSearch.done(); - - TemplateStatusSearch = createSearchBuilder(); - TemplateStatusSearch.and("template_id", TemplateStatusSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); - TemplateStatusSearch.and("download_state", TemplateStatusSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); + + HostDestroyedSearch = createSearchBuilder(); + HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); + HostDestroyedSearch.done(); + + TemplateStatusSearch = createSearchBuilder(); + TemplateStatusSearch.and("template_id", TemplateStatusSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateStatusSearch.and("download_state", TemplateStatusSearch.entity().getDownloadState(), + SearchCriteria.Op.EQ); TemplateStatusSearch.and("destroyed", TemplateStatusSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); TemplateStatusSearch.done(); @@ -121,12 +115,14 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase params) throws ConfigurationException { - boolean result = super.configure(name, params); - ZONE_TEMPLATE_SEARCH = createSearchBuilder(); - ZONE_TEMPLATE_SEARCH.and("template_id", ZONE_TEMPLATE_SEARCH.entity().getTemplateId(), SearchCriteria.Op.EQ); - ZONE_TEMPLATE_SEARCH.and("state", ZONE_TEMPLATE_SEARCH.entity().getDownloadState(), SearchCriteria.Op.EQ); - SearchBuilder hostSearch = _hostDao.createSearchBuilder(); - hostSearch.and("zone_id", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - ZONE_TEMPLATE_SEARCH.join("tmplHost", hostSearch, hostSearch.entity().getId(), ZONE_TEMPLATE_SEARCH.entity().getHostId(), JoinBuilder.JoinType.INNER); - ZONE_TEMPLATE_SEARCH.done(); - - LOCAL_SECONDARY_STORAGE_SEARCH = createSearchBuilder(); - LOCAL_SECONDARY_STORAGE_SEARCH.and("template_id", LOCAL_SECONDARY_STORAGE_SEARCH.entity().getTemplateId(), SearchCriteria.Op.EQ); - LOCAL_SECONDARY_STORAGE_SEARCH.and("state", LOCAL_SECONDARY_STORAGE_SEARCH.entity().getDownloadState(), SearchCriteria.Op.EQ); - SearchBuilder localSecondaryHost = _hostDao.createSearchBuilder(); - localSecondaryHost.and("private_ip_address", localSecondaryHost.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ); - localSecondaryHost.and("state", localSecondaryHost.entity().getStatus(), SearchCriteria.Op.EQ); - localSecondaryHost.and("data_center_id", localSecondaryHost.entity().getDataCenterId(), SearchCriteria.Op.EQ); - localSecondaryHost.and("type", localSecondaryHost.entity().getType(), SearchCriteria.Op.EQ); - LOCAL_SECONDARY_STORAGE_SEARCH.join("host", localSecondaryHost, localSecondaryHost.entity().getId(), LOCAL_SECONDARY_STORAGE_SEARCH.entity().getHostId(), JoinBuilder.JoinType.INNER); - LOCAL_SECONDARY_STORAGE_SEARCH.done(); - - return result; - } - @Override - 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); - } - - - @Override - public List listByOnlyTemplateId(long templateId) { - SearchCriteria sc = TemplateSearch.create(); - sc.setParameters("template_id", templateId); - sc.setParameters("destroyed", false); - return listIncludingRemovedBy(sc); - } - - @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); - } - - @Override - public VMTemplateHostVO findByTemplateId(long templateId) { - SearchCriteria sc = HostTemplateSearch.create(); - sc.setParameters("template_id", templateId); - sc.setParameters("destroyed", false); - return findOneIncludingRemovedBy(sc); - } - - @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; - } @Override - public List listByTemplateHostStatus(long templateId, long hostId, VMTemplateHostVO.Status... states) { + public boolean configure(String name, Map params) throws ConfigurationException { + boolean result = super.configure(name, params); + ZONE_TEMPLATE_SEARCH = createSearchBuilder(); + ZONE_TEMPLATE_SEARCH.and("template_id", ZONE_TEMPLATE_SEARCH.entity().getTemplateId(), SearchCriteria.Op.EQ); + ZONE_TEMPLATE_SEARCH.and("state", ZONE_TEMPLATE_SEARCH.entity().getDownloadState(), SearchCriteria.Op.EQ); + SearchBuilder hostSearch = _hostDao.createSearchBuilder(); + hostSearch.and("zone_id", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + ZONE_TEMPLATE_SEARCH.join("tmplHost", hostSearch, hostSearch.entity().getId(), ZONE_TEMPLATE_SEARCH.entity() + .getHostId(), JoinBuilder.JoinType.INNER); + ZONE_TEMPLATE_SEARCH.done(); + + LOCAL_SECONDARY_STORAGE_SEARCH = createSearchBuilder(); + LOCAL_SECONDARY_STORAGE_SEARCH.and("template_id", LOCAL_SECONDARY_STORAGE_SEARCH.entity().getTemplateId(), + SearchCriteria.Op.EQ); + LOCAL_SECONDARY_STORAGE_SEARCH.and("state", LOCAL_SECONDARY_STORAGE_SEARCH.entity().getDownloadState(), + SearchCriteria.Op.EQ); + SearchBuilder localSecondaryHost = _hostDao.createSearchBuilder(); + localSecondaryHost.and("private_ip_address", localSecondaryHost.entity().getPrivateIpAddress(), + SearchCriteria.Op.EQ); + localSecondaryHost.and("state", localSecondaryHost.entity().getStatus(), SearchCriteria.Op.EQ); + localSecondaryHost.and("data_center_id", localSecondaryHost.entity().getDataCenterId(), SearchCriteria.Op.EQ); + localSecondaryHost.and("type", localSecondaryHost.entity().getType(), SearchCriteria.Op.EQ); + LOCAL_SECONDARY_STORAGE_SEARCH.join("host", localSecondaryHost, localSecondaryHost.entity().getId(), + LOCAL_SECONDARY_STORAGE_SEARCH.entity().getHostId(), JoinBuilder.JoinType.INNER); + LOCAL_SECONDARY_STORAGE_SEARCH.done(); + + return result; + } + + @Override + 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); + } + + @Override + public List listByOnlyTemplateId(long templateId) { + SearchCriteria sc = TemplateSearch.create(); + sc.setParameters("template_id", templateId); + sc.setParameters("destroyed", false); + return listIncludingRemovedBy(sc); + } + + @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); + } + + @Override + public VMTemplateHostVO findByTemplateId(long templateId) { + SearchCriteria sc = HostTemplateSearch.create(); + sc.setParameters("template_id", templateId); + sc.setParameters("destroyed", false); + return findOneIncludingRemovedBy(sc); + } + + @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; + } + + @Override + public List listByTemplateHostStatus(long templateId, long hostId, + VMTemplateHostVO.Status... states) { SearchCriteria sc = HostTemplateStateSearch.create(); sc.setParameters("template_id", templateId); sc.setParameters("host_id", hostId); - sc.setParameters("states", (Object[])states); + sc.setParameters("states", (Object[]) states); return search(sc, null); } - - @Override - public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateHostVO.Status downloadState) { + + @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)); + 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; + } 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 boolean templateAvailable(long templateId, long hostId) { + VMTemplateHostVO tmpltHost = findByHostTemplate(hostId, templateId); + if (tmpltHost == null) + return false; - @Override - public List listByTemplateStates(long templateId, VMTemplateHostVO.Status... states) { - SearchCriteria sc = TemplateStatesSearch.create(); - sc.setParameters("states", (Object[])states); - sc.setParameters("template_id", templateId); + 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); - } + } @Override public List listByState(VMTemplateHostVO.Status state) { @@ -324,14 +329,14 @@ 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); - } + } @Override public List listByZoneTemplate(long dcId, long templateId, boolean readyOnly) { @@ -340,61 +345,61 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase listDestroyed(long hostId) { - SearchCriteria sc = HostDestroyedSearch.create(); - sc.setParameters("host_id", hostId); - sc.setParameters("destroyed", true); - return listIncludingRemovedBy(sc); - } - @Override - public VMTemplateHostVO findByHostTemplate(long hostId, long templateId, boolean lock) { - SearchCriteria sc = HostTemplateSearch.create(); - sc.setParameters("host_id", hostId); - sc.setParameters("template_id", templateId); + @Override + public List listDestroyed(long hostId) { + SearchCriteria sc = HostDestroyedSearch.create(); + sc.setParameters("host_id", hostId); + sc.setParameters("destroyed", true); + return listIncludingRemovedBy(sc); + } + + @Override + public VMTemplateHostVO findByHostTemplate(long hostId, long templateId, boolean lock) { + SearchCriteria sc = HostTemplateSearch.create(); + sc.setParameters("host_id", hostId); + sc.setParameters("template_id", templateId); sc.setParameters("destroyed", false); - if (!lock) - return findOneIncludingRemovedBy(sc); - else - return lockOneRandomRow(sc, true); - } - - //Based on computing node host id, and template id, find out the corresponding template_host_ref, assuming local secondary storage and computing node is in the same zone, and private ip - @Override - public VMTemplateHostVO findLocalSecondaryStorageByHostTemplate(long hostId, long templateId) { - HostVO computingHost = _hostDao.findById(hostId); - SearchCriteria sc = LOCAL_SECONDARY_STORAGE_SEARCH.create(); - sc.setJoinParameters("host", "private_ip_address", computingHost.getPrivateIpAddress()); - sc.setJoinParameters("host", "state", com.cloud.host.Status.Up); - sc.setJoinParameters("host", "data_center_id", computingHost.getDataCenterId()); - sc.setJoinParameters("host", "type", Host.Type.LocalSecondaryStorage); - sc.setParameters("template_id", templateId); - sc.setParameters("state", VMTemplateHostVO.Status.DOWNLOADED); + if (!lock) + return findOneIncludingRemovedBy(sc); + else + return lockOneRandomRow(sc, true); + } + + // Based on computing node host id, and template id, find out the + // corresponding template_host_ref, assuming local secondary storage and + // computing node is in the same zone, and private ip + @Override + public VMTemplateHostVO findLocalSecondaryStorageByHostTemplate(long hostId, long templateId) { + HostVO computingHost = _hostDao.findById(hostId); + SearchCriteria sc = LOCAL_SECONDARY_STORAGE_SEARCH.create(); + sc.setJoinParameters("host", "private_ip_address", computingHost.getPrivateIpAddress()); + sc.setJoinParameters("host", "state", com.cloud.host.Status.Up); + sc.setJoinParameters("host", "data_center_id", computingHost.getDataCenterId()); + sc.setJoinParameters("host", "type", Host.Type.LocalSecondaryStorage); + sc.setParameters("template_id", templateId); + sc.setParameters("state", VMTemplateHostVO.Status.DOWNLOADED); sc.setParameters("destroyed", false); - return findOneBy(sc); - } + return findOneBy(sc); + } @Override public void deleteByHost(Long hostId) { List tmpltHosts = listByHostId(hostId); - for (VMTemplateHostVO tmpltHost : tmpltHosts ) { + for (VMTemplateHostVO tmpltHost : tmpltHosts) { remove(tmpltHost.getId()); } } - + @Override - public boolean updateState(State currentState, Event event, - State nextState, DataObjectInStore vo, Object data) { - VMTemplateHostVO templateHost = (VMTemplateHostVO)vo; + public boolean updateState(State currentState, Event event, State nextState, DataObjectInStore vo, Object data) { + VMTemplateHostVO templateHost = (VMTemplateHostVO) vo; Long oldUpdated = templateHost.getUpdatedCount(); Date oldUpdatedTime = templateHost.getUpdated(); - - + SearchCriteria sc = updateStateSearch.create(); sc.setParameters("id", templateHost.getId()); sc.setParameters("state", currentState); @@ -411,14 +416,19 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase 0; diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDao.java b/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDao.java index 501c3ca5cc8..7e6360b8960 100644 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDao.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDao.java @@ -25,25 +25,29 @@ import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface VMTemplatePoolDao extends GenericDao, StateDao { - public List listByPoolId(long id); - - public List listByTemplateId(long templateId); - - public VMTemplateStoragePoolVO findByPoolTemplate(long poolId, long templateId); +public interface VMTemplatePoolDao extends GenericDao, + StateDao { + public List listByPoolId(long id); - public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState); - - public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId); + public List listByTemplateId(long templateId); - public List listByTemplateStatus(long templateId, long datacenterId, VMTemplateStoragePoolVO.Status downloadState); - - public List listByTemplateStatus(long templateId, long datacenterId, long podId, VMTemplateStoragePoolVO.Status downloadState); + public VMTemplateStoragePoolVO findByPoolTemplate(long poolId, long templateId); - public List listByTemplateStates(long templateId, VMTemplateStoragePoolVO.Status ... states); + public List listByTemplateStatus(long templateId, + VMTemplateStoragePoolVO.Status downloadState); - - boolean templateAvailable(long templateId, long poolId); + public List listByTemplateStatus(long templateId, + VMTemplateStoragePoolVO.Status downloadState, long poolId); - public VMTemplateStoragePoolVO findByHostTemplate(Long hostId, Long templateId); + 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/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java index 5f212ebbfea..ba8135b5f32 100644 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java @@ -42,105 +42,104 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; @Component -@Local(value={VMTemplatePoolDao.class}) +@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 final SearchBuilder updateStateSearch; - - 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(); + public static final Logger s_logger = Logger.getLogger(VMTemplatePoolDaoImpl.class.getName()); - 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(); + 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 final SearchBuilder updateStateSearch; + + 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(); + TemplateStatesSearch.and("template_id", TemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + TemplateStatesSearch.and("states", TemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.IN); + TemplateStatesSearch.done(); - updateStateSearch = this.createSearchBuilder(); - updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ); - updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ); - updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ); - updateStateSearch.done(); - } + updateStateSearch = this.createSearchBuilder(); + updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ); + updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ); + updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ); + updateStateSearch.done(); + } - @Override - public List listByPoolId(long id) { - SearchCriteria sc = PoolSearch.create(); - sc.setParameters("pool_id", id); - return listIncludingRemovedBy(sc); - } + @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 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 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) { + 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) { + @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); @@ -148,130 +147,133 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase listByTemplateStatus(long templateId, long datacenterId, VMTemplateStoragePoolVO.Status downloadState) { + @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()) { + 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; + } 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); - } + } @Override - public boolean updateState(State currentState, Event event, - State nextState, DataObjectInStore vo, Object data) { - VMTemplateStoragePoolVO templatePool = (VMTemplateStoragePoolVO)vo; + 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); + } + + @Override + public boolean updateState(State currentState, Event event, State nextState, DataObjectInStore vo, Object data) { + VMTemplateStoragePoolVO templatePool = (VMTemplateStoragePoolVO) vo; Long oldUpdated = templatePool.getUpdatedCount(); Date oldUpdatedTime = templatePool.getUpdated(); - + SearchCriteria sc = updateStateSearch.create(); sc.setParameters("id", templatePool.getId()); sc.setParameters("state", currentState); @@ -288,14 +290,19 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase 0; diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java index 7cfd3b5937c..d49645d944a 100644 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java @@ -34,8 +34,7 @@ import java.util.List; @Component @Local(VMTemplateS3Dao.class) -public class VMTemplateS3DaoImpl extends GenericDaoBase - implements VMTemplateS3Dao { +public class VMTemplateS3DaoImpl extends GenericDaoBase implements VMTemplateS3Dao { private final SearchBuilder searchBuilder; @@ -44,19 +43,15 @@ public class VMTemplateS3DaoImpl extends GenericDaoBase super(); this.searchBuilder = createSearchBuilder(); - this.searchBuilder - .and(S3_ID_COLUMN_NAME, this.searchBuilder.entity().getS3Id(), - EQ) - .and(TEMPLATE_ID_COLUMN_NAME, - this.searchBuilder.entity().getTemplateId(), EQ).done(); + this.searchBuilder.and(S3_ID_COLUMN_NAME, this.searchBuilder.entity().getS3Id(), EQ) + .and(TEMPLATE_ID_COLUMN_NAME, this.searchBuilder.entity().getTemplateId(), EQ).done(); } @Override public List listByS3Id(final long s3id) { - final SearchCriteria criteria = this.searchBuilder - .create(); + final SearchCriteria criteria = this.searchBuilder.create(); criteria.setParameters(S3_ID_COLUMN_NAME, s3id); @@ -67,8 +62,7 @@ public class VMTemplateS3DaoImpl extends GenericDaoBase @Override public VMTemplateS3VO findOneByTemplateId(final long templateId) { - final SearchCriteria criteria = this.searchBuilder - .create(); + final SearchCriteria criteria = this.searchBuilder.create(); criteria.setParameters(TEMPLATE_ID_COLUMN_NAME, templateId); @@ -77,11 +71,9 @@ public class VMTemplateS3DaoImpl extends GenericDaoBase } @Override - public VMTemplateS3VO findOneByS3Template(final long s3Id, - final long templateId) { + public VMTemplateS3VO findOneByS3Template(final long s3Id, final long templateId) { - final SearchCriteria criteria = this.searchBuilder - .create(); + final SearchCriteria criteria = this.searchBuilder.create(); criteria.setParameters(S3_ID_COLUMN_NAME, s3Id); criteria.setParameters(TEMPLATE_ID_COLUMN_NAME, templateId); @@ -93,8 +85,7 @@ public class VMTemplateS3DaoImpl extends GenericDaoBase @Override public void expungeAllByTemplateId(long templateId) { - final SearchCriteria criteria = this.searchBuilder - .create(); + final SearchCriteria criteria = this.searchBuilder.create(); criteria.setParameters(TEMPLATE_ID_COLUMN_NAME, templateId); diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDao.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDao.java index 27e05c92e3d..67f7c3f64d7 100755 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDao.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDao.java @@ -22,11 +22,11 @@ import com.cloud.storage.VMTemplateZoneVO; import com.cloud.utils.db.GenericDao; public interface VMTemplateZoneDao extends GenericDao { - public List listByZoneId(long id); + public List listByZoneId(long id); - public List listByTemplateId(long templateId); + public List listByTemplateId(long templateId); - public VMTemplateZoneVO findByZoneTemplate(long zoneId, long templateId); + public VMTemplateZoneVO findByZoneTemplate(long zoneId, long templateId); public List listByZoneTemplate(Long zoneId, long templateId); diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java index 27b554cdb8a..c4a4dc7230a 100644 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java @@ -20,7 +20,6 @@ import java.util.List; import javax.ejb.Local; -import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -31,63 +30,60 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @Component -@Local(value={VMTemplateZoneDao.class}) +@Local(value = { VMTemplateZoneDao.class }) public class VMTemplateZoneDaoImpl extends GenericDaoBase implements VMTemplateZoneDao { - public static final Logger s_logger = Logger.getLogger(VMTemplateZoneDaoImpl.class.getName()); + public static final Logger s_logger = Logger.getLogger(VMTemplateZoneDaoImpl.class.getName()); - protected final SearchBuilder ZoneSearch; - protected final SearchBuilder TemplateSearch; - protected final SearchBuilder ZoneTemplateSearch; + 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(); - 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(); - 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(); + } - 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 List listByZoneId(long id) { - SearchCriteria sc = ZoneSearch.create(); - sc.setParameters("zone_id", id); - 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 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 + @Override public List listByZoneTemplate(Long zoneId, long templateId) { - SearchCriteria sc = ZoneTemplateSearch.create(); + 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); + } @Override public void deletePrimaryRecordsForTemplate(long templateId) { @@ -100,5 +96,4 @@ public class VMTemplateZoneDaoImpl extends GenericDaoBase, StateDao findUsableVolumesForInstance(long instanceId); - Long countAllocatedVolumesForAccount(long accountId); + Long countAllocatedVolumesForAccount(long accountId); HypervisorType getHypervisorType(long volumeId); @@ -76,15 +76,16 @@ public interface VolumeDao extends GenericDao, StateDao implements VolumeDao { private static final Logger s_logger = Logger.getLogger(VolumeDaoImpl.class); protected final SearchBuilder DetachedAccountIdSearch; @@ -63,23 +63,23 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol protected GenericSearchBuilder CountByAccount; protected GenericSearchBuilder primaryStorageSearch; protected GenericSearchBuilder secondaryStorageSearch; - @Inject ResourceTagDao _tagsDao; + @Inject + ResourceTagDao _tagsDao; protected static final String SELECT_VM_SQL = "SELECT DISTINCT instance_id from volumes v where v.host_id = ? and v.mirror_state = ?"; protected static final String SELECT_HYPERTYPE_FROM_VOLUME = "SELECT c.hypervisor_type from volumes v, storage_pool s, cluster c where v.pool_id = s.id and s.cluster_id = c.id and v.id = ?"; - private static final String ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT = "SELECT pool.id, SUM(IF(vol.state='Ready' AND vol.account_id = ?, 1, 0)) FROM `cloud`.`storage_pool` pool LEFT JOIN `cloud`.`volumes` vol ON pool.id = vol.pool_id WHERE pool.data_center_id = ? " + - " AND pool.pod_id = ? AND pool.cluster_id = ? " + - " GROUP BY pool.id ORDER BY 2 ASC "; - + private static final String ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT = "SELECT pool.id, SUM(IF(vol.state='Ready' AND vol.account_id = ?, 1, 0)) FROM `cloud`.`storage_pool` pool LEFT JOIN `cloud`.`volumes` vol ON pool.id = vol.pool_id WHERE pool.data_center_id = ? " + + " AND pool.pod_id = ? AND pool.cluster_id = ? " + " GROUP BY pool.id ORDER BY 2 ASC "; + @Override public List findDetachedByAccount(long accountId) { - SearchCriteria sc = DetachedAccountIdSearch.create(); - sc.setParameters("accountId", accountId); - sc.setParameters("destroyed", Volume.State.Destroy); - return listBy(sc); + SearchCriteria sc = DetachedAccountIdSearch.create(); + sc.setParameters("accountId", accountId); + sc.setParameters("destroyed", Volume.State.Destroy); + return listBy(sc); } - + @Override public List findByAccount(long accountId) { SearchCriteria sc = AllFieldsSearch.create(); @@ -87,172 +87,172 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol sc.setParameters("state", Volume.State.Ready); return listBy(sc); } - + @Override public List findByInstance(long id) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("instanceId", id); - return listBy(sc); - } - - @Override - public List findByInstanceAndDeviceId(long instanceId, long deviceId){ - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("instanceId", instanceId); - sc.setParameters("deviceId", deviceId); - return listBy(sc); + return listBy(sc); } - + + @Override + public List findByInstanceAndDeviceId(long instanceId, long deviceId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("instanceId", instanceId); + sc.setParameters("deviceId", deviceId); + return listBy(sc); + } + @Override public List findByPoolId(long poolId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("poolId", poolId); sc.setParameters("notDestroyed", Volume.State.Destroy); sc.setParameters("vType", Volume.Type.ROOT.toString()); - return listBy(sc); - } - - @Override + return listBy(sc); + } + + @Override public List findCreatedByInstance(long id) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("instanceId", id); sc.setParameters("state", Volume.State.Ready); return listBy(sc); } - + @Override public List findUsableVolumesForInstance(long instanceId) { SearchCriteria sc = InstanceStatesSearch.create(); sc.setParameters("instance", instanceId); sc.setParameters("states", Volume.State.Creating, Volume.State.Ready, Volume.State.Allocated); - + return listBy(sc); } - - @Override - public List findByInstanceAndType(long id, Type vType) { + + @Override + public List findByInstanceAndType(long id, Type vType) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("instanceId", id); sc.setParameters("vType", vType.toString()); - return listBy(sc); - } - - @Override - public List findByInstanceIdDestroyed(long vmId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("instanceId", vmId); - sc.setParameters("destroyed", Volume.State.Destroy); - return listBy(sc); - } - - @Override - public List findReadyRootVolumesByInstance(long instanceId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("instanceId", instanceId); - sc.setParameters("state", Volume.State.Ready); - sc.setParameters("vType", Volume.Type.ROOT); - return listBy(sc); - } - - @Override - public List findByAccountAndPod(long accountId, long podId) { - SearchCriteria sc = AllFieldsSearch.create(); + return listBy(sc); + } + + @Override + public List findByInstanceIdDestroyed(long vmId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("instanceId", vmId); + sc.setParameters("destroyed", Volume.State.Destroy); + return listBy(sc); + } + + @Override + public List findReadyRootVolumesByInstance(long instanceId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("instanceId", instanceId); + sc.setParameters("state", Volume.State.Ready); + sc.setParameters("vType", Volume.Type.ROOT); + return listBy(sc); + } + + @Override + public List findByAccountAndPod(long accountId, long podId) { + SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("accountId", accountId); sc.setParameters("pod", podId); sc.setParameters("state", Volume.State.Ready); - - return listIncludingRemovedBy(sc); - } - - @Override - public List findByTemplateAndZone(long templateId, long zoneId) { - SearchCriteria sc = TemplateZoneSearch.create(); - sc.setParameters("template", templateId); - sc.setParameters("zone", zoneId); - - return listIncludingRemovedBy(sc); - } - @Override - public boolean isAnyVolumeActivelyUsingTemplateOnPool(long templateId, long poolId) { - SearchCriteria sc = ActiveTemplateSearch.create(); - sc.setParameters("template", templateId); - sc.setParameters("pool", poolId); - - List results = customSearchIncludingRemoved(sc, null); - assert results.size() > 0 : "How can this return a size of " + results.size(); - - return results.get(0) > 0; - } - + return listIncludingRemovedBy(sc); + } + + @Override + public List findByTemplateAndZone(long templateId, long zoneId) { + SearchCriteria sc = TemplateZoneSearch.create(); + sc.setParameters("template", templateId); + sc.setParameters("zone", zoneId); + + return listIncludingRemovedBy(sc); + } + + @Override + public boolean isAnyVolumeActivelyUsingTemplateOnPool(long templateId, long poolId) { + SearchCriteria sc = ActiveTemplateSearch.create(); + sc.setParameters("template", templateId); + sc.setParameters("pool", poolId); + + List results = customSearchIncludingRemoved(sc, null); + assert results.size() > 0 : "How can this return a size of " + results.size(); + + return results.get(0) > 0; + } + @Override public void deleteVolumesByInstance(long instanceId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("instanceId", instanceId); expunge(sc); } - + @Override public void attachVolume(long volumeId, long vmId, long deviceId) { - VolumeVO volume = createForUpdate(volumeId); - volume.setInstanceId(vmId); - volume.setDeviceId(deviceId); - volume.setUpdated(new Date()); - volume.setAttached(new Date()); - update(volumeId, volume); + VolumeVO volume = createForUpdate(volumeId); + volume.setInstanceId(vmId); + volume.setDeviceId(deviceId); + volume.setUpdated(new Date()); + volume.setAttached(new Date()); + update(volumeId, volume); } - + @Override public void detachVolume(long volumeId) { - VolumeVO volume = createForUpdate(volumeId); - volume.setInstanceId(null); + VolumeVO volume = createForUpdate(volumeId); + volume.setInstanceId(null); volume.setDeviceId(null); - volume.setUpdated(new Date()); - volume.setAttached(null); - update(volumeId, volume); + volume.setUpdated(new Date()); + volume.setAttached(null); + update(volumeId, volume); } - + @Override @DB - public HypervisorType getHypervisorType(long volumeId) { - /*lookup from cluster of pool*/ - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; + public HypervisorType getHypervisorType(long volumeId) { + /* lookup from cluster of pool */ + Transaction txn = Transaction.currentTxn(); + PreparedStatement pstmt = null; - try { - String sql = SELECT_HYPERTYPE_FROM_VOLUME; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, volumeId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { + try { + String sql = SELECT_HYPERTYPE_FROM_VOLUME; + pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, volumeId); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { return HypervisorType.getType(rs.getString(1)); } - return HypervisorType.None; - } catch (SQLException e) { - throw new CloudRuntimeException("DB Exception on: " + SELECT_HYPERTYPE_FROM_VOLUME, e); - } catch (Throwable e) { - throw new CloudRuntimeException("Caught: " + SELECT_HYPERTYPE_FROM_VOLUME, e); - } - } - + return HypervisorType.None; + } catch (SQLException e) { + throw new CloudRuntimeException("DB Exception on: " + SELECT_HYPERTYPE_FROM_VOLUME, e); + } catch (Throwable e) { + throw new CloudRuntimeException("Caught: " + SELECT_HYPERTYPE_FROM_VOLUME, e); + } + } + @Override public ImageFormat getImageFormat(Long volumeId) { HypervisorType type = getHypervisorType(volumeId); - if ( type.equals(HypervisorType.KVM)) { + if (type.equals(HypervisorType.KVM)) { return ImageFormat.QCOW2; - } else if ( type.equals(HypervisorType.XenServer)) { + } else if (type.equals(HypervisorType.XenServer)) { return ImageFormat.VHD; - } else if ( type.equals(HypervisorType.VMware)) { + } else if (type.equals(HypervisorType.VMware)) { return ImageFormat.OVA; } else { s_logger.warn("Do not support hypervisor " + type.toString()); return null; } } - - public VolumeDaoImpl() { - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ); + + public VolumeDaoImpl() { + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ); AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), Op.EQ); AllFieldsSearch.and("pod", AllFieldsSearch.entity().getPodId(), Op.EQ); AllFieldsSearch.and("instanceId", AllFieldsSearch.entity().getInstanceId(), Op.EQ); @@ -264,33 +264,33 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol AllFieldsSearch.and("notDestroyed", AllFieldsSearch.entity().getState(), Op.NEQ); AllFieldsSearch.and("updatedCount", AllFieldsSearch.entity().getUpdatedCount(), Op.EQ); AllFieldsSearch.done(); - + DetachedAccountIdSearch = createSearchBuilder(); DetachedAccountIdSearch.and("accountId", DetachedAccountIdSearch.entity().getAccountId(), Op.EQ); DetachedAccountIdSearch.and("destroyed", DetachedAccountIdSearch.entity().getState(), Op.NEQ); DetachedAccountIdSearch.and("instanceId", DetachedAccountIdSearch.entity().getInstanceId(), Op.NULL); DetachedAccountIdSearch.done(); - + TemplateZoneSearch = createSearchBuilder(); TemplateZoneSearch.and("template", TemplateZoneSearch.entity().getTemplateId(), Op.EQ); TemplateZoneSearch.and("zone", TemplateZoneSearch.entity().getDataCenterId(), Op.EQ); TemplateZoneSearch.done(); - + TotalSizeByPoolSearch = createSearchBuilder(SumCount.class); TotalSizeByPoolSearch.select("sum", Func.SUM, TotalSizeByPoolSearch.entity().getSize()); - TotalSizeByPoolSearch.select("count", Func.COUNT, (Object[])null); + TotalSizeByPoolSearch.select("count", Func.COUNT, (Object[]) null); TotalSizeByPoolSearch.and("poolId", TotalSizeByPoolSearch.entity().getPoolId(), Op.EQ); TotalSizeByPoolSearch.and("removed", TotalSizeByPoolSearch.entity().getRemoved(), Op.NULL); TotalSizeByPoolSearch.and("state", TotalSizeByPoolSearch.entity().getState(), Op.NEQ); TotalSizeByPoolSearch.done(); - + ActiveTemplateSearch = createSearchBuilder(Long.class); ActiveTemplateSearch.and("pool", ActiveTemplateSearch.entity().getPoolId(), Op.EQ); ActiveTemplateSearch.and("template", ActiveTemplateSearch.entity().getTemplateId(), Op.EQ); ActiveTemplateSearch.and("removed", ActiveTemplateSearch.entity().getRemoved(), Op.NULL); ActiveTemplateSearch.select(null, Func.COUNT, null); ActiveTemplateSearch.done(); - + InstanceStatesSearch = createSearchBuilder(); InstanceStatesSearch.and("instance", InstanceStatesSearch.entity().getInstanceId(), Op.EQ); InstanceStatesSearch.and("states", InstanceStatesSearch.entity().getState(), Op.IN); @@ -315,24 +315,25 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol secondaryStorageSearch.and("path", secondaryStorageSearch.entity().getPath(), Op.NULL); secondaryStorageSearch.and("isRemoved", secondaryStorageSearch.entity().getRemoved(), Op.NULL); secondaryStorageSearch.done(); - } + } - @Override @DB(txn=false) - public Pair getCountAndTotalByPool(long poolId) { + @Override + @DB(txn = false) + public Pair getCountAndTotalByPool(long poolId) { SearchCriteria sc = TotalSizeByPoolSearch.create(); sc.setParameters("poolId", poolId); List results = customSearch(sc, null); SumCount sumCount = results.get(0); return new Pair(sumCount.count, sumCount.sum); - } + } @Override - public Long countAllocatedVolumesForAccount(long accountId) { - SearchCriteria sc = CountByAccount.create(); + public Long countAllocatedVolumesForAccount(long accountId) { + SearchCriteria sc = CountByAccount.create(); sc.setParameters("account", accountId); - sc.setParameters("state", Volume.State.Destroy); + sc.setParameters("state", Volume.State.Destroy); return customSearch(sc, null).get(0); - } + } @Override public long primaryStorageUsedForAccount(long accountId) { @@ -358,55 +359,61 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol } } + public static class SumCount { + public long sum; + public long count; - public static class SumCount { - public long sum; - public long count; - public SumCount() { - } - } + public SumCount() { + } + } @Override public List listVolumesToBeDestroyed() { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("state", Volume.State.Destroy); - + return listBy(sc); } - @Override - public boolean updateState(com.cloud.storage.Volume.State currentState, - Event event, com.cloud.storage.Volume.State nextState, Volume vo, - Object data) { - - Long oldUpdated = vo.getUpdatedCount(); - Date oldUpdatedTime = vo.getUpdated(); - - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("id", vo.getId()); - sc.setParameters("state", currentState); - sc.setParameters("updatedCount", vo.getUpdatedCount()); - - vo.incrUpdatedCount(); - - UpdateBuilder builder = getUpdateBuilder(vo); - builder.set(vo, "state", nextState); - builder.set(vo, "updated", new Date()); - - int rows = update((VolumeVO)vo, sc); - if (rows == 0 && s_logger.isDebugEnabled()) { - VolumeVO dbVol = findByIdIncludingRemoved(vo.getId()); - if (dbVol != null) { - StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); - str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=").append(dbVol.getUpdated()); - str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()).append("; updatedTime=").append(vo.getUpdated()); - str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated).append("; updatedTime=").append(oldUpdatedTime); - } else { - s_logger.debug("Unable to update volume: id=" + vo.getId() + ", as there is no such volume exists in the database anymore"); - } - } - return rows > 0; - } + @Override + public boolean updateState(com.cloud.storage.Volume.State currentState, Event event, + com.cloud.storage.Volume.State nextState, Volume vo, Object data) { + + Long oldUpdated = vo.getUpdatedCount(); + Date oldUpdatedTime = vo.getUpdated(); + + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("id", vo.getId()); + sc.setParameters("state", currentState); + sc.setParameters("updatedCount", vo.getUpdatedCount()); + + vo.incrUpdatedCount(); + + UpdateBuilder builder = getUpdateBuilder(vo); + builder.set(vo, "state", nextState); + builder.set(vo, "updated", new Date()); + + int rows = update((VolumeVO) vo, sc); + if (rows == 0 && s_logger.isDebugEnabled()) { + VolumeVO dbVol = findByIdIncludingRemoved(vo.getId()); + if (dbVol != null) { + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()) + .append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=") + .append(dbVol.getUpdated()); + str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState) + .append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()) + .append("; updatedTime=").append(vo.getUpdated()); + str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState) + .append("; event=").append(event).append("; updatecount=").append(oldUpdated) + .append("; updatedTime=").append(oldUpdatedTime); + } else { + s_logger.debug("Unable to update volume: id=" + vo.getId() + + ", as there is no such volume exists in the database anymore"); + } + } + return rows > 0; + } @Override public List listPoolIdsByVolumeCount(long dcId, Long podId, Long clusterId, long accountId) { @@ -420,7 +427,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol pstmt.setLong(2, dcId); pstmt.setLong(3, podId); pstmt.setLong(4, clusterId); - + ResultSet rs = pstmt.executeQuery(); while (rs.next()) { result.add(rs.getLong(1)); @@ -432,8 +439,9 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol throw new CloudRuntimeException("Caught: " + ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT, e); } } - - @Override @DB(txn=false) + + @Override + @DB(txn = false) public Pair getNonDestroyedCountAndTotalByPool(long poolId) { SearchCriteria sc = TotalSizeByPoolSearch.create(); sc.setParameters("poolId", poolId); @@ -442,7 +450,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol SumCount sumCount = results.get(0); return new Pair(sumCount.count, sumCount.sum); } - + @Override @DB public boolean remove(Long id) { diff --git a/engine/schema/src/com/cloud/storage/dao/VolumeHostDao.java b/engine/schema/src/com/cloud/storage/dao/VolumeHostDao.java index 39dda12345b..ccb276b47f9 100755 --- a/engine/schema/src/com/cloud/storage/dao/VolumeHostDao.java +++ b/engine/schema/src/com/cloud/storage/dao/VolumeHostDao.java @@ -25,16 +25,17 @@ import com.cloud.storage.VolumeHostVO; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface VolumeHostDao extends GenericDao, StateDao{ +public interface VolumeHostDao extends GenericDao, + StateDao { - VolumeHostVO findByHostVolume(long hostId, long volumeId); + VolumeHostVO findByHostVolume(long hostId, long volumeId); - VolumeHostVO findByVolumeId(long volumeId); + VolumeHostVO findByVolumeId(long volumeId); - List listBySecStorage(long sserverId); + List listBySecStorage(long sserverId); - List listDestroyed(long hostId); + List listDestroyed(long hostId); - VolumeHostVO findVolumeByZone(long zoneId, long volumeId); + VolumeHostVO findVolumeByZone(long zoneId, long volumeId); } diff --git a/engine/schema/src/com/cloud/storage/dao/VolumeHostDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VolumeHostDaoImpl.java index 2fd39e6eeca..b731ebbeb4e 100755 --- a/engine/schema/src/com/cloud/storage/dao/VolumeHostDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VolumeHostDaoImpl.java @@ -35,7 +35,7 @@ import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.UpdateBuilder; @Component -@Local(value={VolumeHostDao.class}) +@Local(value = { VolumeHostDao.class }) public class VolumeHostDaoImpl extends GenericDaoBase implements VolumeHostDao { private static final Logger s_logger = Logger.getLogger(VolumeHostDaoImpl.class); protected final SearchBuilder HostVolumeSearch; @@ -44,7 +44,8 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem protected final SearchBuilder HostSearch; protected final SearchBuilder HostDestroyedSearch; protected final SearchBuilder updateStateSearch; - public VolumeHostDaoImpl(){ + + public VolumeHostDaoImpl() { HostVolumeSearch = createSearchBuilder(); HostVolumeSearch.and("host_id", HostVolumeSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostVolumeSearch.and("volume_id", HostVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); @@ -58,7 +59,7 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem ZoneVolumeSearch.done(); HostSearch = createSearchBuilder(); - HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostSearch.and("host_id", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostSearch.and("destroyed", HostSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); HostSearch.done(); @@ -70,8 +71,8 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem HostDestroyedSearch = createSearchBuilder(); HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ); - HostDestroyedSearch.done(); - + HostDestroyedSearch.done(); + updateStateSearch = this.createSearchBuilder(); updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ); updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ); @@ -79,8 +80,6 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem updateStateSearch.done(); } - - @Override public VolumeHostVO findByHostVolume(long hostId, long volumeId) { SearchCriteria sc = HostVolumeSearch.create(); @@ -88,7 +87,7 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem sc.setParameters("volume_id", volumeId); sc.setParameters("destroyed", false); return findOneIncludingRemovedBy(sc); - } + } @Override public VolumeHostVO findVolumeByZone(long volumeId, long zoneId) { @@ -107,8 +106,6 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem return findOneBy(sc); } - - @Override public List listBySecStorage(long ssHostId) { SearchCriteria sc = HostSearch.create(); @@ -118,7 +115,7 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem } @Override - public List listDestroyed(long hostId){ + public List listDestroyed(long hostId) { SearchCriteria sc = HostDestroyedSearch.create(); sc.setParameters("host_id", hostId); sc.setParameters("destroyed", true); @@ -126,13 +123,11 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem } @Override - public boolean updateState(State currentState, Event event, - State nextState, DataObjectInStore vo, Object data) { + public boolean updateState(State currentState, Event event, State nextState, DataObjectInStore vo, Object data) { VolumeHostVO volHost = (VolumeHostVO) vo; Long oldUpdated = volHost.getUpdatedCount(); Date oldUpdatedTime = volHost.getUpdated(); - - + SearchCriteria sc = updateStateSearch.create(); sc.setParameters("id", volHost.getId()); sc.setParameters("state", currentState); @@ -149,14 +144,18 @@ public class VolumeHostDaoImpl extends GenericDaoBase implem VolumeHostVO dbVol = findByIdIncludingRemoved(volHost.getId()); if (dbVol != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); - str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=") + str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()) + .append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=") .append(dbVol.getUpdated()); - str.append(": New Data={id=").append(volHost.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(volHost.getUpdatedCount()) + str.append(": New Data={id=").append(volHost.getId()).append("; state=").append(nextState) + .append("; event=").append(event).append("; updatecount=").append(volHost.getUpdatedCount()) .append("; updatedTime=").append(volHost.getUpdated()); - str.append(": stale Data={id=").append(volHost.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated) + str.append(": stale Data={id=").append(volHost.getId()).append("; state=").append(currentState) + .append("; event=").append(event).append("; updatecount=").append(oldUpdated) .append("; updatedTime=").append(oldUpdatedTime); } else { - s_logger.debug("Unable to update objectIndatastore: id=" + volHost.getId() + ", as there is no such object exists in the database anymore"); + s_logger.debug("Unable to update objectIndatastore: id=" + volHost.getId() + + ", as there is no such object exists in the database anymore"); } } return rows > 0; diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/allocator/StorageCacheRandomAllocator.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/allocator/StorageCacheRandomAllocator.java index f8232b8987a..f244a0371b7 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/allocator/StorageCacheRandomAllocator.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/allocator/StorageCacheRandomAllocator.java @@ -18,6 +18,7 @@ */ package org.apache.cloudstack.storage.cache.allocator; +import java.util.Collections; import java.util.List; import javax.inject.Inject; @@ -30,27 +31,25 @@ import org.springframework.stereotype.Component; import com.cloud.storage.ScopeType; -import edu.emory.mathcs.backport.java.util.Collections; - @Component public class StorageCacheRandomAllocator implements StorageCacheAllocator { - private static final Logger s_logger = Logger - .getLogger(StorageCacheRandomAllocator.class); + private static final Logger s_logger = Logger.getLogger(StorageCacheRandomAllocator.class); @Inject DataStoreManager dataStoreMgr; + @Override public DataStore getCacheStore(Scope scope) { if (scope.getScopeType() != ScopeType.ZONE) { s_logger.debug("Can only support zone wide cache storage"); return null; } - + List cacheStores = dataStoreMgr.getImageCacheStores(scope); if (cacheStores.size() <= 0) { s_logger.debug("Can't find cache storage in zone: " + scope.getScopeId()); return null; } - + Collections.shuffle(cacheStores); return cacheStores.get(0); } diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java index d2895fdf377..cb5ea106fed 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java @@ -39,16 +39,14 @@ import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.framework.async.AsyncRpcConext; import org.apache.cloudstack.storage.cache.allocator.StorageCacheAllocator; -import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.command.CopyCmdAnswer; import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager; import org.apache.log4j.Logger; import com.cloud.utils.component.Manager; +import com.cloud.utils.exception.CloudRuntimeException; public class StorageCacheManagerImpl implements StorageCacheManager, Manager { - private static final Logger s_logger = Logger - .getLogger(StorageCacheManagerImpl.class); + private static final Logger s_logger = Logger.getLogger(StorageCacheManagerImpl.class); @Inject List storageCacheAllocator; @Inject @@ -120,10 +118,9 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { return true; } - - private class CreateCacheObjectContext extends AsyncRpcConext { final AsyncCallFuture future; + /** * @param callback */ @@ -134,48 +131,47 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { } - @Override - public DataObject createCacheObject(DataObject data, Scope scope) { - DataStore cacheStore = this.getCacheStorage(scope); - DataObjectInStore obj = objectInStoreMgr.findObject(data, cacheStore); - if (obj != null && obj.getState() == ObjectInDataStoreStateMachine.State.Ready) { - s_logger.debug("there is already one in the cache store"); - return objectInStoreMgr.get(data, cacheStore); - } + @Override + public DataObject createCacheObject(DataObject data, Scope scope) { + DataStore cacheStore = this.getCacheStorage(scope); + DataObjectInStore obj = objectInStoreMgr.findObject(data, cacheStore); + if (obj != null && obj.getState() == ObjectInDataStoreStateMachine.State.Ready) { + s_logger.debug("there is already one in the cache store"); + return objectInStoreMgr.get(data, cacheStore); + } - //TODO: consider multiple thread to create - DataObject objOnCacheStore = cacheStore.create(data); + DataObject objOnCacheStore = cacheStore.create(data); - AsyncCallFuture future = new AsyncCallFuture(); - CopyCommandResult result = null; - try { - objOnCacheStore.processEvent(Event.CreateOnlyRequested); + AsyncCallFuture future = new AsyncCallFuture(); + CopyCommandResult result = null; + try { + objOnCacheStore.processEvent(Event.CreateOnlyRequested); - dataMotionSvr.copyAsync(data, objOnCacheStore, future); - result = future.get(); + dataMotionSvr.copyAsync(data, objOnCacheStore, future); + result = future.get(); - if (result.isFailed()) { - objOnCacheStore.processEvent(Event.OperationFailed); - } else { - objOnCacheStore.processEvent(Event.OperationSuccessed, result.getAnswer()); - return objOnCacheStore; - } + if (result.isFailed()) { + objOnCacheStore.processEvent(Event.OperationFailed); + } else { + objOnCacheStore.processEvent(Event.OperationSuccessed, result.getAnswer()); + return objOnCacheStore; + } } catch (InterruptedException e) { s_logger.debug("create cache storage failed: " + e.toString()); + throw new CloudRuntimeException(e); } catch (ExecutionException e) { s_logger.debug("create cache storage failed: " + e.toString()); - } catch (Exception e) { - s_logger.debug("create cache storage failed: " + e.toString()); + throw new CloudRuntimeException(e); } finally { if (result == null) { objOnCacheStore.processEvent(Event.OperationFailed); } } - return null; - } + return null; + } - @Override + @Override public DataObject getCacheObject(DataObject data, Scope scope) { DataStore cacheStore = this.getCacheStorage(scope); DataObject objOnCacheStore = cacheStore.create(data); @@ -183,12 +179,13 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { return objOnCacheStore; } - protected Void createCacheObjectCallBack(AsyncCallbackDispatcher callback, - CreateCacheObjectContext context) { - AsyncCallFuture future = context.future; - future.complete(callback.getResult()); - return null; - } + protected Void createCacheObjectCallBack( + AsyncCallbackDispatcher callback, + CreateCacheObjectContext context) { + AsyncCallFuture future = context.future; + future.complete(callback.getResult()); + return null; + } @Override public boolean deleteCacheObject(DataObject data) { diff --git a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java index 65beb40c475..a01d2d30139 100644 --- a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java +++ b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java @@ -23,30 +23,29 @@ import java.util.Map; import javax.inject.Inject; import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionStrategy; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; -import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.command.CopyCmdAnswer; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataObjectType; @@ -56,11 +55,9 @@ import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.dao.HostDao; import com.cloud.storage.DataStoreRole; -import com.cloud.storage.ImageStore; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; import com.cloud.storage.VolumeManager; @@ -77,8 +74,7 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class AncientDataMotionStrategy implements DataMotionStrategy { - private static final Logger s_logger = Logger - .getLogger(AncientDataMotionStrategy.class); + private static final Logger s_logger = Logger.getLogger(AncientDataMotionStrategy.class); @Inject EndPointSelector selector; @Inject @@ -107,8 +103,10 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { DataStoreManager dataStoreMgr; @Inject TemplateDataStoreDao templateStoreDao; - @Inject DiskOfferingDao diskOfferingDao; - @Inject VMTemplatePoolDao templatePoolDao; + @Inject + DiskOfferingDao diskOfferingDao; + @Inject + VMTemplatePoolDao templatePoolDao; @Inject VolumeManager volumeMgr; @Inject @@ -125,7 +123,6 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { return false; } - protected boolean needCacheStorage(DataObject srcData, DataObject destData) { DataTO srcTO = srcData.getTO(); DataTO destTO = destData.getTO(); @@ -140,9 +137,9 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } return true; } - + private Scope getZoneScope(Scope destScope) { - ZoneScope zoneScope = null; + ZoneScope zoneScope = null; if (destScope instanceof ClusterScope) { ClusterScope clusterScope = (ClusterScope) destScope; zoneScope = new ZoneScope(clusterScope.getZoneId()); @@ -150,14 +147,15 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { HostScope hostScope = (HostScope) destScope; zoneScope = new ZoneScope(hostScope.getZoneId()); } else { - zoneScope = (ZoneScope)destScope; + zoneScope = (ZoneScope) destScope; } return zoneScope; } protected Answer copyObject(DataObject srcData, DataObject destData) { String value = configDao.getValue(Config.PrimaryStorageDownloadWait.toString()); - int _primaryStorageDownloadWait = NumbersUtil.parseInt(value, Integer.parseInt(Config.PrimaryStorageDownloadWait.getDefaultValue())); + int _primaryStorageDownloadWait = NumbersUtil.parseInt(value, + Integer.parseInt(Config.PrimaryStorageDownloadWait.getDefaultValue())); Answer answer = null; DataObject cacheData = null; try { @@ -193,7 +191,7 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { protected DataObject cacheSnapshotChain(SnapshotInfo snapshot) { DataObject leafData = null; - while(snapshot != null) { + while (snapshot != null) { DataObject cacheData = cacheMgr.createCacheObject(snapshot, snapshot.getDataStore().getScope()); if (leafData == null) { leafData = cacheData; @@ -208,11 +206,10 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } protected Answer copyVolumeFromSnapshot(DataObject snapObj, DataObject volObj) { - SnapshotInfo snapshot = (SnapshotInfo)snapObj; + SnapshotInfo snapshot = (SnapshotInfo) snapObj; StoragePool pool = (StoragePool) volObj.getDataStore(); - String basicErrMsg = "Failed to create volume from " - + snapshot.getName() + " on pool " + pool; + String basicErrMsg = "Failed to create volume from " + snapshot.getName() + " on pool " + pool; DataStore store = snapObj.getDataStore(); DataStoreTO storTO = store.getTO(); DataObject srcData = snapObj; @@ -221,23 +218,21 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { srcData = cacheSnapshotChain(snapshot); } - String value = configDao - .getValue(Config.CreateVolumeFromSnapshotWait.toString()); + String value = configDao.getValue(Config.CreateVolumeFromSnapshotWait.toString()); int _createVolumeFromSnapshotWait = NumbersUtil.parseInt(value, - Integer.parseInt(Config.CreateVolumeFromSnapshotWait - .getDefaultValue())); + Integer.parseInt(Config.CreateVolumeFromSnapshotWait.getDefaultValue())); CopyCommand cmd = new CopyCommand(srcData.getTO(), volObj.getTO(), _createVolumeFromSnapshotWait); EndPoint ep = selector.select(snapObj, volObj); Answer answer = ep.sendMessage(cmd); - return answer; + return answer; } catch (Exception e) { s_logger.error(basicErrMsg, e); throw new CloudRuntimeException(basicErrMsg); } finally { if (!(storTO instanceof NfsTO)) { - deleteSnapshotCacheChain((SnapshotInfo)srcData); + deleteSnapshotCacheChain((SnapshotInfo) srcData); } } } @@ -256,86 +251,82 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { protected Answer copyVolumeBetweenPools(DataObject srcData, DataObject destData) { String value = configDao.getValue(Config.CopyVolumeWait.key()); - int _copyvolumewait = NumbersUtil.parseInt(value, - Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); + int _copyvolumewait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); Scope destScope = getZoneScope(destData.getDataStore().getScope()); DataStore cacheStore = cacheMgr.getCacheStorage(destScope); if (cacheStore == null) { - //need to find a nfs image store, assuming that can't copy volume directly to s3 - ImageStoreEntity imageStore = (ImageStoreEntity)this.dataStoreMgr.getImageStore(destScope.getScopeId()); - if (!imageStore.getProtocol().equalsIgnoreCase("nfs")) { - s_logger.debug("can't find a nfs image store"); - return null; - } + // need to find a nfs image store, assuming that can't copy volume + // directly to s3 + ImageStoreEntity imageStore = (ImageStoreEntity) this.dataStoreMgr.getImageStore(destScope.getScopeId()); + if (!imageStore.getProtocol().equalsIgnoreCase("nfs")) { + s_logger.debug("can't find a nfs image store"); + return null; + } - DataObject objOnImageStore = imageStore.create(srcData); - objOnImageStore.processEvent(Event.CreateOnlyRequested); + DataObject objOnImageStore = imageStore.create(srcData); + objOnImageStore.processEvent(Event.CreateOnlyRequested); - Answer answer = this.copyObject(srcData, objOnImageStore); - if (answer == null || !answer.getResult()) { - if (answer != null) { - s_logger.debug("copy to image store failed: " + answer.getDetails()); - } - objOnImageStore.processEvent(Event.OperationFailed); - imageStore.delete(objOnImageStore); - return answer; - } + Answer answer = this.copyObject(srcData, objOnImageStore); + if (answer == null || !answer.getResult()) { + if (answer != null) { + s_logger.debug("copy to image store failed: " + answer.getDetails()); + } + objOnImageStore.processEvent(Event.OperationFailed); + imageStore.delete(objOnImageStore); + return answer; + } - objOnImageStore.processEvent(Event.OperationSuccessed, answer); + objOnImageStore.processEvent(Event.OperationSuccessed, answer); - objOnImageStore.processEvent(Event.CopyingRequested); + objOnImageStore.processEvent(Event.CopyingRequested); - CopyCommand cmd = new CopyCommand(objOnImageStore.getTO(), destData.getTO(), _copyvolumewait); - EndPoint ep = selector.select(objOnImageStore, destData); - answer = ep.sendMessage(cmd); - - if (answer == null || !answer.getResult()) { - if (answer != null) { - s_logger.debug("copy to primary store failed: " + answer.getDetails()); - } - objOnImageStore.processEvent(Event.OperationFailed); - imageStore.delete(objOnImageStore); - return answer; - } - - objOnImageStore.processEvent(Event.OperationSuccessed); - imageStore.delete(objOnImageStore); - return answer; + CopyCommand cmd = new CopyCommand(objOnImageStore.getTO(), destData.getTO(), _copyvolumewait); + EndPoint ep = selector.select(objOnImageStore, destData); + answer = ep.sendMessage(cmd); + + if (answer == null || !answer.getResult()) { + if (answer != null) { + s_logger.debug("copy to primary store failed: " + answer.getDetails()); + } + objOnImageStore.processEvent(Event.OperationFailed); + imageStore.delete(objOnImageStore); + return answer; + } + + objOnImageStore.processEvent(Event.OperationSuccessed); + imageStore.delete(objOnImageStore); + return answer; } else { - DataObject cacheData = cacheMgr.createCacheObject(srcData, destScope); - CopyCommand cmd = new CopyCommand(cacheData.getTO(), destData.getTO(), _copyvolumewait); - EndPoint ep = selector.select(cacheData, destData); - Answer answer = ep.sendMessage(cmd); - return answer; + DataObject cacheData = cacheMgr.createCacheObject(srcData, destScope); + CopyCommand cmd = new CopyCommand(cacheData.getTO(), destData.getTO(), _copyvolumewait); + EndPoint ep = selector.select(cacheData, destData); + Answer answer = ep.sendMessage(cmd); + return answer; } } @Override - public Void copyAsync(DataObject srcData, DataObject destData, - AsyncCompletionCallback callback) { + public Void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback) { Answer answer = null; String errMsg = null; try { - if (srcData.getType() == DataObjectType.SNAPSHOT - && destData.getType() == DataObjectType.VOLUME) { - answer = copyVolumeFromSnapshot(srcData, destData); - } else if (srcData.getType() == DataObjectType.SNAPSHOT - && destData.getType() == DataObjectType.TEMPLATE) { - answer = createTemplateFromSnapshot(srcData, destData); - } else if (srcData.getType() == DataObjectType.TEMPLATE - && destData.getType() == DataObjectType.VOLUME) { - answer = cloneVolume(srcData, destData); - } else if (destData.getType() == DataObjectType.VOLUME - && srcData.getType() == DataObjectType.VOLUME && srcData.getDataStore().getRole() == DataStoreRole.Primary && destData.getDataStore().getRole() == DataStoreRole.Primary) { - answer = copyVolumeBetweenPools(srcData, destData); - } else if (srcData.getType() == DataObjectType.SNAPSHOT && - destData.getType() == DataObjectType.SNAPSHOT) { - answer = copySnapshot(srcData, destData); + if (srcData.getType() == DataObjectType.SNAPSHOT && destData.getType() == DataObjectType.VOLUME) { + answer = copyVolumeFromSnapshot(srcData, destData); + } else if (srcData.getType() == DataObjectType.SNAPSHOT && destData.getType() == DataObjectType.TEMPLATE) { + answer = createTemplateFromSnapshot(srcData, destData); + } else if (srcData.getType() == DataObjectType.TEMPLATE && destData.getType() == DataObjectType.VOLUME) { + answer = cloneVolume(srcData, destData); + } else if (destData.getType() == DataObjectType.VOLUME && srcData.getType() == DataObjectType.VOLUME + && srcData.getDataStore().getRole() == DataStoreRole.Primary + && destData.getDataStore().getRole() == DataStoreRole.Primary) { + answer = copyVolumeBetweenPools(srcData, destData); + } else if (srcData.getType() == DataObjectType.SNAPSHOT && destData.getType() == DataObjectType.SNAPSHOT) { + answer = copySnapshot(srcData, destData); } else { - answer = copyObject(srcData, destData); + answer = copyObject(srcData, destData); } if (answer != null && !answer.getResult()) { @@ -352,19 +343,14 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } @DB - protected Answer createTemplateFromSnapshot(DataObject srcData, - DataObject destData) { + protected Answer createTemplateFromSnapshot(DataObject srcData, DataObject destData) { - String value = configDao - .getValue(Config.CreatePrivateTemplateFromSnapshotWait - .toString()); - int _createprivatetemplatefromsnapshotwait = NumbersUtil.parseInt( - value, Integer - .parseInt(Config.CreatePrivateTemplateFromSnapshotWait - .getDefaultValue())); + String value = configDao.getValue(Config.CreatePrivateTemplateFromSnapshotWait.toString()); + int _createprivatetemplatefromsnapshotwait = NumbersUtil.parseInt(value, + Integer.parseInt(Config.CreatePrivateTemplateFromSnapshotWait.getDefaultValue())); if (needCacheStorage(srcData, destData)) { - SnapshotInfo snapshot = (SnapshotInfo)srcData; + SnapshotInfo snapshot = (SnapshotInfo) srcData; srcData = cacheSnapshotChain(snapshot); } @@ -376,7 +362,8 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { protected Answer copySnapshot(DataObject srcData, DataObject destData) { String value = configDao.getValue(Config.BackupSnapshotWait.toString()); - int _backupsnapshotwait = NumbersUtil.parseInt(value, Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue())); + int _backupsnapshotwait = NumbersUtil.parseInt(value, + Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue())); DataObject cacheData = null; Answer answer = null; diff --git a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java index 8db878afe12..22de0b25279 100644 --- a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java +++ b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java @@ -42,17 +42,13 @@ public class DataMotionServiceImpl implements DataMotionService { List strategies; @Override - public void copyAsync(DataObject srcData, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback) { if (srcData.getDataStore().getDriver().canCopy(srcData, destData)) { - srcData.getDataStore().getDriver() - .copyAsync(srcData, destData, callback); + srcData.getDataStore().getDriver().copyAsync(srcData, destData, callback); return; - } else if (destData.getDataStore().getDriver() - .canCopy(srcData, destData)) { - destData.getDataStore().getDriver() - .copyAsync(srcData, destData, callback); + } else if (destData.getDataStore().getDriver().canCopy(srcData, destData)) { + destData.getDataStore().getDriver().copyAsync(srcData, destData, callback); return; } @@ -66,8 +62,8 @@ public class DataMotionServiceImpl implements DataMotionService { } @Override - public void copyAsync(Map volumeMap, VirtualMachineTO vmTo, - Host srcHost, Host destHost, AsyncCompletionCallback callback) { + public void copyAsync(Map volumeMap, VirtualMachineTO vmTo, Host srcHost, Host destHost, + AsyncCompletionCallback callback) { for (DataMotionStrategy strategy : strategies) { if (strategy.canHandle(volumeMap, srcHost, destHost)) { strategy.copyAsync(volumeMap, vmTo, srcHost, destHost, callback); diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateDataFactoryImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateDataFactoryImpl.java index 52c79e6da6b..e369c1c033e 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateDataFactoryImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateDataFactoryImpl.java @@ -33,15 +33,13 @@ import org.springframework.stereotype.Component; import com.cloud.storage.DataStoreRole; import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplatePoolDao; @Component public class TemplateDataFactoryImpl implements TemplateDataFactory { - private static final Logger s_logger = Logger - .getLogger(TemplateDataFactoryImpl.class); + private static final Logger s_logger = Logger.getLogger(TemplateDataFactoryImpl.class); @Inject VMTemplateDao imageDataDao; @Inject @@ -50,11 +48,12 @@ public class TemplateDataFactoryImpl implements TemplateDataFactory { VMTemplatePoolDao templatePoolDao; @Inject TemplateDataStoreDao templateStoreDao; + @Override public TemplateInfo getTemplate(long templateId, DataStore store) { VMTemplateVO templ = imageDataDao.findById(templateId); if (store == null) { - TemplateObject tmpl = TemplateObject.getTemplate(templ, null); + TemplateObject tmpl = TemplateObject.getTemplate(templ, null); return tmpl; } // verify if the given input parameters are consistent with our db data. @@ -75,17 +74,15 @@ public class TemplateDataFactoryImpl implements TemplateDataFactory { s_logger.debug("template " + templateId + " is not in store:" + store.getId() + ", type:" + store.getRole()); } - TemplateObject tmpl = TemplateObject.getTemplate(templ, store); + TemplateObject tmpl = TemplateObject.getTemplate(templ, store); return tmpl; } - @Override public TemplateInfo getTemplate(long templateId, DataStoreRole storeRole) { - VMTemplateVO templ = imageDataDao.findById(templateId); TemplateDataStoreVO tmplStore = templateStoreDao.findByTemplate(templateId, storeRole); DataStore store = null; - if ( tmplStore != null ){ + if (tmplStore != null) { store = this.storeMgr.getDataStore(tmplStore.getDataStoreId(), storeRole); } return this.getTemplate(templateId, store); @@ -93,16 +90,14 @@ public class TemplateDataFactoryImpl implements TemplateDataFactory { @Override public TemplateInfo getTemplate(long templateId, DataStoreRole storeRole, Long zoneId) { - VMTemplateVO templ = imageDataDao.findById(templateId); TemplateDataStoreVO tmplStore = templateStoreDao.findByTemplateZone(templateId, zoneId, storeRole); DataStore store = null; - if ( tmplStore != null ){ + if (tmplStore != null) { store = this.storeMgr.getDataStore(tmplStore.getDataStoreId(), storeRole); } return this.getTemplate(templateId, store); } - @Override public TemplateInfo getTemplate(DataObject obj, DataStore store) { return this.getTemplate(obj.getId(), store); diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java index c4d04fb9910..a0cbc27b1b2 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java @@ -28,9 +28,6 @@ import java.util.Set; import javax.inject.Inject; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService; @@ -40,10 +37,10 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState; @@ -61,6 +58,8 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.image.manager.ImageDataManager; import org.apache.cloudstack.storage.image.store.TemplateObject; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.DeleteTemplateCommand; @@ -68,11 +67,9 @@ import com.cloud.agent.api.storage.ListTemplateAnswer; import com.cloud.agent.api.storage.ListTemplateCommand; import com.cloud.alert.AlertManager; import com.cloud.api.query.dao.UserVmJoinDao; -import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.DataStoreRole; @@ -92,7 +89,6 @@ import com.cloud.user.AccountManager; import com.cloud.user.ResourceLimitService; import com.cloud.utils.UriUtils; import com.cloud.utils.fsm.NoTransitionException; -import com.cloud.vm.UserVmVO; import com.cloud.vm.dao.UserVmDao; @Component @@ -134,7 +130,8 @@ public class TemplateServiceImpl implements TemplateService { VolumeDao _volumeDao; @Inject TemplateDataFactory _templateFactory; - @Inject VMTemplatePoolDao _tmpltPoolDao; + @Inject + VMTemplatePoolDao _tmpltPoolDao; @Inject EndPointSelector _epSelector; @Inject @@ -142,12 +139,12 @@ public class TemplateServiceImpl implements TemplateService { @Inject TemplateManager _tmpltMgr; - class TemplateOpContext extends AsyncRpcConext { final TemplateObject template; final AsyncCallFuture future; + public TemplateOpContext(AsyncCompletionCallback callback, TemplateObject template, - AsyncCallFuture future) { + AsyncCallFuture future) { super(callback); this.template = template; this.future = future; @@ -161,22 +158,21 @@ public class TemplateServiceImpl implements TemplateService { return future; } - } @Override - public void createTemplateAsync( - TemplateInfo template, DataStore store, AsyncCompletionCallback callback) { + public void createTemplateAsync(TemplateInfo template, DataStore store, + AsyncCompletionCallback callback) { // persist template_store_ref entry - TemplateObject templateOnStore = (TemplateObject)store.create(template); + TemplateObject templateOnStore = (TemplateObject) store.create(template); // update template_store_ref and template state - try{ + try { templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.CreateOnlyRequested); } catch (Exception e) { TemplateApiResult result = new TemplateApiResult(templateOnStore); result.setResult(e.toString()); result.setSuccess(false); - if ( callback != null ){ + if (callback != null) { callback.complete(result); } return; @@ -203,8 +199,8 @@ public class TemplateServiceImpl implements TemplateService { List availHypers = _clusterDao.getAvailableHypervisorInZone(store.getScope().getScopeId()); if (availHypers.isEmpty()) { /* - * This is for cloudzone, local secondary storage resource - * started before cluster created + * This is for cloudzone, local secondary storage resource started + * before cluster created */ availHypers.add(HypervisorType.KVM); } @@ -216,7 +212,8 @@ public class TemplateServiceImpl implements TemplateService { for (VMTemplateVO template : toBeDownloaded) { if (availHypers.contains(template.getHypervisorType())) { // only download sys template applicable for current hypervisor - TemplateDataStoreVO tmpltHost = _vmTemplateStoreDao.findByStoreTemplate(store.getId(), template.getId()); + TemplateDataStoreVO tmpltHost = _vmTemplateStoreDao + .findByStoreTemplate(store.getId(), template.getId()); if (tmpltHost == null || tmpltHost.getState() != ObjectInDataStoreStateMachine.State.Ready) { TemplateInfo tmplt = _templateFactory.getTemplate(template.getId(), DataStoreRole.Image); createTemplateAsync(tmplt, store, null); @@ -229,16 +226,15 @@ public class TemplateServiceImpl implements TemplateService { public void handleSysTemplateDownload(HypervisorType hostHyper, Long dcId) { Set toBeDownloaded = new HashSet(); List stores = _storeMgr.getImageStoresByScope(new ZoneScope(dcId)); - if (stores == null || stores.isEmpty()){ + if (stores == null || stores.isEmpty()) { return; } - /*Download all the templates in zone with the same hypervisortype*/ - for ( DataStore store : stores) { + /* Download all the templates in zone with the same hypervisortype */ + for (DataStore store : stores) { List rtngTmplts = _templateDao.listAllSystemVMTemplates(); List defaultBuiltin = _templateDao.listDefaultBuiltinTemplates(); - for (VMTemplateVO rtngTmplt : rtngTmplts) { if (rtngTmplt.getHypervisorType() == hostHyper) { toBeDownloaded.add(rtngTmplt); @@ -251,8 +247,9 @@ public class TemplateServiceImpl implements TemplateService { } } - for (VMTemplateVO template: toBeDownloaded) { - TemplateDataStoreVO tmpltHost = _vmTemplateStoreDao.findByStoreTemplate(store.getId(), template.getId()); + for (VMTemplateVO template : toBeDownloaded) { + TemplateDataStoreVO tmpltHost = _vmTemplateStoreDao + .findByStoreTemplate(store.getId(), template.getId()); if (tmpltHost == null || tmpltHost.getState() != ObjectInDataStoreStateMachine.State.Ready) { TemplateInfo tmplt = _templateFactory.getTemplate(template.getId(), DataStoreRole.Image); createTemplateAsync(tmplt, store, null); @@ -277,11 +274,10 @@ public class TemplateServiceImpl implements TemplateService { Set toBeDownloaded = new HashSet(); List allTemplates = null; - if (zoneId == null){ + if (zoneId == null) { // region wide store allTemplates = _templateDao.listAllActive(); - } - else{ + } else { // zone wide store allTemplates = _templateDao.listAllInZone(zoneId); } @@ -319,7 +315,8 @@ public class TemplateServiceImpl implements TemplateService { } if (tmpltInfo.isCorrupted()) { tmpltStore.setDownloadState(Status.DOWNLOAD_ERROR); - String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + " is corrupted on secondary storage " + tmpltStore.getId(); + String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + + " is corrupted on secondary storage " + tmpltStore.getId(); tmpltStore.setErrorString(msg); s_logger.info("msg"); if (tmplt.getUrl() == null) { @@ -344,11 +341,14 @@ public class TemplateServiceImpl implements TemplateService { // set template to ready state if (tmplt.getState() != TemplateState.Ready) { try { - imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.CreateRequested, null, _templateDao); - imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.OperationSucceeded, null, _templateDao); + imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.CreateRequested, null, + _templateDao); + imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.OperationSucceeded, null, + _templateDao); } catch (NoTransitionException e) { // non fatal though - s_logger.debug("failed to update template " + tmplt.getUniqueName() + " state to Ready", e); + s_logger.debug( + "failed to update template " + tmplt.getUniqueName() + " state to Ready", e); } } @@ -360,17 +360,19 @@ public class TemplateServiceImpl implements TemplateService { tmpltInfo.getSize() - UriUtils.getRemoteSize(tmplt.getUrl())); } catch (ResourceAllocationException e) { s_logger.warn(e.getMessage()); - _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId, null, e.getMessage(), e.getMessage()); + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId, null, + e.getMessage(), e.getMessage()); } finally { - _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(), - com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal()); + _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId) + .getDomainId(), com.cloud.configuration.Resource.ResourceType.secondary_storage + .getOrdinal()); } } } _vmTemplateStoreDao.update(tmpltStore.getId(), tmpltStore); } else { - tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, - tmpltInfo.getInstallPath(), tmplt.getUrl()); + tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, + null, null, null, tmpltInfo.getInstallPath(), tmplt.getUrl()); tmpltStore.setSize(tmpltInfo.getSize()); tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize()); tmpltStore.setDataStoreRole(store.getRole()); @@ -385,8 +387,10 @@ public class TemplateServiceImpl implements TemplateService { // set template to ready state if (tmplt.getState() != TemplateState.Ready) { try { - imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.CreateRequested, null, _templateDao); - imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.OperationSucceeded, null, _templateDao); + imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.CreateRequested, null, + _templateDao); + imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.OperationSucceeded, null, + _templateDao); } catch (NoTransitionException e) { // non fatal though s_logger.debug("failed to update template " + tmplt.getUniqueName() + " state to Ready", e); @@ -429,7 +433,8 @@ public class TemplateServiceImpl implements TemplateService { continue; } if (availHypers.contains(tmplt.getHypervisorType())) { - s_logger.info("Downloading template " + tmplt.getUniqueName() + " to image store " + store.getName()); + s_logger.info("Downloading template " + tmplt.getUniqueName() + " to image store " + + store.getName()); associateTemplateToZone(tmplt.getId(), zoneId); TemplateInfo tmpl = _templateFactory.getTemplate(tmplt.getId(), DataStoreRole.Image); createTemplateAsync(tmpl, store, null); @@ -437,19 +442,22 @@ public class TemplateServiceImpl implements TemplateService { } } - for (String uniqueName : templateInfos.keySet()) { + for (String uniqueName : templateInfos.keySet()) { TemplateProp tInfo = templateInfos.get(uniqueName); if (_tmpltMgr.templateIsDeleteable(tInfo.getId())) { - //TODO: we cannot directly call deleteTemplateSync here to reuse delete logic since in this case, our db does not have this template at all. - VMTemplateVO template = _templateDao.findById(tInfo.getId()); - DeleteTemplateCommand dtCommand = new DeleteTemplateCommand(store.getTO(), tInfo.getInstallPath(), null, null); + // TODO: we cannot directly call deleteTemplateSync here to + // reuse delete logic since in this case, our db does not have + // this template at all. + DeleteTemplateCommand dtCommand = new DeleteTemplateCommand(store.getTO(), tInfo.getInstallPath(), + null, null); EndPoint ep = _epSelector.select(store); Answer answer = ep.sendMessage(dtCommand); if (answer == null || !answer.getResult()) { s_logger.info("Failed to deleted template at store: " + store.getName()); } else { - String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + storeId; + String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + + storeId; s_logger.info(description); } @@ -458,17 +466,16 @@ public class TemplateServiceImpl implements TemplateService { } - - // persist entry in template_zone_ref table. zoneId can be empty for region-wide image store, in that case, + // persist entry in template_zone_ref table. zoneId can be empty for + // region-wide image store, in that case, // we will associate the template to all the zones. - private void associateTemplateToZone(long templateId, Long zoneId){ + private void associateTemplateToZone(long templateId, Long zoneId) { List dcs = new ArrayList(); - if (zoneId != null ){ + if (zoneId != null) { dcs.add(zoneId); - } - else{ + } else { List zones = _dcDao.listAll(); - for (DataCenterVO zone : zones){ + for (DataCenterVO zone : zones) { dcs.add(zone.getId()); } } @@ -484,13 +491,12 @@ public class TemplateServiceImpl implements TemplateService { } } - private Map listTemplate(DataStore ssStore) { ListTemplateCommand cmd = new ListTemplateCommand(ssStore.getTO()); EndPoint ep = _epSelector.select(ssStore); Answer answer = ep.sendMessage(cmd); if (answer != null && answer.getResult()) { - ListTemplateAnswer tanswer = (ListTemplateAnswer)answer; + ListTemplateAnswer tanswer = (ListTemplateAnswer) answer; return tanswer.getTemplateInfo(); } else { if (s_logger.isDebugEnabled()) { @@ -501,7 +507,6 @@ public class TemplateServiceImpl implements TemplateService { return null; } - protected Void createTemplateCallback(AsyncCallbackDispatcher callback, TemplateOpContext context) { TemplateObject template = context.getTemplate(); @@ -511,7 +516,7 @@ public class TemplateServiceImpl implements TemplateService { if (callbackResult.isFailed()) { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); result.setResult(callbackResult.getResult()); - if ( parentCallback != null ){ + if (parentCallback != null) { parentCallback.complete(result); } return null; @@ -521,21 +526,20 @@ public class TemplateServiceImpl implements TemplateService { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed); } catch (Exception e) { result.setResult(e.toString()); - if ( parentCallback != null ){ + if (parentCallback != null) { parentCallback.complete(result); } return null; } - if (parentCallback != null){ + if (parentCallback != null) { parentCallback.complete(result); } return null; } @Override - public AsyncCallFuture deleteTemplateAsync( - TemplateInfo template) { + public AsyncCallFuture deleteTemplateAsync(TemplateInfo template) { TemplateObject to = (TemplateObject) template; // update template_store_ref status to.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); @@ -549,14 +553,15 @@ public class TemplateServiceImpl implements TemplateService { return future; } - public Void deleteTemplateCallback(AsyncCallbackDispatcher callback, TemplateOpContext context) { + public Void deleteTemplateCallback(AsyncCallbackDispatcher callback, + TemplateOpContext context) { CommandResult result = callback.getResult(); TemplateObject vo = context.getTemplate(); - if (result.isSuccess()) { + if (result.isSuccess()) { vo.processEvent(Event.OperationSuccessed); } else { vo.processEvent(Event.OperationFailed); - } + } TemplateApiResult apiResult = new TemplateApiResult(vo); apiResult.setResult(result.getResult()); apiResult.setSuccess(result.isSuccess()); @@ -564,12 +569,13 @@ public class TemplateServiceImpl implements TemplateService { return null; } - private AsyncCallFuture copyAsync(DataObject source, TemplateInfo template, DataStore store){ + private AsyncCallFuture copyAsync(DataObject source, TemplateInfo template, DataStore store) { AsyncCallFuture future = new AsyncCallFuture(); DataObject templateOnStore = store.create(template); templateOnStore.processEvent(Event.CreateOnlyRequested); - TemplateOpContext context = new TemplateOpContext(null, (TemplateObject) templateOnStore, future); + TemplateOpContext context = new TemplateOpContext(null, + (TemplateObject) templateOnStore, future); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); caller.setCallback(caller.getTarget().copyTemplateCallBack(null, null)).setContext(context); _motionSrv.copyAsync(source, templateOnStore, caller); @@ -577,14 +583,14 @@ public class TemplateServiceImpl implements TemplateService { } @Override - public AsyncCallFuture createTemplateFromSnapshotAsync( - SnapshotInfo snapshot, TemplateInfo template, DataStore store) { + public AsyncCallFuture createTemplateFromSnapshotAsync(SnapshotInfo snapshot, + TemplateInfo template, DataStore store) { return copyAsync(snapshot, template, store); } @Override - public AsyncCallFuture createTemplateFromVolumeAsync( - VolumeInfo volume, TemplateInfo template, DataStore store) { + public AsyncCallFuture createTemplateFromVolumeAsync(VolumeInfo volume, TemplateInfo template, + DataStore store) { return copyAsync(volume, template, store); } @@ -595,7 +601,7 @@ public class TemplateServiceImpl implements TemplateService { @Override public AsyncCallFuture prepareTemplateOnPrimary(TemplateInfo srcTemplate, StoragePool pool) { - return copyAsync(srcTemplate, srcTemplate, (DataStore)pool); + return copyAsync(srcTemplate, srcTemplate, (DataStore) pool); } protected Void copyTemplateCallBack(AsyncCallbackDispatcher callback, @@ -623,29 +629,29 @@ public class TemplateServiceImpl implements TemplateService { return null; } - @Override - public void addSystemVMTemplatesToSecondary(DataStore store){ + public void addSystemVMTemplatesToSecondary(DataStore store) { long storeId = store.getId(); List rtngTmplts = _templateDao.listAllSystemVMTemplates(); - for ( VMTemplateVO tmplt : rtngTmplts ) { + for (VMTemplateVO tmplt : rtngTmplts) { // set template ready state - if ( tmplt.getState() != TemplateState.Ready ){ + if (tmplt.getState() != TemplateState.Ready) { try { - imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.CreateRequested, null, - _templateDao); - imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.OperationSucceeded, null, - _templateDao); + imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.CreateRequested, null, _templateDao); + imageMgr.getStateMachine().transitTo(tmplt, TemplateEvent.OperationSucceeded, null, _templateDao); } catch (NoTransitionException e) { // non fatal though s_logger.debug("failed to update system vm template state to Ready", e); } } TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId()); - if ( tmpltStore == null ) { - tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, TemplateConstants.DEFAULT_SYSTEM_VM_TEMPLATE_PATH + tmplt.getId() + File.separator, tmplt.getUrl()); + if (tmpltStore == null) { + tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, + null, null, TemplateConstants.DEFAULT_SYSTEM_VM_TEMPLATE_PATH + tmplt.getId() + File.separator, + tmplt.getUrl()); tmpltStore.setSize(0L); - tmpltStore.setPhysicalSize(0); // no size information for pre-seeded system vm templates + tmpltStore.setPhysicalSize(0); // no size information for + // pre-seeded system vm templates tmpltStore.setDataStoreRole(store.getRole()); _vmTemplateStoreDao.persist(tmpltStore); } diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageDataManagerImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageDataManagerImpl.java index d8708308cef..f41416baf90 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageDataManagerImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageDataManagerImpl.java @@ -27,8 +27,7 @@ import com.cloud.utils.fsm.StateMachine2; @Component public class ImageDataManagerImpl implements ImageDataManager { - private final StateMachine2 - stateMachine = new StateMachine2(); + private final StateMachine2 stateMachine = new StateMachine2(); public ImageDataManagerImpl() { stateMachine.addTransition(TemplateState.Allocated, TemplateEvent.CreateRequested, TemplateState.Creating); @@ -41,7 +40,8 @@ public class ImageDataManagerImpl implements ImageDataManager { stateMachine.addTransition(TemplateState.Destroying, TemplateEvent.DestroyRequested, TemplateState.Destroying); stateMachine.addTransition(TemplateState.Destroying, TemplateEvent.OperationFailed, TemplateState.Destroying); stateMachine.addTransition(TemplateState.Destroying, TemplateEvent.OperationSucceeded, TemplateState.Destroyed); - //TODO: this should not be needed, but it happened during testing where multiple success event is sent to callback + // TODO: this should not be needed, but it happened during testing where + // multiple success event is sent to callback stateMachine.addTransition(TemplateState.Ready, TemplateEvent.OperationSucceeded, TemplateState.Ready); } diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageStoreProviderManagerImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageStoreProviderManagerImpl.java index 43c02f6b6c2..73c960fef9e 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageStoreProviderManagerImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/manager/ImageStoreProviderManagerImpl.java @@ -40,16 +40,12 @@ import org.apache.cloudstack.storage.image.store.ImageStoreImpl; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; @Component public class ImageStoreProviderManagerImpl implements ImageStoreProviderManager { - private static final Logger s_logger = Logger.getLogger(ImageStoreProviderManagerImpl.class); + private static final Logger s_logger = Logger.getLogger(ImageStoreProviderManagerImpl.class); @Inject ImageStoreDao dataStoreDao; @Inject @@ -67,10 +63,9 @@ public class ImageStoreProviderManagerImpl implements ImageStoreProviderManager public ImageStoreEntity getImageStore(long dataStoreId) { ImageStoreVO dataStore = dataStoreDao.findById(dataStoreId); String providerName = dataStore.getProviderName(); - ImageStoreProvider provider = (ImageStoreProvider)providerManager.getDataStoreProvider(providerName); - ImageStoreEntity imgStore = ImageStoreImpl.getDataStore(dataStore, - driverMaps.get(provider.getName()), provider - ); + ImageStoreProvider provider = (ImageStoreProvider) providerManager.getDataStoreProvider(providerName); + ImageStoreEntity imgStore = ImageStoreImpl + .getDataStore(dataStore, driverMaps.get(provider.getName()), provider); // TODO Auto-generated method stub return imgStore; } @@ -120,8 +115,6 @@ public class ImageStoreProviderManagerImpl implements ImageStoreProviderManager return imageStores; } - - @Override public List listImageCacheStores(Scope scope) { if (scope.getScopeType() != ScopeType.ZONE) { diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/store/ImageStoreImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/store/ImageStoreImpl.java index 95c952e1cd2..c6840d7aa17 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/store/ImageStoreImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/store/ImageStoreImpl.java @@ -44,11 +44,9 @@ import com.cloud.agent.api.to.DataStoreTO; import com.cloud.storage.DataStoreRole; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.utils.component.ComponentContext; -import com.cloud.utils.storage.encoding.EncodingType; - public class ImageStoreImpl implements ImageStoreEntity { - private static final Logger s_logger = Logger.getLogger(ImageStoreImpl.class); + private static final Logger s_logger = Logger.getLogger(ImageStoreImpl.class); @Inject VMTemplateDao imageDao; @Inject @@ -59,7 +57,7 @@ public class ImageStoreImpl implements ImageStoreEntity { boolean needDownloadToCacheStorage = false; public ImageStoreImpl() { - + super(); } protected void configure(ImageStoreVO dataStoreVO, ImageStoreDriver imageDataStoreDriver, @@ -71,7 +69,7 @@ public class ImageStoreImpl implements ImageStoreEntity { public static ImageStoreEntity getDataStore(ImageStoreVO dataStoreVO, ImageStoreDriver imageDataStoreDriver, ImageStoreProvider provider) { - ImageStoreImpl instance = (ImageStoreImpl)ComponentContext.inject(ImageStoreImpl.class); + ImageStoreImpl instance = ComponentContext.inject(ImageStoreImpl.class); instance.configure(dataStoreVO, imageDataStoreDriver, provider); return instance; } @@ -90,8 +88,9 @@ public class ImageStoreImpl implements ImageStoreEntity { @Override public DataStoreRole getRole() { - return this.imageDataStoreVO.getRole(); + return this.imageDataStoreVO.getRole(); } + @Override public long getId() { // TODO Auto-generated method stub @@ -128,8 +127,7 @@ public class ImageStoreImpl implements ImageStoreEntity { @Override public boolean exists(DataObject object) { - return (objectInStoreMgr.findObject(object, - this) != null) ? true : false; + return (objectInStoreMgr.findObject(object, this) != null) ? true : false; } @Override @@ -137,11 +135,10 @@ public class ImageStoreImpl implements ImageStoreEntity { return this.imageDataStoreVO.getUuid(); } - public Date getCreated(){ + public Date getCreated() { return this.imageDataStoreVO.getCreated(); } - @Override public DataObject create(DataObject obj) { DataObject object = objectInStoreMgr.create(obj, this); @@ -150,18 +147,18 @@ public class ImageStoreImpl implements ImageStoreEntity { @Override public boolean delete(DataObject obj) { - AsyncCallFuture future = new AsyncCallFuture(); - this.driver.deleteAsync(obj, future); - try { - future.get(); - } catch (InterruptedException e) { - s_logger.debug("failed delete obj", e); - return false; - } catch (ExecutionException e) { - s_logger.debug("failed delete obj", e); - return false; - } - objectInStoreMgr.delete(obj); + AsyncCallFuture future = new AsyncCallFuture(); + this.driver.deleteAsync(obj, future); + try { + future.get(); + } catch (InterruptedException e) { + s_logger.debug("failed delete obj", e); + return false; + } catch (ExecutionException e) { + s_logger.debug("failed delete obj", e); + return false; + } + objectInStoreMgr.delete(obj); return true; } @@ -175,7 +172,6 @@ public class ImageStoreImpl implements ImageStoreEntity { return imageDataStoreVO.getDataCenterId(); } - @Override public String getProviderName() { return imageDataStoreVO.getProviderName(); @@ -186,15 +182,13 @@ public class ImageStoreImpl implements ImageStoreEntity { return imageDataStoreVO.getProtocol(); } - - @Override public DataStoreTO getTO() { return getDriver().getStoreTO(this); } @Override - public String getMountPoint(){ + public String getMountPoint() { return this.imageDataStoreVO.getParent(); } diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/store/TemplateObject.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/store/TemplateObject.java index b17fc3df254..e4be6277eac 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/store/TemplateObject.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/store/TemplateObject.java @@ -54,8 +54,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; public class TemplateObject implements TemplateInfo { - private static final Logger s_logger = Logger - .getLogger(TemplateObject.class); + private static final Logger s_logger = Logger.getLogger(TemplateObject.class); private VMTemplateVO imageVO; private DataStore dataStore; @Inject @@ -64,8 +63,10 @@ public class TemplateObject implements TemplateInfo { VMTemplateDao imageDao; @Inject ObjectInDataStoreManager objectInStoreMgr; - @Inject VMTemplatePoolDao templatePoolDao; - @Inject TemplateDataStoreDao templateStoreDao; + @Inject + VMTemplatePoolDao templatePoolDao; + @Inject + TemplateDataStoreDao templateStoreDao; public TemplateObject() { } @@ -81,7 +82,6 @@ public class TemplateObject implements TemplateInfo { return to; } - public void setSize(Long size) { this.imageVO.setSize(size); } @@ -114,7 +114,7 @@ public class TemplateObject implements TemplateInfo { public String getUri() { VMTemplateVO image = imageDao.findById(this.imageVO.getId()); - return image.getUrl(); + return image.getUrl(); } @@ -125,28 +125,21 @@ public class TemplateObject implements TemplateInfo { } /* - -// If the template that was passed into this allocator is not installed in the storage pool, - // add 3 * (template size on secondary storage) to the running total - VMTemplateHostVO templateHostVO = _storageMgr.findVmTemplateHost(templateForVmCreation.getId(), null); - - if (templateHostVO == null) { - VMTemplateSwiftVO templateSwiftVO = _swiftMgr.findByTmpltId(templateForVmCreation.getId()); - if (templateSwiftVO != null) { - long templateSize = templateSwiftVO.getPhysicalSize(); - if (templateSize == 0) { - templateSize = templateSwiftVO.getSize(); - } - totalAllocatedSize += (templateSize + _extraBytesPerVolume); - } - } else { - long templateSize = templateHostVO.getPhysicalSize(); - if ( templateSize == 0 ){ - templateSize = templateHostVO.getSize(); - } - totalAllocatedSize += (templateSize + _extraBytesPerVolume); - } - + * + * // If the template that was passed into this allocator is not + * installed in the storage pool, // add 3 * (template size on secondary + * storage) to the running total VMTemplateHostVO templateHostVO = + * _storageMgr.findVmTemplateHost(templateForVmCreation.getId(), null); + * + * if (templateHostVO == null) { VMTemplateSwiftVO templateSwiftVO = + * _swiftMgr.findByTmpltId(templateForVmCreation.getId()); if + * (templateSwiftVO != null) { long templateSize = + * templateSwiftVO.getPhysicalSize(); if (templateSize == 0) { + * templateSize = templateSwiftVO.getSize(); } totalAllocatedSize += + * (templateSize + _extraBytesPerVolume); } } else { long templateSize = + * templateHostVO.getPhysicalSize(); if ( templateSize == 0 ){ + * templateSize = templateHostVO.getSize(); } totalAllocatedSize += + * (templateSize + _extraBytesPerVolume); } */ VMTemplateVO image = imageDao.findById(this.imageVO.getId()); return image.getSize(); @@ -164,8 +157,7 @@ public class TemplateObject implements TemplateInfo { public boolean stateTransit(TemplateEvent e) throws NoTransitionException { this.imageVO = imageDao.findById(this.imageVO.getId()); - boolean result= imageMgr.getStateMachine().transitTo(this.imageVO, e, null, - imageDao); + boolean result = imageMgr.getStateMachine().transitTo(this.imageVO, e, null, imageDao); this.imageVO = imageDao.findById(this.imageVO.getId()); return result; } @@ -173,12 +165,12 @@ public class TemplateObject implements TemplateInfo { @Override public void processEvent(Event event) { try { - if (this.getDataStore().getRole() == DataStoreRole.Image || - this.getDataStore().getRole() == DataStoreRole.ImageCache) { + if (this.getDataStore().getRole() == DataStoreRole.Image + || this.getDataStore().getRole() == DataStoreRole.ImageCache) { TemplateEvent templEvent = null; if (event == ObjectInDataStoreStateMachine.Event.CreateOnlyRequested) { templEvent = TemplateEvent.CreateRequested; - } else if (event == ObjectInDataStoreStateMachine.Event.DestroyRequested){ + } else if (event == ObjectInDataStoreStateMachine.Event.DestroyRequested) { templEvent = TemplateEvent.DestroyRequested; } else if (event == ObjectInDataStoreStateMachine.Event.OperationSuccessed) { templEvent = TemplateEvent.OperationSucceeded; @@ -195,9 +187,9 @@ public class TemplateObject implements TemplateInfo { } catch (NoTransitionException e) { s_logger.debug("failed to update state", e); throw new CloudRuntimeException("Failed to update state" + e.toString()); - } finally{ + } finally { // in case of OperationFailed, expunge the entry - if ( event == ObjectInDataStoreStateMachine.Event.OperationFailed){ + if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) { objectInStoreMgr.delete(this); } } @@ -206,63 +198,64 @@ public class TemplateObject implements TemplateInfo { @Override public void processEvent(ObjectInDataStoreStateMachine.Event event, Answer answer) { try { - if (this.getDataStore().getRole() == DataStoreRole.Primary) { - if (answer instanceof CopyCmdAnswer) { - CopyCmdAnswer cpyAnswer = (CopyCmdAnswer)answer; - TemplateObjectTO newTemplate = (TemplateObjectTO)cpyAnswer.getNewData(); - VMTemplateStoragePoolVO templatePoolRef = templatePoolDao.findByPoolTemplate(this.getDataStore().getId(), this.getId()); - templatePoolRef.setDownloadPercent(100); - templatePoolRef.setDownloadState(Status.DOWNLOADED); - templatePoolRef.setLocalDownloadPath(newTemplate.getPath()); - templatePoolRef.setInstallPath(newTemplate.getPath()); - templatePoolDao.update(templatePoolRef.getId(), templatePoolRef); - } - } else if (this.getDataStore().getRole() == DataStoreRole.Image || - this.getDataStore().getRole() == DataStoreRole.ImageCache) { - if (answer instanceof CopyCmdAnswer) { - CopyCmdAnswer cpyAnswer = (CopyCmdAnswer)answer; - TemplateObjectTO newTemplate = (TemplateObjectTO)cpyAnswer.getNewData(); - TemplateDataStoreVO templateStoreRef = this.templateStoreDao.findByStoreTemplate(this.getDataStore().getId(), - this.getId()); - templateStoreRef.setInstallPath(newTemplate.getPath()); - templateStoreRef.setDownloadPercent(100); - templateStoreRef.setDownloadState(Status.DOWNLOADED); - templateStoreRef.setSize(newTemplate.getSize()); - templateStoreDao.update(templateStoreRef.getId(), templateStoreRef); + if (this.getDataStore().getRole() == DataStoreRole.Primary) { + if (answer instanceof CopyCmdAnswer) { + CopyCmdAnswer cpyAnswer = (CopyCmdAnswer) answer; + TemplateObjectTO newTemplate = (TemplateObjectTO) cpyAnswer.getNewData(); + VMTemplateStoragePoolVO templatePoolRef = templatePoolDao.findByPoolTemplate(this.getDataStore() + .getId(), this.getId()); + templatePoolRef.setDownloadPercent(100); + templatePoolRef.setDownloadState(Status.DOWNLOADED); + templatePoolRef.setLocalDownloadPath(newTemplate.getPath()); + templatePoolRef.setInstallPath(newTemplate.getPath()); + templatePoolDao.update(templatePoolRef.getId(), templatePoolRef); + } + } else if (this.getDataStore().getRole() == DataStoreRole.Image + || this.getDataStore().getRole() == DataStoreRole.ImageCache) { + if (answer instanceof CopyCmdAnswer) { + CopyCmdAnswer cpyAnswer = (CopyCmdAnswer) answer; + TemplateObjectTO newTemplate = (TemplateObjectTO) cpyAnswer.getNewData(); + TemplateDataStoreVO templateStoreRef = this.templateStoreDao.findByStoreTemplate(this + .getDataStore().getId(), this.getId()); + templateStoreRef.setInstallPath(newTemplate.getPath()); + templateStoreRef.setDownloadPercent(100); + templateStoreRef.setDownloadState(Status.DOWNLOADED); + templateStoreRef.setSize(newTemplate.getSize()); + templateStoreDao.update(templateStoreRef.getId(), templateStoreRef); if (this.getDataStore().getRole() == DataStoreRole.Image) { VMTemplateVO templateVO = this.imageDao.findById(this.getId()); templateVO.setFormat(newTemplate.getFormat()); templateVO.setSize(newTemplate.getSize()); this.imageDao.update(templateVO.getId(), templateVO); } - } + } - TemplateEvent templEvent = null; - if (event == ObjectInDataStoreStateMachine.Event.CreateOnlyRequested) { - templEvent = TemplateEvent.CreateRequested; - } else if (event == ObjectInDataStoreStateMachine.Event.DestroyRequested){ + TemplateEvent templEvent = null; + if (event == ObjectInDataStoreStateMachine.Event.CreateOnlyRequested) { + templEvent = TemplateEvent.CreateRequested; + } else if (event == ObjectInDataStoreStateMachine.Event.DestroyRequested) { templEvent = TemplateEvent.DestroyRequested; } else if (event == ObjectInDataStoreStateMachine.Event.OperationSuccessed) { - templEvent = TemplateEvent.OperationSucceeded; - } else if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) { - templEvent = TemplateEvent.OperationFailed; - } + templEvent = TemplateEvent.OperationSucceeded; + } else if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) { + templEvent = TemplateEvent.OperationFailed; + } - if (templEvent != null && this.getDataStore().getRole() == DataStoreRole.Image) { - this.stateTransit(templEvent); - } - } + if (templEvent != null && this.getDataStore().getRole() == DataStoreRole.Image) { + this.stateTransit(templEvent); + } + } objectInStoreMgr.update(this, event); } catch (NoTransitionException e) { s_logger.debug("failed to update state", e); throw new CloudRuntimeException("Failed to update state" + e.toString()); - } catch (Exception ex){ + } catch (Exception ex) { s_logger.debug("failed to process event and answer", ex); objectInStoreMgr.delete(this); throw new CloudRuntimeException("Failed to process event", ex); - } finally{ + } finally { // in case of OperationFailed, expunge the entry - if ( event == ObjectInDataStoreStateMachine.Event.OperationFailed){ + if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) { objectInStoreMgr.delete(this); } } @@ -270,26 +263,26 @@ public class TemplateObject implements TemplateInfo { @Override public DataTO getTO() { - DataTO to = null; - if (this.dataStore == null) { - to = new TemplateObjectTO(this); - } else { - to = this.dataStore.getDriver().getTO(this); - if (to == null) { - to = new TemplateObjectTO(this); - } - } + DataTO to = null; + if (this.dataStore == null) { + to = new TemplateObjectTO(this); + } else { + to = this.dataStore.getDriver().getTO(this); + if (to == null) { + to = new TemplateObjectTO(this); + } + } return to; } @Override public String getInstallPath() { - if (this.dataStore == null) { - return null; - } - DataObjectInStore obj = objectInStoreMgr.findObject(this, this.dataStore); - return obj.getInstallPath(); + if (this.dataStore == null) { + return null; + } + DataObjectInStore obj = objectInStoreMgr.findObject(this, this.dataStore); + return obj.getInstallPath(); } @Override diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/MockLocalNfsSecondaryStorageResource.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/MockLocalNfsSecondaryStorageResource.java index 8e5b1640a06..4d932964a64 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/MockLocalNfsSecondaryStorageResource.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/MockLocalNfsSecondaryStorageResource.java @@ -21,26 +21,21 @@ import static java.util.Arrays.asList; import java.io.InputStream; import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.List; import javax.naming.ConfigurationException; -import org.springframework.stereotype.Component; - -import com.amazonaws.services.s3.model.S3ObjectSummary; - import org.apache.cloudstack.storage.command.DownloadSystemTemplateCommand; import org.apache.cloudstack.storage.resource.NfsSecondaryStorageResource; import org.apache.cloudstack.storage.template.DownloadManagerImpl; +import org.springframework.stereotype.Component; +import com.amazonaws.services.s3.model.S3ObjectSummary; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.storage.DownloadAnswer; -import com.cloud.agent.api.storage.ssCommand; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.S3TO; @@ -54,10 +49,9 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; @Component -public class MockLocalNfsSecondaryStorageResource extends - NfsSecondaryStorageResource { +public class MockLocalNfsSecondaryStorageResource extends NfsSecondaryStorageResource { - public MockLocalNfsSecondaryStorageResource(){ + public MockLocalNfsSecondaryStorageResource() { _dlMgr = new DownloadManagerImpl(); _storage = new JavaStorageLayer(); HashMap params = new HashMap(); @@ -68,37 +62,32 @@ public class MockLocalNfsSecondaryStorageResource extends // TODO Auto-generated catch block e.printStackTrace(); } - - createTemplateFromSnapshotXenScript = Script.findScript(getDefaultScriptsDir(), "create_privatetemplate_from_snapshot_xen.sh"); - /* - _storage = new JavaStorageLayer(); - ((DownloadManagerImpl)_dlMgr).setThreadPool(Executors.newFixedThreadPool(10)); - ((DownloadManagerImpl)_dlMgr).setStorageLayer(_storage); - */ + createTemplateFromSnapshotXenScript = Script.findScript(getDefaultScriptsDir(), + "create_privatetemplate_from_snapshot_xen.sh"); } @Override - public String getRootDir(String secUrl){ + public String getRootDir(String secUrl) { return "/mnt"; } @Override public Answer executeRequest(Command cmd) { - if (cmd instanceof DownloadSystemTemplateCommand){ - return execute((DownloadSystemTemplateCommand)cmd); + if (cmd instanceof DownloadSystemTemplateCommand) { + return execute((DownloadSystemTemplateCommand) cmd); } else { - //return Answer.createUnsupportedCommandAnswer(cmd); + // return Answer.createUnsupportedCommandAnswer(cmd); return super.executeRequest(cmd); } } - private Answer execute(DownloadSystemTemplateCommand cmd){ + private Answer execute(DownloadSystemTemplateCommand cmd) { DataStoreTO dstore = cmd.getDataStore(); - if ( dstore instanceof S3TO ){ - //TODO: how to handle download progress for S3 - S3TO s3 = (S3TO)cmd.getDataStore(); + if (dstore instanceof S3TO) { + // TODO: how to handle download progress for S3 + S3TO s3 = (S3TO) cmd.getDataStore(); String url = cmd.getUrl(); String user = null; String password = null; @@ -108,19 +97,16 @@ public class MockLocalNfsSecondaryStorageResource extends } // get input stream from the given url InputStream in = UriUtils.getInputStreamFromUrl(url, user, password); - URI uri; URL urlObj; try { - uri = new URI(url); urlObj = new URL(url); - } catch (URISyntaxException e) { - throw new CloudRuntimeException("URI is incorrect: " + url); } catch (MalformedURLException e) { throw new CloudRuntimeException("URL is incorrect: " + url); } final String bucket = s3.getBucketName(); - // convention is no / in the end for install path based on S3Utils implementation. + // convention is no / in the end for install path based on S3Utils + // implementation. String path = determineS3TemplateDirectory(cmd.getAccountId(), cmd.getResourceId(), cmd.getName()); // template key is // TEMPLATE_ROOT_DIR/account_id/template_id/template_name @@ -130,19 +116,19 @@ public class MockLocalNfsSecondaryStorageResource extends if (s3Obj == null || s3Obj.size() == 0) { return new Answer(cmd, false, "Failed to download to S3 bucket: " + bucket + " with key: " + key); } else { - return new DownloadAnswer(null, 100, null, Status.DOWNLOADED, path, path, s3Obj.get(0).getSize(), s3Obj.get(0).getSize(), s3Obj.get(0) - .getETag()); + return new DownloadAnswer(null, 100, null, Status.DOWNLOADED, path, path, s3Obj.get(0).getSize(), s3Obj + .get(0).getSize(), s3Obj.get(0).getETag()); } - } - else if ( dstore instanceof NfsTO ){ + } else if (dstore instanceof NfsTO) { return new Answer(cmd, false, "Nfs needs to be pre-installed with system vm templates"); - } - else if ( dstore instanceof SwiftTO ){ - //TODO: need to move code from execute(uploadTemplateToSwiftFromSecondaryStorageCommand) here, but we need to handle - // source is url, most likely we need to modify our existing swiftUpload python script. + } else if (dstore instanceof SwiftTO) { + // TODO: need to move code from + // execute(uploadTemplateToSwiftFromSecondaryStorageCommand) here, + // but we need to handle + // source is url, most likely we need to modify our existing + // swiftUpload python script. return new Answer(cmd, false, "Swift is not currently support DownloadCommand"); - } - else{ + } else { return new Answer(cmd, false, "Unsupported image data store: " + dstore); } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTest.java index b369459a9a8..3d300de1060 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTest.java @@ -16,8 +16,6 @@ // under the License. package org.apache.cloudstack.storage.allocator; -import static org.junit.Assert.fail; - import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -36,6 +34,7 @@ import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -70,370 +69,372 @@ import com.cloud.vm.VirtualMachineProfile; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:/storageContext.xml") public class StorageAllocatorTest { - @Inject - PrimaryDataStoreDao storagePoolDao; - @Inject - StorageManager storageMgr; - @Inject - DiskOfferingDao diskOfferingDao; - @Inject - VolumeDao volumeDao; - @Inject - HostPodDao podDao; - @Inject - ClusterDao clusterDao; - @Inject - DataCenterDao dcDao; - @Inject - StoragePoolDetailsDao poolDetailsDao; - @Inject - DataStoreProviderManager providerMgr; - Long dcId = 1l; - Long podId = 1l; - Long clusterId = 1l; - Long volumeId = null; - Long diskOfferingId = null; - Long storagePoolId = null; - VolumeVO volume = null; - DiskOfferingVO diskOffering = null; - StoragePoolVO storage = null; + @Inject + PrimaryDataStoreDao storagePoolDao; + @Inject + StorageManager storageMgr; + @Inject + DiskOfferingDao diskOfferingDao; + @Inject + VolumeDao volumeDao; + @Inject + HostPodDao podDao; + @Inject + ClusterDao clusterDao; + @Inject + DataCenterDao dcDao; + @Inject + StoragePoolDetailsDao poolDetailsDao; + @Inject + DataStoreProviderManager providerMgr; + Long dcId = 1l; + Long podId = 1l; + Long clusterId = 1l; + Long volumeId = null; + Long diskOfferingId = null; + Long storagePoolId = null; + VolumeVO volume = null; + DiskOfferingVO diskOffering = null; + StoragePoolVO storage = null; - @Before - public void setup() throws Exception { - ComponentContext.initComponentsLifeCycle(); + @Before + public void setup() throws Exception { + ComponentContext.initComponentsLifeCycle(); - } + } - protected void createDb() { - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); - dc = dcDao.persist(dc); - dcId = dc.getId(); + protected void createDb() { + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); + dc = dcDao.persist(dc); + dcId = dc.getId(); - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), "255.255.255.255", "", 8, "test"); - pod = podDao.persist(pod); - podId = pod.getId(); - - ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); - cluster.setHypervisorType(HypervisorType.XenServer.toString()); - cluster.setClusterType(ClusterType.CloudManaged); - cluster.setManagedState(ManagedState.Managed); - cluster = clusterDao.persist(cluster); - clusterId = cluster.getId(); + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), "255.255.255.255", "", 8, "test"); + pod = podDao.persist(pod); + podId = pod.getId(); - DataStoreProvider provider = providerMgr.getDataStoreProvider("cloudstack primary data store provider"); - storage = new StoragePoolVO(); - storage.setDataCenterId(dcId); - storage.setPodId(podId); - storage.setPoolType(StoragePoolType.NetworkFilesystem); - storage.setClusterId(clusterId); - storage.setStatus(StoragePoolStatus.Up); - storage.setScope(ScopeType.CLUSTER); - storage.setAvailableBytes(1000); - storage.setCapacityBytes(20000); - storage.setHostAddress(UUID.randomUUID().toString()); - storage.setPath(UUID.randomUUID().toString()); - storage.setStorageProviderName(provider.getName()); - storage = storagePoolDao.persist(storage); - storagePoolId = storage.getId(); + ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); + cluster.setHypervisorType(HypervisorType.XenServer.toString()); + cluster.setClusterType(ClusterType.CloudManaged); + cluster.setManagedState(ManagedState.Managed); + cluster = clusterDao.persist(cluster); + clusterId = cluster.getId(); - storageMgr.createCapacityEntry(storage.getId()); + DataStoreProvider provider = providerMgr.getDataStoreProvider("cloudstack primary data store provider"); + storage = new StoragePoolVO(); + storage.setDataCenterId(dcId); + storage.setPodId(podId); + storage.setPoolType(StoragePoolType.NetworkFilesystem); + storage.setClusterId(clusterId); + storage.setStatus(StoragePoolStatus.Up); + storage.setScope(ScopeType.CLUSTER); + storage.setAvailableBytes(1000); + storage.setCapacityBytes(20000); + storage.setHostAddress(UUID.randomUUID().toString()); + storage.setPath(UUID.randomUUID().toString()); + storage.setStorageProviderName(provider.getName()); + storage = storagePoolDao.persist(storage); + storagePoolId = storage.getId(); - diskOffering = new DiskOfferingVO(); - diskOffering.setDiskSize(500); - diskOffering.setName("test-disk"); - diskOffering.setSystemUse(false); - diskOffering.setUseLocalStorage(false); - diskOffering.setCustomized(false); - diskOffering.setRecreatable(false); - diskOffering = diskOfferingDao.persist(diskOffering); - diskOfferingId = diskOffering.getId(); + storageMgr.createCapacityEntry(storage.getId()); - volume = new VolumeVO(Volume.Type.ROOT, "volume", dcId, 1, 1, diskOffering.getId(), diskOffering.getDiskSize()); - volume = volumeDao.persist(volume); - volumeId = volume.getId(); - } - - - - @Inject - List allocators; - @Test - public void testClusterAllocatorMultiplePools() { - Long newStorageId = null; - try { - createDb(); - - DataStoreProvider provider = providerMgr.getDataStoreProvider("cloudstack primary data store provider"); - storage = new StoragePoolVO(); - storage.setDataCenterId(dcId); - storage.setPodId(podId); - storage.setPoolType(StoragePoolType.NetworkFilesystem); - storage.setClusterId(clusterId); - storage.setStatus(StoragePoolStatus.Up); - storage.setScope(ScopeType.CLUSTER); - storage.setAvailableBytes(1000); - storage.setCapacityBytes(20000); - storage.setHostAddress(UUID.randomUUID().toString()); - storage.setPath(UUID.randomUUID().toString()); - storage.setStorageProviderName(provider.getName()); - StoragePoolVO newStorage = storagePoolDao.persist(storage); - newStorageId = newStorage.getId(); - - DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.XenServer); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - Assert.assertEquals(pools.size(), 1); - foundAcct++; - } - } + diskOffering = new DiskOfferingVO(); + diskOffering.setDiskSize(500); + diskOffering.setName("test-disk"); + diskOffering.setSystemUse(false); + diskOffering.setUseLocalStorage(false); + diskOffering.setCustomized(false); + diskOffering.setRecreatable(false); + diskOffering = diskOfferingDao.persist(diskOffering); + diskOfferingId = diskOffering.getId(); - if (foundAcct > 1 || foundAcct == 0) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - - if (newStorageId != null) { - storagePoolDao.remove(newStorageId); - } - Assert.fail(); - } - } - - @Test - public void testClusterAllocator() { - try { - createDb(); - DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.XenServer); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - Assert.assertEquals(pools.get(0).getId(), storage.getId()); - foundAcct++; - } - } + volume = new VolumeVO(Volume.Type.ROOT, "volume", dcId, 1, 1, diskOffering.getId(), diskOffering.getDiskSize()); + volume = volumeDao.persist(volume); + volumeId = volume.getId(); + } - if (foundAcct > 1 || foundAcct == 0) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - Assert.fail(); - } - } - - - @Test - public void testClusterAllocatorWithTags() { - try { - createDb(); - StoragePoolDetailVO detailVO = new StoragePoolDetailVO(this.storagePoolId, "high", "true"); - poolDetailsDao.persist(detailVO); - DiskOfferingVO diskOff = this.diskOfferingDao.findById(diskOffering.getId()); - List tags = new ArrayList(); - tags.add("high"); - diskOff.setTagsArray(tags); - diskOfferingDao.update(diskOff.getId(), diskOff); - - DiskProfile profile = new DiskProfile(volume, diskOff, HypervisorType.XenServer); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - Assert.assertEquals(pools.get(0).getId(), storage.getId()); - foundAcct++; - } - } + @Inject + List allocators; - if (foundAcct > 1 || foundAcct == 0) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - Assert.fail(); - } - } - - @Test - public void testClusterAllocatorWithWrongTag() { - try { - createDb(); - StoragePoolDetailVO detailVO = new StoragePoolDetailVO(this.storagePoolId, "high", "true"); - poolDetailsDao.persist(detailVO); - DiskOfferingVO diskOff = this.diskOfferingDao.findById(diskOffering.getId()); - List tags = new ArrayList(); - tags.add("low"); - diskOff.setTagsArray(tags); - diskOfferingDao.update(diskOff.getId(), diskOff); - - DiskProfile profile = new DiskProfile(volume, diskOff, HypervisorType.XenServer); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - foundAcct++; - } - } + @Test + public void testClusterAllocatorMultiplePools() { + Long newStorageId = null; + try { + createDb(); - if (foundAcct != 0) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - Assert.fail(); - } - } - - @Test - public void testZoneWideStorageAllocator() { - try { - createDb(); - - StoragePoolVO pool = storagePoolDao.findById(storagePoolId); - pool.setScope(ScopeType.ZONE); - storagePoolDao.update(pool.getId(), pool); - - DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.KVM); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(vmProfile.getHypervisorType()).thenReturn(HypervisorType.KVM); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - Assert.assertEquals(pools.get(0).getId(), storage.getId()); - foundAcct++; - } - } + DataStoreProvider provider = providerMgr.getDataStoreProvider("cloudstack primary data store provider"); + storage = new StoragePoolVO(); + storage.setDataCenterId(dcId); + storage.setPodId(podId); + storage.setPoolType(StoragePoolType.NetworkFilesystem); + storage.setClusterId(clusterId); + storage.setStatus(StoragePoolStatus.Up); + storage.setScope(ScopeType.CLUSTER); + storage.setAvailableBytes(1000); + storage.setCapacityBytes(20000); + storage.setHostAddress(UUID.randomUUID().toString()); + storage.setPath(UUID.randomUUID().toString()); + storage.setStorageProviderName(provider.getName()); + StoragePoolVO newStorage = storagePoolDao.persist(storage); + newStorageId = newStorage.getId(); - if (foundAcct > 1 || foundAcct == 0) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - Assert.fail(); - } - } - - @Test - public void testPoolStateIsNotUp() { - try { - createDb(); - - StoragePoolVO pool = storagePoolDao.findById(storagePoolId); - pool.setScope(ScopeType.ZONE); - pool.setStatus(StoragePoolStatus.Maintenance); - storagePoolDao.update(pool.getId(), pool); - - DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.XenServer); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - Assert.assertEquals(pools.get(0).getId(), storage.getId()); - foundAcct++; - } - } + DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.XenServer); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + Assert.assertEquals(pools.size(), 1); + foundAcct++; + } + } - if (foundAcct == 1) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - Assert.fail(); - } - } - - - - - @Test - public void testLocalStorageAllocator() { - try { - createDb(); - - StoragePoolVO pool = storagePoolDao.findById(storagePoolId); - pool.setScope(ScopeType.HOST); - storagePoolDao.update(pool.getId(), pool); - - DiskOfferingVO diskOff = diskOfferingDao.findById(diskOfferingId); - diskOff.setUseLocalStorage(true); - diskOfferingDao.update(diskOfferingId, diskOff); - - DiskProfile profile = new DiskProfile(volume, diskOff, HypervisorType.XenServer); - VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); - Mockito.when(storageMgr.storagePoolHasEnoughSpace( - Mockito.anyListOf(Volume.class), Mockito.any(StoragePool.class))).thenReturn(true); - DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); - int foundAcct = 0; - for (StoragePoolAllocator allocator : allocators) { - List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); - if (!pools.isEmpty()) { - Assert.assertEquals(pools.get(0).getId(), storage.getId()); - foundAcct++; - } - } + if (foundAcct > 1 || foundAcct == 0) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); - if (foundAcct > 1 || foundAcct == 0) { - Assert.fail(); - } - } catch (Exception e) { - cleanDb(); - Assert.fail(); - } - } - - protected void cleanDb() { - if (volumeId != null) { - volumeDao.remove(volumeId); - volumeId = null; - } - if (diskOfferingId != null) { - diskOfferingDao.remove(diskOfferingId); - diskOfferingId = null; - } - if (storagePoolId != null) { - storagePoolDao.remove(storagePoolId); - storagePoolId = null; - } - if (clusterId != null) { - clusterDao.remove(clusterId); - clusterId = null; - } - if (podId != null) { - podDao.remove(podId); - podId = null; - } - if (dcId != null) { - dcDao.remove(dcId); - dcId = null; - } - } + if (newStorageId != null) { + storagePoolDao.remove(newStorageId); + } + Assert.fail(); + } + } + + @Test + public void testClusterAllocator() { + try { + createDb(); + DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.XenServer); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + Assert.assertEquals(pools.get(0).getId(), storage.getId()); + foundAcct++; + } + } + + if (foundAcct > 1 || foundAcct == 0) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); + Assert.fail(); + } + } + + @Test + public void testClusterAllocatorWithTags() { + try { + createDb(); + StoragePoolDetailVO detailVO = new StoragePoolDetailVO(this.storagePoolId, "high", "true"); + poolDetailsDao.persist(detailVO); + DiskOfferingVO diskOff = this.diskOfferingDao.findById(diskOffering.getId()); + List tags = new ArrayList(); + tags.add("high"); + diskOff.setTagsArray(tags); + diskOfferingDao.update(diskOff.getId(), diskOff); + + DiskProfile profile = new DiskProfile(volume, diskOff, HypervisorType.XenServer); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + Assert.assertEquals(pools.get(0).getId(), storage.getId()); + foundAcct++; + } + } + + if (foundAcct > 1 || foundAcct == 0) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); + Assert.fail(); + } + } + + @Test + public void testClusterAllocatorWithWrongTag() { + try { + createDb(); + StoragePoolDetailVO detailVO = new StoragePoolDetailVO(this.storagePoolId, "high", "true"); + poolDetailsDao.persist(detailVO); + DiskOfferingVO diskOff = this.diskOfferingDao.findById(diskOffering.getId()); + List tags = new ArrayList(); + tags.add("low"); + diskOff.setTagsArray(tags); + diskOfferingDao.update(diskOff.getId(), diskOff); + + DiskProfile profile = new DiskProfile(volume, diskOff, HypervisorType.XenServer); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + foundAcct++; + } + } + + if (foundAcct != 0) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); + Assert.fail(); + } + } + + @Test + public void testZoneWideStorageAllocator() { + try { + createDb(); + + StoragePoolVO pool = storagePoolDao.findById(storagePoolId); + pool.setScope(ScopeType.ZONE); + storagePoolDao.update(pool.getId(), pool); + + DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.KVM); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when(vmProfile.getHypervisorType()).thenReturn(HypervisorType.KVM); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + Assert.assertEquals(pools.get(0).getId(), storage.getId()); + foundAcct++; + } + } + + if (foundAcct > 1 || foundAcct == 0) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); + Assert.fail(); + } + } + + @Test + public void testPoolStateIsNotUp() { + try { + createDb(); + + StoragePoolVO pool = storagePoolDao.findById(storagePoolId); + pool.setScope(ScopeType.ZONE); + pool.setStatus(StoragePoolStatus.Maintenance); + storagePoolDao.update(pool.getId(), pool); + + DiskProfile profile = new DiskProfile(volume, diskOffering, HypervisorType.XenServer); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + Assert.assertEquals(pools.get(0).getId(), storage.getId()); + foundAcct++; + } + } + + if (foundAcct == 1) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); + Assert.fail(); + } + } + + @Test + public void testLocalStorageAllocator() { + try { + createDb(); + + StoragePoolVO pool = storagePoolDao.findById(storagePoolId); + pool.setScope(ScopeType.HOST); + storagePoolDao.update(pool.getId(), pool); + + DiskOfferingVO diskOff = diskOfferingDao.findById(diskOfferingId); + diskOff.setUseLocalStorage(true); + diskOfferingDao.update(diskOfferingId, diskOff); + + DiskProfile profile = new DiskProfile(volume, diskOff, HypervisorType.XenServer); + VirtualMachineProfile vmProfile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when( + storageMgr.storagePoolHasEnoughSpace(Matchers.anyListOf(Volume.class), + Matchers.any(StoragePool.class))).thenReturn(true); + DeploymentPlan plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); + int foundAcct = 0; + for (StoragePoolAllocator allocator : allocators) { + List pools = allocator.allocateToPool(profile, vmProfile, plan, new ExcludeList(), 1); + if (!pools.isEmpty()) { + Assert.assertEquals(pools.get(0).getId(), storage.getId()); + foundAcct++; + } + } + + if (foundAcct > 1 || foundAcct == 0) { + Assert.fail(); + } + } catch (Exception e) { + cleanDb(); + Assert.fail(); + } + } + + protected void cleanDb() { + if (volumeId != null) { + volumeDao.remove(volumeId); + volumeId = null; + } + if (diskOfferingId != null) { + diskOfferingDao.remove(diskOfferingId); + diskOfferingId = null; + } + if (storagePoolId != null) { + storagePoolDao.remove(storagePoolId); + storagePoolId = null; + } + if (clusterId != null) { + clusterDao.remove(clusterId); + clusterId = null; + } + if (podId != null) { + podDao.remove(podId); + podId = null; + } + if (dcId != null) { + dcDao.remove(dcId); + dcId = null; + } + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTestConfiguration.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTestConfiguration.java index 4790086b2e1..e3172176f9a 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTestConfiguration.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/allocator/StorageAllocatorTestConfiguration.java @@ -39,35 +39,28 @@ import com.cloud.storage.dao.StoragePoolDetailsDaoImpl; import com.cloud.storage.dao.VMTemplateDaoImpl; import com.cloud.vm.UserVmManager; - @Configuration -@ComponentScan(basePackageClasses={ - StoragePoolDetailsDaoImpl.class, - PrimaryDataStoreDaoImpl.class, - VMTemplateDaoImpl.class, - HostDaoImpl.class, - DomainDaoImpl.class, - DataCenterDaoImpl.class}, - includeFilters={@Filter(value=Library.class, type=FilterType.CUSTOM)}, - useDefaultFilters=false - ) +@ComponentScan(basePackageClasses = { StoragePoolDetailsDaoImpl.class, PrimaryDataStoreDaoImpl.class, + VMTemplateDaoImpl.class, HostDaoImpl.class, DomainDaoImpl.class, DataCenterDaoImpl.class }, + includeFilters = { @Filter(value = Library.class, type = FilterType.CUSTOM) }, useDefaultFilters = false) public class StorageAllocatorTestConfiguration { - @Bean - public UserVmManager UserVmManager() { - return Mockito.mock(UserVmManager.class); - } - @Bean - public StorageManager StorageManager() { - return Mockito.mock(StorageManager.class); - } + @Bean + public UserVmManager UserVmManager() { + return Mockito.mock(UserVmManager.class); + } - public static class Library implements TypeFilter { + @Bean + public StorageManager StorageManager() { + return Mockito.mock(StorageManager.class); + } - @Override - public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { - mdr.getClassMetadata().getClassName(); - ComponentScan cs = StorageAllocatorTestConfiguration.class.getAnnotation(ComponentScan.class); - return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs); - } - } + public static class Library implements TypeFilter { + + @Override + public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { + mdr.getClassMetadata().getClassName(); + ComponentScan cs = StorageAllocatorTestConfiguration.class.getAnnotation(ComponentScan.class); + return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs); + } + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTest.java index bde5804e624..3fee7ac3bea 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTest.java @@ -23,7 +23,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; -@Target({TYPE, METHOD}) +@Target({ TYPE, METHOD }) @Retention(RUNTIME) public @interface AopTest { diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTestAdvice.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTestAdvice.java index 63669c453d7..902f5953eb1 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTestAdvice.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AopTestAdvice.java @@ -21,14 +21,14 @@ import org.aspectj.lang.ProceedingJoinPoint; import com.cloud.utils.db.Transaction; public class AopTestAdvice { - public Object AopTestMethod(ProceedingJoinPoint call) throws Throwable { - Transaction txn = Transaction.open(call.getSignature().getName()); - Object ret = null; - try { - ret = call.proceed(); - } finally { - txn.close(); - } - return ret; - } + public Object AopTestMethod(ProceedingJoinPoint call) throws Throwable { + Transaction txn = Transaction.open(call.getSignature().getName()); + Object ret = null; + try { + ret = call.proceed(); + } finally { + txn.close(); + } + return ret; + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java index acb61069074..60f86d86ddb 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java @@ -22,11 +22,7 @@ import org.apache.cloudstack.acl.APIChecker; import org.apache.cloudstack.engine.service.api.OrchestrationService; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.framework.rpc.RpcProvider; -import org.apache.cloudstack.storage.HostEndpointRpcServer; import org.apache.cloudstack.storage.cache.manager.StorageCacheManagerImpl; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.image.db.ImageStoreDaoImpl; -import org.apache.cloudstack.storage.image.db.ImageStoreDetailsDaoImpl; import org.apache.cloudstack.storage.test.ChildTestConfiguration.Library; import org.apache.cloudstack.test.utils.SpringUtils; import org.mockito.Mockito; @@ -79,7 +75,6 @@ import com.cloud.storage.dao.VMTemplatePoolDaoImpl; import com.cloud.storage.dao.VMTemplateZoneDaoImpl; import com.cloud.storage.dao.VolumeDaoImpl; import com.cloud.storage.dao.VolumeHostDaoImpl; -import com.cloud.storage.download.DownloadMonitor; import com.cloud.storage.download.DownloadMonitorImpl; import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; @@ -98,164 +93,138 @@ 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.VMInstanceDao; import com.cloud.vm.dao.VMInstanceDaoImpl; import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl; -@Configuration -@ComponentScan(basePackageClasses={ - NicDaoImpl.class, - VMInstanceDaoImpl.class, - VMTemplateHostDaoImpl.class, - VolumeHostDaoImpl.class, - VolumeDaoImpl.class, - VMTemplatePoolDaoImpl.class, - ResourceTagsDaoImpl.class, - VMTemplateDaoImpl.class, - MockStorageMotionStrategy.class, - ConfigurationDaoImpl.class, - ClusterDaoImpl.class, - HostPodDaoImpl.class, - VMTemplateZoneDaoImpl.class, - VMTemplateDetailsDaoImpl.class, - HostDetailsDaoImpl.class, - HostTagsDaoImpl.class, - HostTransferMapDaoImpl.class, - DataCenterIpAddressDaoImpl.class, - DataCenterLinkLocalIpAddressDaoImpl.class, - DataCenterVnetDaoImpl.class, - PodVlanDaoImpl.class, - DcDetailsDaoImpl.class, - DiskOfferingDaoImpl.class, - StoragePoolHostDaoImpl.class, - UserVmDaoImpl.class, - UserVmDetailsDaoImpl.class, - ServiceOfferingDaoImpl.class, - CapacityDaoImpl.class, - SnapshotDaoImpl.class, - VMSnapshotDaoImpl.class, - OCFS2ManagerImpl.class, - ClusterDetailsDaoImpl.class, - SecondaryStorageVmDaoImpl.class, - ConsoleProxyDaoImpl.class, - StoragePoolWorkDaoImpl.class, - StorageCacheManagerImpl.class, - UserDaoImpl.class, - DataCenterDaoImpl.class, - StoragePoolDetailsDaoImpl.class, - DomainDaoImpl.class, - DownloadMonitorImpl.class, - AccountDaoImpl.class -}, -includeFilters={@Filter(value=Library.class, type=FilterType.CUSTOM)}, -useDefaultFilters=false -) -public class ChildTestConfiguration extends TestConfiguration { - - @Bean - public SecondaryStorageVmManager secondaryStoreageMgr() { - return Mockito.mock(SecondaryStorageVmManager.class); - } - @Bean - public HostDao hostDao() { - return Mockito.spy(new HostDaoImpl()); - } - - @Bean - public EndPointSelector selector() { - return Mockito.mock(EndPointSelector.class); - } - @Bean - public AgentManager agentMgr() { - return new DirectAgentManagerSimpleImpl(); - } - +@Configuration +@ComponentScan(basePackageClasses = { NicDaoImpl.class, VMInstanceDaoImpl.class, VMTemplateHostDaoImpl.class, + VolumeHostDaoImpl.class, VolumeDaoImpl.class, VMTemplatePoolDaoImpl.class, ResourceTagsDaoImpl.class, + VMTemplateDaoImpl.class, MockStorageMotionStrategy.class, ConfigurationDaoImpl.class, ClusterDaoImpl.class, + HostPodDaoImpl.class, VMTemplateZoneDaoImpl.class, VMTemplateDetailsDaoImpl.class, HostDetailsDaoImpl.class, + HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, DataCenterIpAddressDaoImpl.class, + DataCenterLinkLocalIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, + DcDetailsDaoImpl.class, DiskOfferingDaoImpl.class, StoragePoolHostDaoImpl.class, UserVmDaoImpl.class, + UserVmDetailsDaoImpl.class, ServiceOfferingDaoImpl.class, CapacityDaoImpl.class, SnapshotDaoImpl.class, + VMSnapshotDaoImpl.class, OCFS2ManagerImpl.class, ClusterDetailsDaoImpl.class, SecondaryStorageVmDaoImpl.class, + ConsoleProxyDaoImpl.class, StoragePoolWorkDaoImpl.class, StorageCacheManagerImpl.class, UserDaoImpl.class, + DataCenterDaoImpl.class, StoragePoolDetailsDaoImpl.class, DomainDaoImpl.class, DownloadMonitorImpl.class, + AccountDaoImpl.class }, includeFilters = { @Filter(value = Library.class, type = FilterType.CUSTOM) }, + useDefaultFilters = false) +public class ChildTestConfiguration extends TestConfiguration { + @Bean - public HostEndpointRpcServer rpcServer() { - return new MockHostEndpointRpcServerDirectCallResource(); + public SecondaryStorageVmManager secondaryStoreageMgr() { + return Mockito.mock(SecondaryStorageVmManager.class); } - + + @Bean + public HostDao hostDao() { + return Mockito.spy(new HostDaoImpl()); + } + + @Bean + public EndPointSelector selector() { + return Mockito.mock(EndPointSelector.class); + } + + @Bean + public AgentManager agentMgr() { + return new DirectAgentManagerSimpleImpl(); + } + @Bean public ResourceLimitService limtServe() { return Mockito.mock(ResourceLimitService.class); } - + @Bean public AccountManager acctMgt() { return Mockito.mock(AccountManager.class); } + @Bean public RpcProvider rpcProvider() { - return Mockito.mock(RpcProvider.class); + return Mockito.mock(RpcProvider.class); } + @Bean public ClusteredAgentRebalanceService _rebalanceService() { return Mockito.mock(ClusteredAgentRebalanceService.class); } + @Bean public UserAuthenticator authenticator() { return Mockito.mock(UserAuthenticator.class); } + @Bean public OrchestrationService orchSrvc() { return Mockito.mock(OrchestrationService.class); } + @Bean public APIChecker apiChecker() { return Mockito.mock(APIChecker.class); } + @Bean public TemplateManager templateMgr() { - return Mockito.mock(TemplateManager.class); + return Mockito.mock(TemplateManager.class); } - + @Bean public VolumeManager volumeMgr() { - return Mockito.mock(VolumeManager.class); + return Mockito.mock(VolumeManager.class); } + @Bean public SwiftManager switfMgr() { - return Mockito.mock(SwiftManager.class); + return Mockito.mock(SwiftManager.class); } + @Bean public ManagementServer server() { - return Mockito.mock(ManagementServer.class); + return Mockito.mock(ManagementServer.class); } + @Bean public VirtualMachineManager vmMgr() { - return Mockito.mock(VirtualMachineManager.class); + return Mockito.mock(VirtualMachineManager.class); } - + @Bean public S3Manager s3Mgr() { - return Mockito.mock(S3Manager.class); + return Mockito.mock(S3Manager.class); } + @Bean public SnapshotManager snapshotMgr() { return Mockito.mock(SnapshotManager.class); } - + @Bean public ResourceManager resourceMgr() { - return Mockito.mock(ResourceManager.class); + return Mockito.mock(ResourceManager.class); } + @Bean public DomainRouterDao domainRouterDao() { - return Mockito.mock(DomainRouterDao.class); + return Mockito.mock(DomainRouterDao.class); } + @Bean public StorageManager storageMgr() { - return Mockito.mock(StorageManager.class); + return Mockito.mock(StorageManager.class); } - + @Bean public AlertManager alertMgr() { return Mockito.mock(AlertManager.class); } - + @Bean public HypervisorGuruManager hypervisorGuruMgr() { - return Mockito.mock(HypervisorGuruManager.class); + return Mockito.mock(HypervisorGuruManager.class); } public static class Library implements TypeFilter { diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java index 726ea010c66..26f4c5da0e9 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java @@ -25,7 +25,6 @@ import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { @@ -54,12 +53,12 @@ public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { } @BeforeMethod(alwaysRun = true) - protected void injectDB(Method testMethod) throws Exception { + protected void injectDB(Method testMethod) throws Exception { txn = Transaction.open(testMethod.getName()); } @Test - protected void injectMockitoTest() { + protected void injectMockitoTest() { injectMockito(); } @@ -71,17 +70,14 @@ public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { } @BeforeMethod(alwaysRun = true) - - @Parameters({"devcloud-host-uuid", "devcloud-host-gateway", "devcloud-host-cidr", - "devcloud-host-ip", "template-url", "devcloud-local-storage-uuid", - "primary-storage-want-to-add", "devcloud-secondary-storage", "s3-accesskey", "s3-secretkey", "s3-endpoint", - "s3-template-bucket", "s3-usehttps", "image-install-path", "primary-storage-uuid-want-to-add", "script-path", - "hypervisor"}) - protected void setup(String hostuuid, String gateway, String cidr, - String hostIp, String templateUrl, String localStorageUuid, - String primaryStorage, String secondaryStorage, String s3_accessKey, String s3_secretKey, String s3_endpoint, String s3_template_bucket, - String s3_usehttps, String imageInstallPath, String primaryStorageUuid, String scriptPath, - String hypervisor) { + @Parameters({ "devcloud-host-uuid", "devcloud-host-gateway", "devcloud-host-cidr", "devcloud-host-ip", + "template-url", "devcloud-local-storage-uuid", "primary-storage-want-to-add", "devcloud-secondary-storage", + "s3-accesskey", "s3-secretkey", "s3-endpoint", "s3-template-bucket", "s3-usehttps", "image-install-path", + "primary-storage-uuid-want-to-add", "script-path", "hypervisor" }) + protected void setup(String hostuuid, String gateway, String cidr, String hostIp, String templateUrl, + String localStorageUuid, String primaryStorage, String secondaryStorage, String s3_accessKey, + String s3_secretKey, String s3_endpoint, String s3_template_bucket, String s3_usehttps, + String imageInstallPath, String primaryStorageUuid, String scriptPath, String hypervisor) { this.hostGuid = hostuuid; this.hostGateway = gateway; this.hostCidr = cidr; @@ -133,14 +129,13 @@ public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { return this.primaryStorageUrl; } - public String getSecondaryStorage() { - return secondaryStorage; - } - - public void setSecondaryStorage(String secondaryStorage) { - this.secondaryStorage = secondaryStorage; - } + public String getSecondaryStorage() { + return secondaryStorage; + } + public void setSecondaryStorage(String secondaryStorage) { + this.secondaryStorage = secondaryStorage; + } public String getS3AccessKey() { return s3AccessKey; @@ -186,13 +181,12 @@ public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { this.scriptPath = scriptPath; } - public HypervisorType getHypervisor() { - return hypervisor; - } - - public void setHypervisor(HypervisorType hypervisor) { - this.hypervisor = hypervisor; - } + public HypervisorType getHypervisor() { + return hypervisor; + } + public void setHypervisor(HypervisorType hypervisor) { + this.hypervisor = hypervisor; + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java index c11da3d8078..ac50e9bde95 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java @@ -26,7 +26,6 @@ import java.util.Map; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -66,6 +65,7 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa ClusterDao clusterDao; @Inject ClusterDetailsDao clusterDetailsDao; + @Override public boolean configure(String name, Map params) throws ConfigurationException { // TODO Auto-generated method stub @@ -92,16 +92,16 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa @Override public Answer easySend(Long hostId, Command cmd) { - try { - return this.send(hostId, cmd); - } catch (AgentUnavailableException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (OperationTimedoutException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; + try { + return this.send(hostId, cmd); + } catch (AgentUnavailableException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (OperationTimedoutException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; } protected void loadResource(Long hostId) { @@ -116,23 +116,23 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa ServerResource resource = null; if (host.getHypervisorType() == HypervisorType.XenServer) { - resource = new XcpOssResource(); - try { - resource.configure(host.getName(), params); - - } catch (ConfigurationException e) { - logger.debug("Failed to load resource:" + e.toString()); - } + resource = new XcpOssResource(); + try { + resource.configure(host.getName(), params); + + } catch (ConfigurationException e) { + logger.debug("Failed to load resource:" + e.toString()); + } } else if (host.getHypervisorType() == HypervisorType.KVM) { - resource = new LibvirtComputingResource(); - try { - params.put("public.network.device", "cloudbr0"); - params.put("private.network.device", "cloudbr0"); - resource.configure(host.getName(), params); - } catch (ConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + resource = new LibvirtComputingResource(); + try { + params.put("public.network.device", "cloudbr0"); + params.put("private.network.device", "cloudbr0"); + resource.configure(host.getName(), params); + } catch (ConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } else if (host.getHypervisorType() == HypervisorType.VMware) { ClusterVO cluster = clusterDao.findById(host.getClusterId()); String url = clusterDetailsDao.findDetail(cluster.getId(), "url").getValue(); @@ -143,7 +143,8 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa String password = clusterDetailsDao.findDetail(cluster.getId(), "password").getValue(); VmwareServerDiscoverer discover = new VmwareServerDiscoverer(); - Map> resources = discover.find(host.getDataCenterId(), host.getPodId(), host.getClusterId(), uri, userName, password, null); + Map> resources = discover.find(host.getDataCenterId(), + host.getPodId(), host.getClusterId(), uri, userName, password, null); for (Map.Entry> entry : resources.entrySet()) { resource = entry.getKey(); } @@ -168,7 +169,8 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa } @Override - public synchronized Answer send(Long hostId, Command cmd) throws AgentUnavailableException, OperationTimedoutException { + public synchronized Answer send(Long hostId, Command cmd) throws AgentUnavailableException, + OperationTimedoutException { ServerResource resource = hostResourcesMap.get(hostId); if (resource == null) { loadResource(hostId); @@ -190,7 +192,8 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa } @Override - public Answer[] send(Long hostId, Commands cmds, int timeout) throws AgentUnavailableException, OperationTimedoutException { + public Answer[] send(Long hostId, Commands cmds, int timeout) throws AgentUnavailableException, + OperationTimedoutException { // TODO Auto-generated method stub return null; } @@ -231,7 +234,6 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa return null; } - @Override public boolean tapLoadingAgents(Long hostId, TapAgentsAction action) { // TODO Auto-generated method stub @@ -239,7 +241,8 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa } @Override - public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, boolean forRebalance) throws ConnectionException { + public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, + boolean forRebalance) throws ConnectionException { // TODO Auto-generated method stub return null; } @@ -286,10 +289,10 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa return null; } - @Override - public void disconnectWithInvestigation(long hostId, Event event) { - // TODO Auto-generated method stub + @Override + public void disconnectWithInvestigation(long hostId, Event event) { + // TODO Auto-generated method stub - } + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentTest.java index ab09c50ff5c..d0cfa395d77 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentTest.java @@ -50,11 +50,11 @@ import com.cloud.org.Cluster.ClusterType; import com.cloud.org.Managed.ManagedState; import com.cloud.resource.ResourceState; -@ContextConfiguration(locations="classpath:/storageContext.xml") +@ContextConfiguration(locations = "classpath:/storageContext.xml") public class DirectAgentTest extends CloudStackTestNGBase { @Inject AgentManager agentMgr; - @Inject + @Inject HostDao hostDao; @Inject HostPodDao podDao; @@ -65,7 +65,7 @@ public class DirectAgentTest extends CloudStackTestNGBase { private long dcId; private long clusterId; private long hostId; - + @Test(priority = -1) public void setUp() { HostVO host = hostDao.findByGuid(getHostGuid()); @@ -75,23 +75,24 @@ public class DirectAgentTest extends CloudStackTestNGBase { clusterId = host.getClusterId(); return; } - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); dc = dcDao.persist(dc); dcId = dc.getId(); - //create pod + // create pod - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), getHostGateway(), getHostCidr(), 8, "test"); + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), getHostGateway(), getHostCidr(), 8, + "test"); pod = podDao.persist(pod); - //create xen cluster + // create xen cluster ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); cluster.setHypervisorType(HypervisorType.XenServer.toString()); cluster.setClusterType(ClusterType.CloudManaged); cluster.setManagedState(ManagedState.Managed); cluster = clusterDao.persist(cluster); clusterId = cluster.getId(); - //create xen host + // create xen host host = new HostVO(getHostGuid()); host.setName("devcloud xen host"); @@ -109,7 +110,7 @@ public class DirectAgentTest extends CloudStackTestNGBase { host = hostDao.persist(host); hostId = host.getId(); } - + @Test public void testInitResource() { ReadyCommand cmd = new ReadyCommand(dcId); @@ -123,23 +124,24 @@ public class DirectAgentTest extends CloudStackTestNGBase { e.printStackTrace(); } } - + @Test public void testDownloadTemplate() { ImageStoreTO image = Mockito.mock(ImageStoreTO.class); PrimaryDataStoreTO primaryStore = Mockito.mock(PrimaryDataStoreTO.class); Mockito.when(primaryStore.getUuid()).thenReturn(getLocalStorageUuid()); - //Mockito.when(image.get).thenReturn(primaryStore); - + // Mockito.when(image.get).thenReturn(primaryStore); + ImageStoreTO imageStore = Mockito.mock(ImageStoreTO.class); Mockito.when(imageStore.getProtocol()).thenReturn("http"); - + TemplateObjectTO template = Mockito.mock(TemplateObjectTO.class); Mockito.when(template.getPath()).thenReturn(getTemplateUrl()); Mockito.when(template.getImageDataStore()).thenReturn(imageStore); - - //Mockito.when(image.getTemplate()).thenReturn(template); - //CopyTemplateToPrimaryStorageCmd cmd = new CopyTemplateToPrimaryStorageCmd(image); + + // Mockito.when(image.getTemplate()).thenReturn(template); + // CopyTemplateToPrimaryStorageCmd cmd = new + // CopyTemplateToPrimaryStorageCmd(image); Command cmd = null; try { agentMgr.send(hostId, cmd); diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHostEndpointRpcServerDirectCallResource.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHostEndpointRpcServerDirectCallResource.java deleted file mode 100644 index 2e57ea9cb4a..00000000000 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHostEndpointRpcServerDirectCallResource.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage.test; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.inject.Inject; - -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.HostEndpointRpcServer; -import org.apache.cloudstack.storage.RemoteHostEndPoint; -import org.apache.log4j.Logger; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.utils.component.ComponentContext; - - -public class MockHostEndpointRpcServerDirectCallResource implements HostEndpointRpcServer { - private static final Logger s_logger = Logger.getLogger(MockHostEndpointRpcServerDirectCallResource.class); - private ScheduledExecutorService executor; - @Inject - AgentManager agentMgr; - public MockHostEndpointRpcServerDirectCallResource() { - executor = Executors.newScheduledThreadPool(10); - } - - public void sendCommandAsync(RemoteHostEndPoint host, final Command command, final AsyncCompletionCallback callback) { - // new MockRpcCallBack(host.getHostId(), command, callback); - MockRpcCallBack run = ComponentContext.inject(MockRpcCallBack.class); - run.setCallback(callback); - run.setCmd(command); - run.setHostId(host.getId()); - executor.schedule(run, 10, TimeUnit.SECONDS); - } - - @Override - public Answer sendCommand(RemoteHostEndPoint host, Command command) { - Answer answer; - try { - answer = agentMgr.send(host.getId(), command); - return answer; - } catch (AgentUnavailableException e) { - return null; - } catch (OperationTimedoutException e) { - return null; - } - } -} diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHypervisorHostEndPointRpcServer.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHypervisorHostEndPointRpcServer.java deleted file mode 100644 index e65963908d3..00000000000 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockHypervisorHostEndPointRpcServer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage.test; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.HostEndpointRpcServer; -import org.apache.cloudstack.storage.RemoteHostEndPoint; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; - -public class MockHypervisorHostEndPointRpcServer implements HostEndpointRpcServer { - private ScheduledExecutorService executor; - public MockHypervisorHostEndPointRpcServer() { - executor = Executors.newScheduledThreadPool(10); - } - - protected class MockRpcCallBack implements Runnable { - private final Command cmd; - private final AsyncCompletionCallback callback; - public MockRpcCallBack(Command cmd, final AsyncCompletionCallback callback) { - this.cmd = cmd; - this.callback = callback; - } - @Override - public void run() { - try { - Answer answer = new Answer(cmd, false, "unknown command"); - /*if (cmd instanceof CopyTemplateToPrimaryStorageCmd) { - answer = new CopyTemplateToPrimaryStorageAnswer(cmd, UUID.randomUUID().toString()); - } else if (cmd instanceof CreateVolumeFromBaseImageCommand) { - answer = new CreateVolumeAnswer(cmd, UUID.randomUUID().toString()); - }*/ - - callback.complete(answer); - } catch (Exception e) { - e.printStackTrace(); - } - } - - } - - public void sendCommandAsync(RemoteHostEndPoint host, final Command command, final AsyncCompletionCallback callback) { - executor.schedule(new MockRpcCallBack(command, callback), 10, TimeUnit.SECONDS); - } - - @Override - public Answer sendCommand(RemoteHostEndPoint host, Command command) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockLocalHostEndPoint.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockLocalHostEndPoint.java index 28a586f83e5..26c1a634b1e 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockLocalHostEndPoint.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockLocalHostEndPoint.java @@ -27,12 +27,13 @@ import com.cloud.agent.api.Command; import com.cloud.agent.api.DeleteSnapshotBackupCommand; public class MockLocalHostEndPoint extends LocalHostEndpoint { - @Override - public Answer sendMessage(Command cmd) { - if ((cmd instanceof CopyCommand) || (cmd instanceof DownloadCommand) || (cmd instanceof DeleteSnapshotBackupCommand)) { - return resource.executeRequest(cmd); - } - // TODO Auto-generated method stub - return new Answer(cmd, false, "unsupported command:" + cmd.toString()); - } + @Override + public Answer sendMessage(Command cmd) { + if ((cmd instanceof CopyCommand) || (cmd instanceof DownloadCommand) + || (cmd instanceof DeleteSnapshotBackupCommand)) { + return resource.executeRequest(cmd); + } + // TODO Auto-generated method stub + return new Answer(cmd, false, "unsupported command:" + cmd.toString()); + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockRpcCallBack.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockRpcCallBack.java index e0ffb48281a..60308da274b 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockRpcCallBack.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockRpcCallBack.java @@ -32,20 +32,20 @@ public class MockRpcCallBack implements Runnable { AgentManager agentMgr; private Command cmd; private long hostId; - private AsyncCompletionCallback callback; - + private AsyncCompletionCallback callback; + public void setCmd(Command cmd) { this.cmd = cmd; } - + public void setHostId(long hostId) { this.hostId = hostId; } - + public void setCallback(AsyncCompletionCallback callback) { this.callback = callback; } - + @Override @DB public void run() { @@ -56,5 +56,5 @@ public class MockRpcCallBack implements Runnable { s_logger.debug("send command failed:", e); } } - + } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockStorageMotionStrategy.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockStorageMotionStrategy.java index edec9770cfa..52ccf410c8d 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockStorageMotionStrategy.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/MockStorageMotionStrategy.java @@ -32,7 +32,6 @@ import com.cloud.host.Host; public class MockStorageMotionStrategy implements DataMotionStrategy { - @Override public boolean canHandle(DataObject srcData, DataObject destData) { // TODO Auto-generated method stub @@ -45,8 +44,7 @@ public class MockStorageMotionStrategy implements DataMotionStrategy { } @Override - public Void copyAsync(DataObject srcData, DataObject destData, - AsyncCompletionCallback callback) { + public Void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback) { CopyCommandResult result = new CopyCommandResult("something", null); callback.complete(result); return null; diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/S3TemplateTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/S3TemplateTest.java index d88e6dad176..0bb724d10e4 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/S3TemplateTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/S3TemplateTest.java @@ -42,6 +42,7 @@ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.image.datastore.ImageStoreHelper; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; @@ -59,42 +60,41 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.download.DownloadMonitorImpl; import com.cloud.utils.component.ComponentContext; -@ContextConfiguration(locations={"classpath:/storageContext.xml"}) - +@ContextConfiguration(locations = { "classpath:/storageContext.xml" }) public class S3TemplateTest extends CloudStackTestNGBase { - @Inject - DataCenterDao dcDao; - ImageStoreVO imageStore; - ImageStoreDetailVO imageStoreDetail; - @Inject - ImageStoreDao imageStoreDao; - @Inject - TemplateService templateSvr; - @Inject - VMTemplateDao templateDao; - @Inject - TemplateDataFactory templateFactory; - @Inject - DataStoreManager dataStoreMgr; - @Inject - EndPointSelector epSelector; - @Inject - DownloadMonitorImpl downloadMonitor; - @Inject - ImageStoreHelper imageStoreHelper; - @Inject - StorageCacheManager cacheMgr; - long dcId; - long templateId; + @Inject + DataCenterDao dcDao; + ImageStoreVO imageStore; + ImageStoreDetailVO imageStoreDetail; + @Inject + ImageStoreDao imageStoreDao; + @Inject + TemplateService templateSvr; + @Inject + VMTemplateDao templateDao; + @Inject + TemplateDataFactory templateFactory; + @Inject + DataStoreManager dataStoreMgr; + @Inject + EndPointSelector epSelector; + @Inject + DownloadMonitorImpl downloadMonitor; + @Inject + ImageStoreHelper imageStoreHelper; + @Inject + StorageCacheManager cacheMgr; + long dcId; + long templateId; - @Test(priority = -1) - public void setUp() { - ComponentContext.initComponentsLifeCycle(); - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); - dc = dcDao.persist(dc); - dcId = dc.getId(); + @Test(priority = -1) + public void setUp() { + ComponentContext.initComponentsLifeCycle(); + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); + dc = dcDao.persist(dc); + dcId = dc.getId(); // add s3 image store Map sParams = new HashMap(); @@ -121,55 +121,54 @@ public class S3TemplateTest extends CloudStackTestNGBase { cParams.put("zoneId", dcId); this.imageStoreHelper.createImageStore(cParams); + VMTemplateVO image = new VMTemplateVO(); + image.setTemplateType(TemplateType.SYSTEM); + image.setUrl(this.getTemplateUrl()); + image.setUniqueName(UUID.randomUUID().toString()); + image.setName(UUID.randomUUID().toString()); + image.setPublicTemplate(false); + image.setFeatured(false); + image.setRequiresHvm(false); + image.setBits(64); + image.setFormat(Storage.ImageFormat.VHD); + image.setEnablePassword(false); + image.setEnableSshKey(false); + image.setGuestOSId(133); + image.setBootable(true); + image.setPrepopulate(true); + image.setCrossZones(true); + image.setExtractable(true); + image.setAccountId(2); + image = templateDao.persist(image); + templateId = image.getId(); - VMTemplateVO image = new VMTemplateVO(); - image.setTemplateType(TemplateType.SYSTEM); - image.setUrl(this.getTemplateUrl()); - image.setUniqueName(UUID.randomUUID().toString()); - image.setName(UUID.randomUUID().toString()); - image.setPublicTemplate(false); - image.setFeatured(false); - image.setRequiresHvm(false); - image.setBits(64); - image.setFormat(Storage.ImageFormat.VHD); - image.setEnablePassword(false); - image.setEnableSshKey(false); - image.setGuestOSId(133); - image.setBootable(true); - image.setPrepopulate(true); - image.setCrossZones(true); - image.setExtractable(true); - image.setAccountId(2); - image = templateDao.persist(image); - templateId = image.getId(); + // inject mockito + LocalHostEndpoint ep = new LocalHostEndpoint(); + ep.setResource(new MockLocalNfsSecondaryStorageResource()); + Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(ep); + } - // inject mockito - LocalHostEndpoint ep = new LocalHostEndpoint(); - ep.setResource(new MockLocalNfsSecondaryStorageResource()); - Mockito.when(epSelector.select(Mockito.any(DataObject.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataObject.class), Mockito.any(DataObject.class))).thenReturn(ep); - } - - @Test(priority = 1) - public void registerTemplate() { - TemplateInfo template = templateFactory.getTemplate(templateId, DataStoreRole.Image); - DataStore store = dataStoreMgr.getImageStore(dcId); - AsyncCallFuture future = new AsyncCallFuture(); - templateSvr.createTemplateAsync(template, store, future); - try { - TemplateApiResult result = future.get(); - assertTrue(result.isSuccess(), "failed to register template: " + result.getResult()); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - assertTrue(false, e.getMessage()); - } catch (ExecutionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - assertTrue(false, e.getMessage()); - } - } + @Test(priority = 1) + public void registerTemplate() { + TemplateInfo template = templateFactory.getTemplate(templateId, DataStoreRole.Image); + DataStore store = dataStoreMgr.getImageStore(dcId); + AsyncCallFuture future = new AsyncCallFuture(); + templateSvr.createTemplateAsync(template, store, future); + try { + TemplateApiResult result = future.get(); + assertTrue(result.isSuccess(), "failed to register template: " + result.getResult()); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertTrue(false, e.getMessage()); + } catch (ExecutionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertTrue(false, e.getMessage()); + } + } @Test(priority = 2) public void copyTemplateToCache() { diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java index 503b8d36350..8210dfe45bd 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java @@ -44,7 +44,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult; -import org.apache.cloudstack.engine.subsystem.api.storage.type.RootDisk; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.storage.LocalHostEndpoint; import org.apache.cloudstack.storage.MockLocalNfsSecondaryStorageResource; @@ -56,6 +55,7 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.to.TemplateObjectTO; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; @@ -97,7 +97,7 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; -@ContextConfiguration(locations={"classpath:/storageContext.xml"}) +@ContextConfiguration(locations = { "classpath:/storageContext.xml" }) public class SnapshotTest extends CloudStackTestNGBase { @Inject ImageStoreDao imageStoreDao; @@ -142,7 +142,8 @@ public class SnapshotTest extends CloudStackTestNGBase { ResourceManager resourceMgr; @Inject VolumeDataFactory volFactory; - @Inject SnapshotDataFactory snapshotFactory; + @Inject + SnapshotDataFactory snapshotFactory; @Inject List snapshotStrategies; @Inject @@ -158,6 +159,7 @@ public class SnapshotTest extends CloudStackTestNGBase { VMTemplateVO image; String imageStoreName = "testImageStore"; RemoteHostEndPoint remoteEp; + @Test(priority = -1) public void setUp() { ComponentContext.initComponentsLifeCycle(); @@ -169,24 +171,25 @@ public class SnapshotTest extends CloudStackTestNGBase { podId = host.getPodId(); imageStore = this.imageStoreDao.findByName(imageStoreName); } else { - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); dc = dcDao.persist(dc); dcId = dc.getId(); - //create pod + // create pod - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), this.getHostCidr(), 8, "test"); + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), + this.getHostCidr(), 8, "test"); pod = podDao.persist(pod); podId = pod.getId(); - //create xen cluster + // create xen cluster ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); cluster.setHypervisorType(this.getHypervisor().toString()); cluster.setClusterType(ClusterType.CloudManaged); cluster.setManagedState(ManagedState.Managed); cluster = clusterDao.persist(cluster); clusterId = cluster.getId(); - //create xen host + // create xen host host = new HostVO(this.getHostGuid()); host.setName("devcloud xen host"); @@ -235,16 +238,17 @@ public class SnapshotTest extends CloudStackTestNGBase { image = imageDataDao.persist(image); - /*TemplateDataStoreVO templateStore = new TemplateDataStoreVO(); - - templateStore.setDataStoreId(imageStore.getId()); - templateStore.setDownloadPercent(100); - templateStore.setDownloadState(Status.DOWNLOADED); - templateStore.setDownloadUrl(imageStore.getUrl()); - templateStore.setInstallPath(this.getImageInstallPath()); - templateStore.setTemplateId(image.getId()); - templateStoreDao.persist(templateStore);*/ - + /* + * TemplateDataStoreVO templateStore = new TemplateDataStoreVO(); + * + * templateStore.setDataStoreId(imageStore.getId()); + * templateStore.setDownloadPercent(100); + * templateStore.setDownloadState(Status.DOWNLOADED); + * templateStore.setDownloadUrl(imageStore.getUrl()); + * templateStore.setInstallPath(this.getImageInstallPath()); + * templateStore.setTemplateId(image.getId()); + * templateStoreDao.persist(templateStore); + */ DataStore store = this.dataStoreMgr.getDataStore(imageStore.getId(), DataStoreRole.Image); TemplateInfo template = templateFactory.getTemplate(image.getId(), DataStoreRole.Image); @@ -257,20 +261,24 @@ public class SnapshotTest extends CloudStackTestNGBase { templateOnStore.processEvent(Event.CreateOnlyRequested); templateOnStore.processEvent(Event.OperationSuccessed, answer); - } @Override protected void injectMockito() { List hosts = new ArrayList(); hosts.add(this.host); - Mockito.when(resourceMgr.listAllUpAndEnabledHosts((Type) Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(hosts); + Mockito.when( + resourceMgr.listAllUpAndEnabledHosts((Type) Matchers.any(), Matchers.anyLong(), Matchers.anyLong(), + Matchers.anyLong())).thenReturn(hosts); - remoteEp = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); - Mockito.when(epSelector.select(Mockito.any(DataObject.class), Mockito.any(DataObject.class))).thenReturn(remoteEp); - Mockito.when(epSelector.select(Mockito.any(DataObject.class))).thenReturn(remoteEp); - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(remoteEp); - Mockito.when(hyGuruMgr.getGuruProcessedCommandTargetHost(Mockito.anyLong(), Mockito.any(Command.class))).thenReturn(this.host.getId()); + remoteEp = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), + this.host.getPublicIpAddress()); + Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn( + remoteEp); + Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(remoteEp); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(remoteEp); + Mockito.when(hyGuruMgr.getGuruProcessedCommandTargetHost(Matchers.anyLong(), Matchers.any(Command.class))) + .thenReturn(this.host.getId()); } @@ -282,26 +290,27 @@ public class SnapshotTest extends CloudStackTestNGBase { return this.dataStoreMgr.getPrimaryDataStore(pools.get(0).getId()); } - /*DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("cloudstack primary data store provider"); - Map params = new HashMap(); - URI uri = new URI(this.getPrimaryStorageUrl()); - params.put("url", this.getPrimaryStorageUrl()); - params.put("server", uri.getHost()); - params.put("path", uri.getPath()); - params.put("protocol", Storage.StoragePoolType.NetworkFilesystem); - params.put("zoneId", dcId); - params.put("clusterId", clusterId); - params.put("name", this.primaryName); - params.put("port", 1); - params.put("podId", this.podId); - params.put("roles", DataStoreRole.Primary.toString()); - params.put("uuid", uuid); - params.put("providerName", String.valueOf(provider.getName())); - - DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); - DataStore store = lifeCycle.initialize(params); - ClusterScope scope = new ClusterScope(clusterId, podId, dcId); - lifeCycle.attachCluster(store, scope);*/ + /* + * DataStoreProvider provider = + * dataStoreProviderMgr.getDataStoreProvider + * ("cloudstack primary data store provider"); Map + * params = new HashMap(); URI uri = new + * URI(this.getPrimaryStorageUrl()); params.put("url", + * this.getPrimaryStorageUrl()); params.put("server", + * uri.getHost()); params.put("path", uri.getPath()); + * params.put("protocol", + * Storage.StoragePoolType.NetworkFilesystem); params.put("zoneId", + * dcId); params.put("clusterId", clusterId); params.put("name", + * this.primaryName); params.put("port", 1); params.put("podId", + * this.podId); params.put("roles", + * DataStoreRole.Primary.toString()); params.put("uuid", uuid); + * params.put("providerName", String.valueOf(provider.getName())); + * + * DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); + * DataStore store = lifeCycle.initialize(params); ClusterScope + * scope = new ClusterScope(clusterId, podId, dcId); + * lifeCycle.attachCluster(store, scope); + */ StoragePoolVO pool = new StoragePoolVO(); pool.setClusterId(clusterId); @@ -327,8 +336,9 @@ public class SnapshotTest extends CloudStackTestNGBase { private SnapshotVO createSnapshotInDb(VolumeInfo volume) { Snapshot.Type snapshotType = Snapshot.Type.MANUAL; - SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), 2, 1, volume.getId(), 1L, UUID.randomUUID().toString(), - (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), HypervisorType.XenServer); + SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), 2, 1, volume.getId(), 1L, UUID.randomUUID() + .toString(), (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), + HypervisorType.XenServer); return this.snapshotDao.persist(snapshotVO); } @@ -341,14 +351,14 @@ public class SnapshotTest extends CloudStackTestNGBase { return volume; } - public VolumeInfo createCopyBaseImage() { DataStore primaryStore = createPrimaryDataStore(); primaryStoreId = primaryStore.getId(); primaryStore = this.dataStoreMgr.getPrimaryDataStore(primaryStoreId); VolumeVO volume = createVolume(image.getId(), primaryStore.getId()); VolumeInfo volInfo = this.volFactory.getVolume(volume.getId()); - AsyncCallFuture future = this.volumeService.createVolumeFromTemplateAsync(volInfo, this.primaryStoreId, this.templateFactory.getTemplate(this.image.getId(), DataStoreRole.Image)); + AsyncCallFuture future = this.volumeService.createVolumeFromTemplateAsync(volInfo, + this.primaryStoreId, this.templateFactory.getTemplate(this.image.getId(), DataStoreRole.Image)); VolumeApiResult result; try { @@ -372,27 +382,27 @@ public class SnapshotTest extends CloudStackTestNGBase { SnapshotInfo newSnapshot = null; for (SnapshotStrategy strategy : this.snapshotStrategies) { if (strategy.canHandle(snapshot)) { - newSnapshot = strategy.takeSnapshot(snapshot); + newSnapshot = strategy.takeSnapshot(snapshot); } } AssertJUnit.assertNotNull(newSnapshot); LocalHostEndpoint ep = new MockLocalHostEndPoint(); ep.setResource(new MockLocalNfsSecondaryStorageResource()); - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); - //delete snapshot + // delete snapshot for (SnapshotStrategy strategy : this.snapshotStrategies) { if (strategy.canHandle(snapshot)) { - strategy.deleteSnapshot(newSnapshot.getId()); + strategy.deleteSnapshot(newSnapshot.getId()); } } - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(remoteEp); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(remoteEp); } private VMTemplateVO createTemplateInDb() { - VMTemplateVO image = new VMTemplateVO(); + VMTemplateVO image = new VMTemplateVO(); image.setTemplateType(TemplateType.USER); image.setUniqueName(UUID.randomUUID().toString()); @@ -435,21 +445,21 @@ public class SnapshotTest extends CloudStackTestNGBase { @Test public void deleteSnapshot() { - VolumeInfo vol = createCopyBaseImage(); + VolumeInfo vol = createCopyBaseImage(); SnapshotVO snapshotVO = createSnapshotInDb(vol); SnapshotInfo snapshot = this.snapshotFactory.getSnapshot(snapshotVO.getId(), vol.getDataStore()); SnapshotInfo newSnapshot = null; for (SnapshotStrategy strategy : this.snapshotStrategies) { if (strategy.canHandle(snapshot)) { - newSnapshot = strategy.takeSnapshot(snapshot); + newSnapshot = strategy.takeSnapshot(snapshot); } } AssertJUnit.assertNotNull(newSnapshot); - //create another snapshot + // create another snapshot for (SnapshotStrategy strategy : this.snapshotStrategies) { if (strategy.canHandle(snapshot)) { - strategy.deleteSnapshot(newSnapshot.getId()); + strategy.deleteSnapshot(newSnapshot.getId()); } } @@ -471,12 +481,11 @@ public class SnapshotTest extends CloudStackTestNGBase { AssertJUnit.assertTrue(result); LocalHostEndpoint ep = new LocalHostEndpoint(); ep.setResource(new MockLocalNfsSecondaryStorageResource()); - Mockito.when(epSelector.select(Mockito.any(DataObject.class), Mockito.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(ep); VMTemplateVO templateVO = createTemplateInDb(); TemplateInfo tmpl = this.templateFactory.getTemplate(templateVO.getId(), DataStoreRole.Image); DataStore imageStore = this.dataStoreMgr.getImageStore(this.dcId); this.imageService.createTemplateFromSnapshotAsync(snapshot, tmpl, imageStore); } - } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageFactoryBean.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageFactoryBean.java index 2ac6dac4c16..53a6464304a 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageFactoryBean.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageFactoryBean.java @@ -16,16 +16,15 @@ // under the License. package org.apache.cloudstack.storage.test; - import org.mockito.Mockito; import org.springframework.beans.factory.FactoryBean; /** - * A {@link FactoryBean} for creating mocked beans based on Mockito so that they + * A {@link FactoryBean} for creating mocked beans based on Mockito so that they * can be {@link @Autowired} into Spring test configurations. - * + * * @author Mattias Severson, Jayway - * + * * @see FactoryBean * @see org.mockito.Mockito */ @@ -35,7 +34,9 @@ public class StorageFactoryBean implements FactoryBean { /** * Creates a Mockito mock instance of the provided class. - * @param classToBeMocked The class to be mocked. + * + * @param classToBeMocked + * The class to be mocked. */ public StorageFactoryBean(Class classToBeMocked) { this.classToBeMocked = classToBeMocked; diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageTest.java index 0ee7fe0a431..5db3a0f09b0 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/StorageTest.java @@ -23,14 +23,13 @@ import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="classpath:resource/storageContext.xml") +@ContextConfiguration(locations = "classpath:resource/storageContext.xml") public class StorageTest { - @Test - public void test() { - fail("Not yet implemented"); - } + @Test + public void test() { + fail("Not yet implemented"); + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TemplateTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TemplateTest.java index c84fee5bcf9..da4c17b6041 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TemplateTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TemplateTest.java @@ -37,6 +37,7 @@ import org.apache.cloudstack.storage.LocalHostEndpoint; import org.apache.cloudstack.storage.MockLocalNfsSecondaryStorageResource; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; @@ -46,97 +47,90 @@ import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.dao.DataCenterDao; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Storage; -import com.cloud.storage.TemplateProfile; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Storage.TemplateType; import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.download.DownloadMonitor; import com.cloud.storage.download.DownloadMonitorImpl; -import com.cloud.template.HypervisorTemplateAdapter; -import com.cloud.template.TemplateAdapter; import com.cloud.utils.component.ComponentContext; -@ContextConfiguration(locations={"classpath:/storageContext.xml"}) - +@ContextConfiguration(locations = { "classpath:/storageContext.xml" }) public class TemplateTest extends CloudStackTestNGBase { - @Inject - DataCenterDao dcDao; - ImageStoreVO imageStore; - @Inject - ImageStoreDao imageStoreDao; - @Inject - TemplateService templateSvr; - @Inject - VMTemplateDao templateDao; - @Inject - TemplateDataFactory templateFactory; - @Inject - DataStoreManager dataStoreMgr; - @Inject - EndPointSelector epSelector; - @Inject - DownloadMonitorImpl downloadMonitor; + @Inject + DataCenterDao dcDao; + ImageStoreVO imageStore; + @Inject + ImageStoreDao imageStoreDao; + @Inject + TemplateService templateSvr; + @Inject + VMTemplateDao templateDao; + @Inject + TemplateDataFactory templateFactory; + @Inject + DataStoreManager dataStoreMgr; + @Inject + EndPointSelector epSelector; + @Inject + DownloadMonitorImpl downloadMonitor; + long dcId; + long templateId; - long dcId; - long templateId; + @Test(priority = -1) + public void setUp() { + ComponentContext.initComponentsLifeCycle(); - @Test(priority = -1) - public void setUp() { - ComponentContext.initComponentsLifeCycle(); + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); + dc = dcDao.persist(dc); + dcId = dc.getId(); - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); - dc = dcDao.persist(dc); - dcId = dc.getId(); + imageStore = new ImageStoreVO(); + imageStore.setName("test"); + imageStore.setDataCenterId(dcId); + imageStore.setProviderName(DataStoreProvider.NFS_IMAGE); + imageStore.setRole(DataStoreRole.Image); + imageStore.setUrl(this.getSecondaryStorage()); + imageStore.setUuid(UUID.randomUUID().toString()); + imageStore.setProtocol("nfs"); + imageStore = imageStoreDao.persist(imageStore); - imageStore = new ImageStoreVO(); - imageStore.setName("test"); - imageStore.setDataCenterId(dcId); - imageStore.setProviderName(DataStoreProvider.NFS_IMAGE); - imageStore.setRole(DataStoreRole.Image); - imageStore.setUrl(this.getSecondaryStorage()); - imageStore.setUuid(UUID.randomUUID().toString()); - imageStore.setProtocol("nfs"); - imageStore = imageStoreDao.persist(imageStore); + VMTemplateVO image = new VMTemplateVO(); + image.setTemplateType(TemplateType.USER); + image.setUrl(this.getTemplateUrl()); + image.setUniqueName(UUID.randomUUID().toString()); + image.setName(UUID.randomUUID().toString()); + image.setPublicTemplate(true); + image.setFeatured(true); + image.setRequiresHvm(true); + image.setBits(64); + image.setFormat(Storage.ImageFormat.VHD); + image.setEnablePassword(true); + image.setEnableSshKey(true); + image.setGuestOSId(1); + image.setBootable(true); + image.setPrepopulate(true); + image.setCrossZones(true); + image.setExtractable(true); - VMTemplateVO image = new VMTemplateVO(); - image.setTemplateType(TemplateType.USER); - image.setUrl(this.getTemplateUrl()); - image.setUniqueName(UUID.randomUUID().toString()); - image.setName(UUID.randomUUID().toString()); - image.setPublicTemplate(true); - image.setFeatured(true); - image.setRequiresHvm(true); - image.setBits(64); - image.setFormat(Storage.ImageFormat.VHD); - image.setEnablePassword(true); - image.setEnableSshKey(true); - image.setGuestOSId(1); - image.setBootable(true); - image.setPrepopulate(true); - image.setCrossZones(true); - image.setExtractable(true); - - - //image.setImageDataStoreId(storeId); - image = templateDao.persist(image); - templateId = image.getId(); + // image.setImageDataStoreId(storeId); + image = templateDao.persist(image); + templateId = image.getId(); // inject mockito LocalHostEndpoint ep = new LocalHostEndpoint(); ep.setResource(new MockLocalNfsSecondaryStorageResource()); - Mockito.when(epSelector.select(Mockito.any(DataObject.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(ep); - } + Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); + } - @Test - public void registerTemplate() { - TemplateInfo template = templateFactory.getTemplate(templateId, DataStoreRole.Image); - DataStore store = dataStoreMgr.getImageStore(dcId); - AsyncCallFuture future = new AsyncCallFuture(); - templateSvr.createTemplateAsync(template, store, future); + @Test + public void registerTemplate() { + TemplateInfo template = templateFactory.getTemplate(templateId, DataStoreRole.Image); + DataStore store = dataStoreMgr.getImageStore(dcId); + AsyncCallFuture future = new AsyncCallFuture(); + templateSvr.createTemplateAsync(template, store, future); try { TemplateApiResult result = future.get(); assertTrue(result.isSuccess(), "failed to register template: " + result.getResult()); @@ -147,11 +141,11 @@ public class TemplateTest extends CloudStackTestNGBase { } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); - assertTrue(false, e.getMessage()); + assertTrue(false, e.getMessage()); } - } + } - // @Test + // @Test public void deleteTemplate() { TemplateInfo template = templateFactory.getTemplate(templateId, DataStoreRole.Image); DataStore store = dataStoreMgr.getImageStore(dcId); @@ -167,7 +161,7 @@ public class TemplateTest extends CloudStackTestNGBase { } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); - assertTrue(false, e.getMessage()); + assertTrue(false, e.getMessage()); } } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestHttp.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestHttp.java index 8b10f7e3224..11d4931fd7d 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestHttp.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestHttp.java @@ -22,28 +22,21 @@ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; -import java.nio.channels.FileChannel; - import junit.framework.Assert; import org.apache.commons.httpclient.HttpException; -import org.apache.cxf.helpers.IOUtils; -import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.Test; -import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Parameters; -@ContextConfiguration(locations="classpath:/storageContext.xml") +@ContextConfiguration(locations = "classpath:/storageContext.xml") public class TestHttp extends AbstractTestNGSpringContextTests { @Test @Parameters("template-url") @@ -59,13 +52,13 @@ public class TestHttp extends AbstractTestNGSpringContextTests { System.out.println(response.getFirstHeader("Content-Length").getValue()); File localFile = new File("/tmp/test"); if (!localFile.exists()) { - localFile.createNewFile(); + localFile.createNewFile(); } - + HttpGet getMethod = new HttpGet(templateUrl); response = client.execute(getMethod); HttpEntity entity = response.getEntity(); - + output = new BufferedOutputStream(new FileOutputStream(localFile)); entity.writeTo(output); } catch (HttpException e) { @@ -83,7 +76,7 @@ public class TestHttp extends AbstractTestNGSpringContextTests { e.printStackTrace(); } } - + File f = new File("/tmp/test"); Assert.assertEquals(f.length(), length); } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNG.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNG.java index b3ecd3c22cb..e85c3d8db35 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNG.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNG.java @@ -20,12 +20,11 @@ import junit.framework.Assert; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests; -import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.cloud.utils.db.DB; -@ContextConfiguration(locations="classpath:/storageContext.xml") + +@ContextConfiguration(locations = "classpath:/storageContext.xml") public class TestNG extends AbstractTestNGSpringContextTests { @Test @DB diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNGAop.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNGAop.java index 130ecd21980..515c5c80532 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNGAop.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/TestNGAop.java @@ -31,8 +31,7 @@ import com.cloud.utils.db.Transaction; public class TestNGAop implements IMethodInterceptor { @Override - public List intercept(List methods, - ITestContext context) { + public List intercept(List methods, ITestContext context) { for (IMethodInstance methodIns : methods) { ITestNGMethod method = methodIns.getMethod(); ConstructorOrMethod meth = method.getConstructorOrMethod(); @@ -44,8 +43,7 @@ public class TestNGAop implements IMethodInterceptor { } } } - - + // TODO Auto-generated method stub return methods; } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java index 187d1f548cc..ef5c4caae96 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java @@ -40,7 +40,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult; -import org.apache.cloudstack.engine.subsystem.api.storage.type.RootDisk; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.storage.RemoteHostEndPoint; import org.apache.cloudstack.storage.command.CopyCmdAnswer; @@ -50,6 +49,7 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.to.TemplateObjectTO; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; @@ -88,7 +88,7 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; -@ContextConfiguration(locations={"classpath:/storageContext.xml"}) +@ContextConfiguration(locations = { "classpath:/storageContext.xml" }) public class VolumeTest extends CloudStackTestNGBase { @Inject ImageStoreDao imageStoreDao; @@ -140,6 +140,7 @@ public class VolumeTest extends CloudStackTestNGBase { long primaryStoreId; VMTemplateVO image; String imageStoreName = "testImageStore"; + @Test(priority = -1) public void setUp() { ComponentContext.initComponentsLifeCycle(); @@ -151,24 +152,25 @@ public class VolumeTest extends CloudStackTestNGBase { podId = host.getPodId(); imageStore = this.imageStoreDao.findByName(imageStoreName); } else { - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); dc = dcDao.persist(dc); dcId = dc.getId(); - //create pod + // create pod - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), this.getHostCidr(), 8, "test"); + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), + this.getHostCidr(), 8, "test"); pod = podDao.persist(pod); podId = pod.getId(); - //create xen cluster + // create xen cluster ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); cluster.setHypervisorType(this.getHypervisor().toString()); cluster.setClusterType(ClusterType.CloudManaged); cluster.setManagedState(ManagedState.Managed); cluster = clusterDao.persist(cluster); clusterId = cluster.getId(); - //create xen host + // create xen host host = new HostVO(this.getHostGuid()); host.setName("devcloud xen host"); @@ -217,16 +219,17 @@ public class VolumeTest extends CloudStackTestNGBase { image = imageDataDao.persist(image); - /*TemplateDataStoreVO templateStore = new TemplateDataStoreVO(); - - templateStore.setDataStoreId(imageStore.getId()); - templateStore.setDownloadPercent(100); - templateStore.setDownloadState(Status.DOWNLOADED); - templateStore.setDownloadUrl(imageStore.getUrl()); - templateStore.setInstallPath(this.getImageInstallPath()); - templateStore.setTemplateId(image.getId()); - templateStoreDao.persist(templateStore);*/ - + /* + * TemplateDataStoreVO templateStore = new TemplateDataStoreVO(); + * + * templateStore.setDataStoreId(imageStore.getId()); + * templateStore.setDownloadPercent(100); + * templateStore.setDownloadState(Status.DOWNLOADED); + * templateStore.setDownloadUrl(imageStore.getUrl()); + * templateStore.setInstallPath(this.getImageInstallPath()); + * templateStore.setTemplateId(image.getId()); + * templateStoreDao.persist(templateStore); + */ DataStore store = this.dataStoreMgr.getDataStore(imageStore.getId(), DataStoreRole.Image); TemplateInfo template = templateFactory.getTemplate(image.getId(), DataStoreRole.Image); @@ -238,20 +241,23 @@ public class VolumeTest extends CloudStackTestNGBase { templateOnStore.processEvent(Event.CreateOnlyRequested); templateOnStore.processEvent(Event.OperationSuccessed, answer); - } @Override protected void injectMockito() { List hosts = new ArrayList(); hosts.add(this.host); - Mockito.when(resourceMgr.listAllUpAndEnabledHosts((Type) Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(hosts); + Mockito.when( + resourceMgr.listAllUpAndEnabledHosts((Type) Matchers.any(), Matchers.anyLong(), Matchers.anyLong(), + Matchers.anyLong())).thenReturn(hosts); - RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); - Mockito.when(epSelector.select(Mockito.any(DataObject.class), Mockito.any(DataObject.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataObject.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(ep); - Mockito.when(hyGuruMgr.getGuruProcessedCommandTargetHost(Mockito.anyLong(), Mockito.any(Command.class))).thenReturn(this.host.getId()); + RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), + this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); + Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); + Mockito.when(hyGuruMgr.getGuruProcessedCommandTargetHost(Matchers.anyLong(), Matchers.any(Command.class))) + .thenReturn(this.host.getId()); } public DataStore createPrimaryDataStore() { @@ -262,26 +268,27 @@ public class VolumeTest extends CloudStackTestNGBase { return this.dataStoreMgr.getPrimaryDataStore(pools.get(0).getId()); } - /*DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("cloudstack primary data store provider"); - Map params = new HashMap(); - URI uri = new URI(this.getPrimaryStorageUrl()); - params.put("url", this.getPrimaryStorageUrl()); - params.put("server", uri.getHost()); - params.put("path", uri.getPath()); - params.put("protocol", Storage.StoragePoolType.NetworkFilesystem); - params.put("zoneId", dcId); - params.put("clusterId", clusterId); - params.put("name", this.primaryName); - params.put("port", 1); - params.put("podId", this.podId); - params.put("roles", DataStoreRole.Primary.toString()); - params.put("uuid", uuid); - params.put("providerName", String.valueOf(provider.getName())); - - DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); - DataStore store = lifeCycle.initialize(params); - ClusterScope scope = new ClusterScope(clusterId, podId, dcId); - lifeCycle.attachCluster(store, scope);*/ + /* + * DataStoreProvider provider = + * dataStoreProviderMgr.getDataStoreProvider + * ("cloudstack primary data store provider"); Map + * params = new HashMap(); URI uri = new + * URI(this.getPrimaryStorageUrl()); params.put("url", + * this.getPrimaryStorageUrl()); params.put("server", + * uri.getHost()); params.put("path", uri.getPath()); + * params.put("protocol", + * Storage.StoragePoolType.NetworkFilesystem); params.put("zoneId", + * dcId); params.put("clusterId", clusterId); params.put("name", + * this.primaryName); params.put("port", 1); params.put("podId", + * this.podId); params.put("roles", + * DataStoreRole.Primary.toString()); params.put("uuid", uuid); + * params.put("providerName", String.valueOf(provider.getName())); + * + * DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); + * DataStore store = lifeCycle.initialize(params); ClusterScope + * scope = new ClusterScope(clusterId, podId, dcId); + * lifeCycle.attachCluster(store, scope); + */ StoragePoolVO pool = new StoragePoolVO(); pool.setClusterId(clusterId); @@ -306,7 +313,8 @@ public class VolumeTest extends CloudStackTestNGBase { } private VolumeVO createVolume(Long templateId, long dataStoreId) { - VolumeVO volume = new VolumeVO(Volume.Type.DATADISK, UUID.randomUUID().toString(), this.dcId, 1L, 1L, 1L, 1000);; + VolumeVO volume = new VolumeVO(Volume.Type.DATADISK, UUID.randomUUID().toString(), this.dcId, 1L, 1L, 1L, 1000); + ; volume.setPoolId(dataStoreId); volume = volumeDao.persist(volume); return volume; @@ -319,7 +327,8 @@ public class VolumeTest extends CloudStackTestNGBase { primaryStore = this.dataStoreMgr.getPrimaryDataStore(primaryStoreId); VolumeVO volume = createVolume(image.getId(), primaryStore.getId()); VolumeInfo volInfo = this.volFactory.getVolume(volume.getId()); - AsyncCallFuture future = this.volumeService.createVolumeFromTemplateAsync(volInfo, this.primaryStoreId, this.templateFactory.getTemplate(this.image.getId(), DataStoreRole.Image)); + AsyncCallFuture future = this.volumeService.createVolumeFromTemplateAsync(volInfo, + this.primaryStoreId, this.templateFactory.getTemplate(this.image.getId(), DataStoreRole.Image)); try { VolumeApiResult result = future.get(); @@ -427,6 +436,5 @@ public class VolumeTest extends CloudStackTestNGBase { e.printStackTrace(); } - } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java index 9d5555a8d8a..4acc8dc7de8 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java @@ -39,7 +39,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult; -import org.apache.cloudstack.engine.subsystem.api.storage.type.RootDisk; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.storage.RemoteHostEndPoint; import org.apache.cloudstack.storage.command.CopyCmdAnswer; @@ -49,6 +48,7 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.to.TemplateObjectTO; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; @@ -87,7 +87,7 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; -@ContextConfiguration(locations={"classpath:/storageContext.xml"}) +@ContextConfiguration(locations = { "classpath:/storageContext.xml" }) public class VolumeTestVmware extends CloudStackTestNGBase { @Inject ImageStoreDao imageStoreDao; @@ -139,6 +139,7 @@ public class VolumeTestVmware extends CloudStackTestNGBase { long primaryStoreId; VMTemplateVO image; String imageStoreName = "testImageStore"; + @Test(priority = -1) public void setUp() { ComponentContext.initComponentsLifeCycle(); @@ -150,17 +151,18 @@ public class VolumeTestVmware extends CloudStackTestNGBase { podId = host.getPodId(); imageStore = this.imageStoreDao.findByName(imageStoreName); } else { - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); dc = dcDao.persist(dc); dcId = dc.getId(); - //create pod + // create pod - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), this.getHostCidr(), 8, "test"); + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), + this.getHostCidr(), 8, "test"); pod = podDao.persist(pod); podId = pod.getId(); - //create xen cluster + // create xen cluster ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); cluster.setHypervisorType(HypervisorType.VMware.toString()); cluster.setClusterType(ClusterType.ExternalManaged); @@ -168,14 +170,14 @@ public class VolumeTestVmware extends CloudStackTestNGBase { cluster = clusterDao.persist(cluster); clusterId = cluster.getId(); - //setup vcenter + // setup vcenter ClusterDetailsVO clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "url", null); this.clusterDetailsDao.persist(clusterDetailVO); clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "username", null); this.clusterDetailsDao.persist(clusterDetailVO); clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "password", null); this.clusterDetailsDao.persist(clusterDetailVO); - //create xen host + // create xen host host = new HostVO(this.getHostGuid()); host.setName("devcloud vmware host"); @@ -224,16 +226,17 @@ public class VolumeTestVmware extends CloudStackTestNGBase { image = imageDataDao.persist(image); - /*TemplateDataStoreVO templateStore = new TemplateDataStoreVO(); - - templateStore.setDataStoreId(imageStore.getId()); - templateStore.setDownloadPercent(100); - templateStore.setDownloadState(Status.DOWNLOADED); - templateStore.setDownloadUrl(imageStore.getUrl()); - templateStore.setInstallPath(this.getImageInstallPath()); - templateStore.setTemplateId(image.getId()); - templateStoreDao.persist(templateStore);*/ - + /* + * TemplateDataStoreVO templateStore = new TemplateDataStoreVO(); + * + * templateStore.setDataStoreId(imageStore.getId()); + * templateStore.setDownloadPercent(100); + * templateStore.setDownloadState(Status.DOWNLOADED); + * templateStore.setDownloadUrl(imageStore.getUrl()); + * templateStore.setInstallPath(this.getImageInstallPath()); + * templateStore.setTemplateId(image.getId()); + * templateStoreDao.persist(templateStore); + */ DataStore store = this.dataStoreMgr.getDataStore(imageStore.getId(), DataStoreRole.Image); TemplateInfo template = templateFactory.getTemplate(image.getId(), DataStoreRole.Image); @@ -244,19 +247,21 @@ public class VolumeTestVmware extends CloudStackTestNGBase { templateOnStore.processEvent(Event.CreateOnlyRequested); templateOnStore.processEvent(Event.OperationSuccessed, answer); - } @Override protected void injectMockito() { List hosts = new ArrayList(); hosts.add(this.host); - Mockito.when(resourceMgr.listAllUpAndEnabledHosts((Type) Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(hosts); + Mockito.when( + resourceMgr.listAllUpAndEnabledHosts((Type) Matchers.any(), Matchers.anyLong(), Matchers.anyLong(), + Matchers.anyLong())).thenReturn(hosts); - RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); - Mockito.when(epSelector.select(Mockito.any(DataObject.class), Mockito.any(DataObject.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataObject.class))).thenReturn(ep); - Mockito.when(epSelector.select(Mockito.any(DataStore.class))).thenReturn(ep); + RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), + this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); + Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(ep); + Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); } public DataStore createPrimaryDataStore() { @@ -267,26 +272,27 @@ public class VolumeTestVmware extends CloudStackTestNGBase { return this.dataStoreMgr.getPrimaryDataStore(pools.get(0).getId()); } - /*DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("cloudstack primary data store provider"); - Map params = new HashMap(); - URI uri = new URI(this.getPrimaryStorageUrl()); - params.put("url", this.getPrimaryStorageUrl()); - params.put("server", uri.getHost()); - params.put("path", uri.getPath()); - params.put("protocol", Storage.StoragePoolType.NetworkFilesystem); - params.put("zoneId", dcId); - params.put("clusterId", clusterId); - params.put("name", this.primaryName); - params.put("port", 1); - params.put("podId", this.podId); - params.put("roles", DataStoreRole.Primary.toString()); - params.put("uuid", uuid); - params.put("providerName", String.valueOf(provider.getName())); - - DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); - DataStore store = lifeCycle.initialize(params); - ClusterScope scope = new ClusterScope(clusterId, podId, dcId); - lifeCycle.attachCluster(store, scope);*/ + /* + * DataStoreProvider provider = + * dataStoreProviderMgr.getDataStoreProvider + * ("cloudstack primary data store provider"); Map + * params = new HashMap(); URI uri = new + * URI(this.getPrimaryStorageUrl()); params.put("url", + * this.getPrimaryStorageUrl()); params.put("server", + * uri.getHost()); params.put("path", uri.getPath()); + * params.put("protocol", + * Storage.StoragePoolType.NetworkFilesystem); params.put("zoneId", + * dcId); params.put("clusterId", clusterId); params.put("name", + * this.primaryName); params.put("port", 1); params.put("podId", + * this.podId); params.put("roles", + * DataStoreRole.Primary.toString()); params.put("uuid", uuid); + * params.put("providerName", String.valueOf(provider.getName())); + * + * DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); + * DataStore store = lifeCycle.initialize(params); ClusterScope + * scope = new ClusterScope(clusterId, podId, dcId); + * lifeCycle.attachCluster(store, scope); + */ StoragePoolVO pool = new StoragePoolVO(); pool.setClusterId(clusterId); @@ -311,20 +317,22 @@ public class VolumeTestVmware extends CloudStackTestNGBase { } private VolumeVO createVolume(Long templateId, long dataStoreId) { - VolumeVO volume = new VolumeVO(Volume.Type.DATADISK, UUID.randomUUID().toString(), this.dcId, 1L, 1L, 1L, 1000);; + VolumeVO volume = new VolumeVO(Volume.Type.DATADISK, UUID.randomUUID().toString(), this.dcId, 1L, 1L, 1L, 1000); + ; volume.setPoolId(dataStoreId); volume = volumeDao.persist(volume); return volume; } - //@Test + // @Test public void testCopyBaseImage() { DataStore primaryStore = createPrimaryDataStore(); primaryStoreId = primaryStore.getId(); primaryStore = this.dataStoreMgr.getPrimaryDataStore(primaryStoreId); VolumeVO volume = createVolume(image.getId(), primaryStore.getId()); VolumeInfo volInfo = this.volFactory.getVolume(volume.getId()); - AsyncCallFuture future = this.volumeService.createVolumeFromTemplateAsync(volInfo, this.primaryStoreId, this.templateFactory.getTemplate(this.image.getId(), DataStoreRole.Image)); + AsyncCallFuture future = this.volumeService.createVolumeFromTemplateAsync(volInfo, + this.primaryStoreId, this.templateFactory.getTemplate(this.image.getId(), DataStoreRole.Image)); try { VolumeApiResult result = future.get(); @@ -432,6 +440,5 @@ public class VolumeTestVmware extends CloudStackTestNGBase { e.printStackTrace(); } - } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java index 4e221010190..42b0463c71b 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java @@ -50,6 +50,7 @@ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.testng.Assert; @@ -82,50 +83,50 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; -@ContextConfiguration(locations={"classpath:/storageContext.xml"}) +@ContextConfiguration(locations = { "classpath:/storageContext.xml" }) public class volumeServiceTest extends CloudStackTestNGBase { - //@Inject - //ImageDataStoreProviderManager imageProviderMgr; - @Inject - TemplateService imageService; - @Inject - VolumeService volumeService; - @Inject - VMTemplateDao imageDataDao; - @Inject - VolumeDao volumeDao; - @Inject - HostDao hostDao; - @Inject - HostPodDao podDao; - @Inject - ClusterDao clusterDao; - @Inject - DataCenterDao dcDao; - @Inject - PrimaryDataStoreDao primaryStoreDao; - @Inject - DataStoreProviderManager dataStoreProviderMgr; - @Inject - AgentManager agentMgr; - @Inject - EndPointSelector selector; - @Inject - TemplateDataFactory imageDataFactory; - @Inject - VolumeDataFactory volumeFactory; - @Inject - ImageStoreDao imageStoreDao; - ImageStoreVO imageStore; - Long dcId; - Long clusterId; - Long podId; - HostVO host; - String primaryName = "my primary data store"; - DataStore primaryStore; + // @Inject + // ImageDataStoreProviderManager imageProviderMgr; + @Inject + TemplateService imageService; + @Inject + VolumeService volumeService; + @Inject + VMTemplateDao imageDataDao; + @Inject + VolumeDao volumeDao; + @Inject + HostDao hostDao; + @Inject + HostPodDao podDao; + @Inject + ClusterDao clusterDao; + @Inject + DataCenterDao dcDao; + @Inject + PrimaryDataStoreDao primaryStoreDao; + @Inject + DataStoreProviderManager dataStoreProviderMgr; + @Inject + AgentManager agentMgr; + @Inject + EndPointSelector selector; + @Inject + TemplateDataFactory imageDataFactory; + @Inject + VolumeDataFactory volumeFactory; + @Inject + ImageStoreDao imageStoreDao; + ImageStoreVO imageStore; + Long dcId; + Long clusterId; + Long podId; + HostVO host; + String primaryName = "my primary data store"; + DataStore primaryStore; @Test(priority = -1) - public void setUp() { + public void setUp() { ComponentContext.initComponentsLifeCycle(); host = hostDao.findByGuid(this.getHostGuid()); @@ -135,51 +136,52 @@ public class volumeServiceTest extends CloudStackTestNGBase { podId = host.getPodId(); return; } - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); - dc = dcDao.persist(dc); - dcId = dc.getId(); - //create pod + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); + dc = dcDao.persist(dc); + dcId = dc.getId(); + // create pod - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), this.getHostCidr(), 8, "test"); - pod = podDao.persist(pod); - podId = pod.getId(); - //create xen cluster - ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); - cluster.setHypervisorType(HypervisorType.XenServer.toString()); - cluster.setClusterType(ClusterType.CloudManaged); - cluster.setManagedState(ManagedState.Managed); - cluster = clusterDao.persist(cluster); - clusterId = cluster.getId(); - //create xen host + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), this.getHostGateway(), + this.getHostCidr(), 8, "test"); + pod = podDao.persist(pod); + podId = pod.getId(); + // create xen cluster + ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); + cluster.setHypervisorType(HypervisorType.XenServer.toString()); + cluster.setClusterType(ClusterType.CloudManaged); + cluster.setManagedState(ManagedState.Managed); + cluster = clusterDao.persist(cluster); + clusterId = cluster.getId(); + // create xen host - host = new HostVO(this.getHostGuid()); - host.setName("devcloud xen host"); - host.setType(Host.Type.Routing); - host.setPrivateIpAddress(this.getHostIp()); - host.setDataCenterId(dc.getId()); - host.setVersion("6.0.1"); - host.setAvailable(true); - host.setSetup(true); - host.setPodId(podId); - host.setLastPinged(0); - host.setResourceState(ResourceState.Enabled); - host.setHypervisorType(HypervisorType.XenServer); - host.setClusterId(cluster.getId()); + host = new HostVO(this.getHostGuid()); + host.setName("devcloud xen host"); + host.setType(Host.Type.Routing); + host.setPrivateIpAddress(this.getHostIp()); + host.setDataCenterId(dc.getId()); + host.setVersion("6.0.1"); + host.setAvailable(true); + host.setSetup(true); + host.setPodId(podId); + host.setLastPinged(0); + host.setResourceState(ResourceState.Enabled); + host.setHypervisorType(HypervisorType.XenServer); + host.setClusterId(cluster.getId()); - host = hostDao.persist(host); + host = hostDao.persist(host); - imageStore = new ImageStoreVO(); - imageStore.setName("test"); - imageStore.setDataCenterId(dcId); - imageStore.setProviderName("CloudStack ImageStore Provider"); - imageStore.setRole(DataStoreRole.Image); - imageStore.setUrl(this.getSecondaryStorage()); - imageStore.setUuid(UUID.randomUUID().toString()); - imageStore = imageStoreDao.persist(imageStore); + imageStore = new ImageStoreVO(); + imageStore.setName("test"); + imageStore.setDataCenterId(dcId); + imageStore.setProviderName("CloudStack ImageStore Provider"); + imageStore.setRole(DataStoreRole.Image); + imageStore.setUrl(this.getSecondaryStorage()); + imageStore.setUuid(UUID.randomUUID().toString()); + imageStore = imageStoreDao.persist(imageStore); - } + } @Override protected void injectMockito() { @@ -189,74 +191,79 @@ public class volumeServiceTest extends CloudStackTestNGBase { List results = new ArrayList(); results.add(host); Mockito.when(hostDao.listAll()).thenReturn(results); - Mockito.when(hostDao.findById(Mockito.anyLong())).thenReturn(host); - Mockito.when(hostDao.findHypervisorHostInCluster(Mockito.anyLong())).thenReturn(results); + Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(host); + Mockito.when(hostDao.findHypervisorHostInCluster(Matchers.anyLong())).thenReturn(results); List eps = new ArrayList(); - eps.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), - host.getPrivateIpAddress(), host.getPublicIpAddress())); - Mockito.when(selector.selectAll(Mockito.any(DataStore.class))).thenReturn(eps); - Mockito.when(selector.select(Mockito.any(DataObject.class))).thenReturn(eps.get(0)); - Mockito.when(selector.select(Mockito.any(DataObject.class), Mockito.any(DataObject.class))).thenReturn(eps.get(0)); + eps.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), + host.getPublicIpAddress())); + Mockito.when(selector.selectAll(Matchers.any(DataStore.class))).thenReturn(eps); + Mockito.when(selector.select(Matchers.any(DataObject.class))).thenReturn(eps.get(0)); + Mockito.when(selector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn( + eps.get(0)); } - private VMTemplateVO createImageData() { - VMTemplateVO image = new VMTemplateVO(); - image.setTemplateType(TemplateType.USER); - image.setUrl(this.getTemplateUrl()); - image.setUniqueName(UUID.randomUUID().toString()); - image.setName(UUID.randomUUID().toString()); - image.setPublicTemplate(true); - image.setFeatured(true); - image.setRequiresHvm(true); - image.setBits(64); - image.setFormat(Storage.ImageFormat.VHD); - image.setEnablePassword(true); - image.setEnableSshKey(true); - image.setGuestOSId(1); - image.setBootable(true); - image.setPrepopulate(true); - image.setCrossZones(true); - image.setExtractable(true); + private VMTemplateVO createImageData() { + VMTemplateVO image = new VMTemplateVO(); + image.setTemplateType(TemplateType.USER); + image.setUrl(this.getTemplateUrl()); + image.setUniqueName(UUID.randomUUID().toString()); + image.setName(UUID.randomUUID().toString()); + image.setPublicTemplate(true); + image.setFeatured(true); + image.setRequiresHvm(true); + image.setBits(64); + image.setFormat(Storage.ImageFormat.VHD); + image.setEnablePassword(true); + image.setEnableSshKey(true); + image.setGuestOSId(1); + image.setBootable(true); + image.setPrepopulate(true); + image.setCrossZones(true); + image.setExtractable(true); + // image.setImageDataStoreId(storeId); + image = imageDataDao.persist(image); - //image.setImageDataStoreId(storeId); - image = imageDataDao.persist(image); + return image; + } + private TemplateInfo createTemplate() { + try { + DataStore store = createImageStore(); + VMTemplateVO image = createImageData(); + TemplateInfo template = imageDataFactory.getTemplate(image.getId(), store); + // AsyncCallFuture future = + // imageService.createTemplateAsync(template, store); + // future.get(); + template = imageDataFactory.getTemplate(image.getId(), store); + /* + * imageProviderMgr.configure("image Provider", new HashMap()); VMTemplateVO image = createImageData(); + * ImageDataStoreProvider defaultProvider = + * imageProviderMgr.getProvider("DefaultProvider"); + * ImageDataStoreLifeCycle lifeCycle = + * defaultProvider.getLifeCycle(); ImageDataStore store = + * lifeCycle.registerDataStore("defaultHttpStore", new + * HashMap()); + * imageService.registerTemplate(image.getId(), + * store.getImageDataStoreId()); TemplateEntity te = + * imageService.getTemplateEntity(image.getId()); return te; + */ + return template; + } catch (Exception e) { + Assert.fail("failed", e); + return null; + } + } - return image; - } + // @Test + public void createTemplateTest() { + createTemplate(); + } - private TemplateInfo createTemplate() { - try { - DataStore store = createImageStore(); - VMTemplateVO image = createImageData(); - TemplateInfo template = imageDataFactory.getTemplate(image.getId(), store); - //AsyncCallFuture future = imageService.createTemplateAsync(template, store); - //future.get(); - template = imageDataFactory.getTemplate(image.getId(), store); - /*imageProviderMgr.configure("image Provider", new HashMap()); - VMTemplateVO image = createImageData(); - ImageDataStoreProvider defaultProvider = imageProviderMgr.getProvider("DefaultProvider"); - ImageDataStoreLifeCycle lifeCycle = defaultProvider.getLifeCycle(); - ImageDataStore store = lifeCycle.registerDataStore("defaultHttpStore", new HashMap()); - imageService.registerTemplate(image.getId(), store.getImageDataStoreId()); - TemplateEntity te = imageService.getTemplateEntity(image.getId()); - return te;*/ - return template; - } catch (Exception e) { - Assert.fail("failed", e); - return null; - } - } - - //@Test - public void createTemplateTest() { - createTemplate(); - } - - @Test - public void testCreatePrimaryStorage() { - DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("sample primary data store provider"); + @Test + public void testCreatePrimaryStorage() { + DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("sample primary data store provider"); Map params = new HashMap(); URI uri = null; try { @@ -278,13 +285,13 @@ public class volumeServiceTest extends CloudStackTestNGBase { params.put("providerName", String.valueOf(provider.getName())); DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); - this.primaryStore = lifeCycle.initialize(params); + this.primaryStore = lifeCycle.initialize(params); ClusterScope scope = new ClusterScope(clusterId, podId, dcId); lifeCycle.attachCluster(this.primaryStore, scope); - } + } - private DataStore createImageStore() { - DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("sample image data store provider"); + private DataStore createImageStore() { + DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("sample image data store provider"); Map params = new HashMap(); String name = UUID.randomUUID().toString(); params.put("name", name); @@ -295,19 +302,20 @@ public class volumeServiceTest extends CloudStackTestNGBase { DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); DataStore store = lifeCycle.initialize(params); return store; - } - //@Test - public void testcreateImageStore() { - createImageStore(); - } + } + // @Test + public void testcreateImageStore() { + createImageStore(); + } - public DataStore createPrimaryDataStore() { - try { - DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider("sample primary data store provider"); - Map params = new HashMap(); - URI uri = new URI(this.getPrimaryStorageUrl()); - params.put("url", this.getPrimaryStorageUrl()); + public DataStore createPrimaryDataStore() { + try { + DataStoreProvider provider = dataStoreProviderMgr + .getDataStoreProvider("sample primary data store provider"); + Map params = new HashMap(); + URI uri = new URI(this.getPrimaryStorageUrl()); + params.put("url", this.getPrimaryStorageUrl()); params.put("server", uri.getHost()); params.put("path", uri.getPath()); params.put("protocol", Storage.StoragePoolType.NetworkFilesystem); @@ -319,57 +327,58 @@ public class volumeServiceTest extends CloudStackTestNGBase { params.put("uuid", UUID.nameUUIDFromBytes(this.getPrimaryStorageUrl().getBytes()).toString()); params.put("providerName", String.valueOf(provider.getName())); - DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); - DataStore store = lifeCycle.initialize(params); - ClusterScope scope = new ClusterScope(clusterId, podId, dcId); - lifeCycle.attachCluster(store, scope); + DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); + DataStore store = lifeCycle.initialize(params); + ClusterScope scope = new ClusterScope(clusterId, podId, dcId); + lifeCycle.attachCluster(store, scope); - /* - PrimaryDataStoreProvider provider = primaryDataStoreProviderMgr.getDataStoreProvider("sample primary data store provider"); - primaryDataStoreProviderMgr.configure("primary data store mgr", new HashMap()); + /* + * PrimaryDataStoreProvider provider = + * primaryDataStoreProviderMgr.getDataStoreProvider + * ("sample primary data store provider"); + * primaryDataStoreProviderMgr.configure("primary data store mgr", + * new HashMap()); + * + * List ds = + * primaryStoreDao.findPoolByName(this.primaryName); if (ds.size() + * >= 1) { PrimaryDataStoreVO store = ds.get(0); if + * (store.getRemoved() == null) { return + * provider.getDataStore(store.getId()); } } + * + * + * Map params = new HashMap(); + * params.put("url", this.getPrimaryStorageUrl()); + * params.put("dcId", dcId.toString()); params.put("clusterId", + * clusterId.toString()); params.put("name", this.primaryName); + * PrimaryDataStoreInfo primaryDataStoreInfo = + * provider.registerDataStore(params); PrimaryDataStoreLifeCycle lc + * = primaryDataStoreInfo.getLifeCycle(); ClusterScope scope = new + * ClusterScope(clusterId, podId, dcId); lc.attachCluster(scope); + * return primaryDataStoreInfo; + */ + return store; + } catch (Exception e) { + return null; + } + } - List ds = primaryStoreDao.findPoolByName(this.primaryName); - if (ds.size() >= 1) { - PrimaryDataStoreVO store = ds.get(0); - if (store.getRemoved() == null) { - return provider.getDataStore(store.getId()); - } - } + private VolumeVO createVolume(Long templateId, long dataStoreId) { + VolumeVO volume = new VolumeVO(Volume.Type.DATADISK, UUID.randomUUID().toString(), this.dcId, 1L, 1L, 1L, 1000); + volume.setPoolId(dataStoreId); + volume = volumeDao.persist(volume); + return volume; + } - - Map params = new HashMap(); - params.put("url", this.getPrimaryStorageUrl()); - params.put("dcId", dcId.toString()); - params.put("clusterId", clusterId.toString()); - params.put("name", this.primaryName); - PrimaryDataStoreInfo primaryDataStoreInfo = provider.registerDataStore(params); - PrimaryDataStoreLifeCycle lc = primaryDataStoreInfo.getLifeCycle(); - ClusterScope scope = new ClusterScope(clusterId, podId, dcId); - lc.attachCluster(scope); - return primaryDataStoreInfo; - */ - return store; - } catch (Exception e) { - return null; - } - } - - private VolumeVO createVolume(Long templateId, long dataStoreId) { - VolumeVO volume = new VolumeVO(Volume.Type.DATADISK, UUID.randomUUID().toString(), this.dcId, 1L, 1L, 1L, 1000); - volume.setPoolId(dataStoreId); - volume = volumeDao.persist(volume); - return volume; - } - - @Test(priority=2) - public void createVolumeFromTemplate() { - DataStore primaryStore = this.primaryStore; - TemplateInfo te = createTemplate(); - VolumeVO volume = createVolume(te.getId(), primaryStore.getId()); - VolumeInfo vol = volumeFactory.getVolume(volume.getId(), primaryStore); - //ve.createVolumeFromTemplate(primaryStore.getId(), new VHD(), te); - AsyncCallFuture future = volumeService.createVolumeFromTemplateAsync(vol, primaryStore.getId(), te); - try { + @Test(priority = 2) + public void createVolumeFromTemplate() { + DataStore primaryStore = this.primaryStore; + TemplateInfo te = createTemplate(); + VolumeVO volume = createVolume(te.getId(), primaryStore.getId()); + VolumeInfo vol = volumeFactory.getVolume(volume.getId(), primaryStore); + // ve.createVolumeFromTemplate(primaryStore.getId(), new VHD(), te); + AsyncCallFuture future = volumeService.createVolumeFromTemplateAsync(vol, + primaryStore.getId(), te); + try { future.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block @@ -378,15 +387,15 @@ public class volumeServiceTest extends CloudStackTestNGBase { // TODO Auto-generated catch block e.printStackTrace(); } - } + } - //@Test(priority=3) - public void createDataDisk() { - DataStore primaryStore = this.primaryStore; - VolumeVO volume = createVolume(null, primaryStore.getId()); - VolumeInfo vol = volumeFactory.getVolume(volume.getId(), primaryStore); - AsyncCallFuture future = volumeService.createVolumeAsync(vol, primaryStore); - try { + // @Test(priority=3) + public void createDataDisk() { + DataStore primaryStore = this.primaryStore; + VolumeVO volume = createVolume(null, primaryStore.getId()); + VolumeInfo vol = volumeFactory.getVolume(volume.getId(), primaryStore); + AsyncCallFuture future = volumeService.createVolumeAsync(vol, primaryStore); + try { future.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block @@ -395,28 +404,15 @@ public class volumeServiceTest extends CloudStackTestNGBase { // TODO Auto-generated catch block e.printStackTrace(); } - } + } - //@Test(priority=3) - public void createAndDeleteDataDisk() { - DataStore primaryStore = this.primaryStore; - VolumeVO volume = createVolume(null, primaryStore.getId()); - VolumeInfo vol = volumeFactory.getVolume(volume.getId(), primaryStore); - AsyncCallFuture future = volumeService.createVolumeAsync(vol, primaryStore); - try { - future.get(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ExecutionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - //delete the volume - vol = volumeFactory.getVolume(volume.getId(), primaryStore); - future = volumeService.expungeVolumeAsync(vol); - try { + // @Test(priority=3) + public void createAndDeleteDataDisk() { + DataStore primaryStore = this.primaryStore; + VolumeVO volume = createVolume(null, primaryStore.getId()); + VolumeInfo vol = volumeFactory.getVolume(volume.getId(), primaryStore); + AsyncCallFuture future = volumeService.createVolumeAsync(vol, primaryStore); + try { future.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block @@ -425,41 +421,53 @@ public class volumeServiceTest extends CloudStackTestNGBase { // TODO Auto-generated catch block e.printStackTrace(); } - } - //@Test(priority=3) - public void tearDown() { - List ds = primaryStoreDao.findPoolByName(this.primaryName); - for (int i = 0; i < ds.size(); i++) { - StoragePoolVO store = ds.get(i); - store.setUuid(null); - primaryStoreDao.remove(ds.get(i).getId()); - primaryStoreDao.expunge(ds.get(i).getId()); - } - } + // delete the volume + vol = volumeFactory.getVolume(volume.getId(), primaryStore); + future = volumeService.expungeVolumeAsync(vol); + try { + future.get(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ExecutionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - //@Test - //@Test + // @Test(priority=3) + public void tearDown() { + List ds = primaryStoreDao.findPoolByName(this.primaryName); + for (int i = 0; i < ds.size(); i++) { + StoragePoolVO store = ds.get(i); + store.setUuid(null); + primaryStoreDao.remove(ds.get(i).getId()); + primaryStoreDao.expunge(ds.get(i).getId()); + } + } + + // @Test + // @Test public void test1() { - /*System.out.println(VolumeTypeHelper.getType("Root")); - System.out.println(VolumeDiskTypeHelper.getDiskType("vmdk")); - System.out.println(ImageFormatHelper.getFormat("ova")); - AssertJUnit.assertFalse(new VMDK().equals(new VHD())); - VMDK vmdk = new VMDK(); - AssertJUnit.assertTrue(vmdk.equals(vmdk)); - VMDK newvmdk = new VMDK(); - AssertJUnit.assertTrue(vmdk.equals(newvmdk)); - - ImageFormat ova = new OVA(); - ImageFormat iso = new ISO(); - AssertJUnit.assertTrue(ova.equals(new OVA())); - AssertJUnit.assertFalse(ova.equals(iso)); - AssertJUnit.assertTrue(ImageFormatHelper.getFormat("test").equals(new Unknown())); - - VolumeDiskType qcow2 = new QCOW2(); - ImageFormat qcow2format = new org.apache.cloudstack.storage.image.format.QCOW2(); - AssertJUnit.assertFalse(qcow2.equals(qcow2format)); -*/ - } + /* + * System.out.println(VolumeTypeHelper.getType("Root")); + * System.out.println(VolumeDiskTypeHelper.getDiskType("vmdk")); + * System.out.println(ImageFormatHelper.getFormat("ova")); + * AssertJUnit.assertFalse(new VMDK().equals(new VHD())); VMDK vmdk = + * new VMDK(); AssertJUnit.assertTrue(vmdk.equals(vmdk)); VMDK newvmdk = + * new VMDK(); AssertJUnit.assertTrue(vmdk.equals(newvmdk)); + * + * ImageFormat ova = new OVA(); ImageFormat iso = new ISO(); + * AssertJUnit.assertTrue(ova.equals(new OVA())); + * AssertJUnit.assertFalse(ova.equals(iso)); + * AssertJUnit.assertTrue(ImageFormatHelper.getFormat("test").equals(new + * Unknown())); + * + * VolumeDiskType qcow2 = new QCOW2(); ImageFormat qcow2format = new + * org.apache.cloudstack.storage.image.format.QCOW2(); + * AssertJUnit.assertFalse(qcow2.equals(qcow2format)); + */ + } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java index c530e4a815e..aafdad05ff0 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java @@ -26,18 +26,13 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.springframework.stereotype.Component; import com.cloud.storage.DataStoreRole; -import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; import com.cloud.storage.dao.SnapshotDao; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -50,10 +45,11 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { DataStoreManager storeMgr; @Inject VolumeDataFactory volumeFactory; + @Override public SnapshotInfo getSnapshot(long snapshotId, DataStore store) { SnapshotVO snapshot = snapshotDao.findById(snapshotId); - SnapshotObject so = SnapshotObject.getSnapshotObject(snapshot, store); + SnapshotObject so = SnapshotObject.getSnapshotObject(snapshot, store); return so; } @@ -63,7 +59,7 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { if (snapshot == null) { throw new CloudRuntimeException("Can't find snapshot: " + obj.getId()); } - SnapshotObject so = SnapshotObject.getSnapshotObject(snapshot, store); + SnapshotObject so = SnapshotObject.getSnapshotObject(snapshot, store); return so; } @@ -75,7 +71,7 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { return null; } DataStore store = this.storeMgr.getDataStore(snapshotStore.getDataStoreId(), role); - SnapshotObject so = SnapshotObject.getSnapshotObject(snapshot, store); + SnapshotObject so = SnapshotObject.getSnapshotObject(snapshot, store); return so; } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java index 8b3c1f6c181..6aee3ea9503 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java @@ -91,7 +91,8 @@ public class SnapshotObject implements SnapshotInfo { @Override public SnapshotInfo getParent() { - SnapshotDataStoreVO snapStoreVO = this.snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), this.snapshot.getId()); + SnapshotDataStoreVO snapStoreVO = this.snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), + this.store.getId(), this.snapshot.getId()); if (snapStoreVO == null) { return null; } @@ -106,7 +107,8 @@ public class SnapshotObject implements SnapshotInfo { @Override public SnapshotInfo getChild() { - SearchCriteriaService sc = SearchCriteria2.create(SnapshotDataStoreVO.class); + SearchCriteriaService sc = SearchCriteria2 + .create(SnapshotDataStoreVO.class); sc.addAnd(sc.getEntity().getDataStoreId(), Op.EQ, this.store.getId()); sc.addAnd(sc.getEntity().getRole(), Op.EQ, this.store.getRole()); sc.addAnd(sc.getEntity().getParentSnapshotId(), Op.EQ, this.getId()); @@ -246,8 +248,8 @@ public class SnapshotObject implements SnapshotInfo { @Override public void processEvent(ObjectInDataStoreStateMachine.Event event, Answer answer) { try { - SnapshotDataStoreVO snapshotStore = this.snapshotStoreDao.findByStoreSnapshot(this.getDataStore().getRole(), this.getDataStore().getId(), - this.getId()); + SnapshotDataStoreVO snapshotStore = this.snapshotStoreDao.findByStoreSnapshot( + this.getDataStore().getRole(), this.getDataStore().getId(), this.getId()); if (answer instanceof CreateObjectAnswer) { SnapshotObjectTO snapshotTO = (SnapshotObjectTO) ((CreateObjectAnswer) answer).getData(); snapshotStore.setInstallPath(snapshotTO.getPath()); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java index 5717c179858..545a6a0ecef 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.storage.snapshot; -import java.util.List; import java.util.concurrent.ExecutionException; import javax.inject.Inject; @@ -25,19 +24,16 @@ import javax.inject.Inject; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotResult; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotResult; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; @@ -51,10 +47,7 @@ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.agent.api.BackupSnapshotAnswer; -import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.dao.ClusterDao; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; @@ -70,391 +63,372 @@ import com.cloud.vm.snapshot.dao.VMSnapshotDao; @Component public class SnapshotServiceImpl implements SnapshotService { - private static final Logger s_logger = Logger.getLogger(SnapshotServiceImpl.class); - @Inject - protected VolumeDao _volsDao; - @Inject - protected UserVmDao _vmDao; - @Inject - protected PrimaryDataStoreDao _storagePoolDao; - @Inject - protected ClusterDao _clusterDao; - @Inject - protected SnapshotDao _snapshotDao; - @Inject - protected SnapshotDataStoreDao _snapshotStoreDao; + private static final Logger s_logger = Logger.getLogger(SnapshotServiceImpl.class); + @Inject + protected VolumeDao _volsDao; + @Inject + protected UserVmDao _vmDao; + @Inject + protected PrimaryDataStoreDao _storagePoolDao; + @Inject + protected ClusterDao _clusterDao; + @Inject + protected SnapshotDao _snapshotDao; + @Inject + protected SnapshotDataStoreDao _snapshotStoreDao; - @Inject - protected SnapshotManager snapshotMgr; - @Inject - protected VolumeManager volumeMgr; - @Inject - private ConfigurationDao _configDao; - @Inject - protected SnapshotStateMachineManager stateMachineManager; - @Inject - private VolumeDao volumeDao; - @Inject - SnapshotDataFactory snapshotfactory; - @Inject - DataStoreManager dataStoreMgr; - @Inject - DataMotionService motionSrv; - @Inject - ObjectInDataStoreManager objInStoreMgr; - @Inject - VMSnapshotDao _vmSnapshotDao; + @Inject + protected SnapshotManager snapshotMgr; + @Inject + protected VolumeManager volumeMgr; + @Inject + protected SnapshotStateMachineManager stateMachineManager; + @Inject + SnapshotDataFactory snapshotfactory; + @Inject + DataStoreManager dataStoreMgr; + @Inject + DataMotionService motionSrv; + @Inject + ObjectInDataStoreManager objInStoreMgr; + @Inject + VMSnapshotDao _vmSnapshotDao; + static private class CreateSnapshotContext extends AsyncRpcConext { + final SnapshotInfo snapshot; + final AsyncCallFuture future; + public CreateSnapshotContext(AsyncCompletionCallback callback, VolumeInfo volume, SnapshotInfo snapshot, + AsyncCallFuture future) { + super(callback); + this.snapshot = snapshot; + this.future = future; + } + } + static private class DeleteSnapshotContext extends AsyncRpcConext { + final SnapshotInfo snapshot; + final AsyncCallFuture future; - static private class CreateSnapshotContext extends AsyncRpcConext { - final VolumeInfo volume; - final SnapshotInfo snapshot; - final AsyncCallFuture future; - public CreateSnapshotContext(AsyncCompletionCallback callback, VolumeInfo volume, - SnapshotInfo snapshot, - AsyncCallFuture future) { - super(callback); - this.volume = volume; - this.snapshot = snapshot; - this.future = future; - } - } + public DeleteSnapshotContext(AsyncCompletionCallback callback, SnapshotInfo snapshot, + AsyncCallFuture future) { + super(callback); + this.snapshot = snapshot; + this.future = future; + } - static private class DeleteSnapshotContext extends AsyncRpcConext { - final SnapshotInfo snapshot; - final AsyncCallFuture future; - public DeleteSnapshotContext(AsyncCompletionCallback callback, SnapshotInfo snapshot, - AsyncCallFuture future) { - super(callback); - this.snapshot = snapshot; - this.future = future; - } + } - } + static private class CopySnapshotContext extends AsyncRpcConext { + final SnapshotInfo srcSnapshot; + final SnapshotInfo destSnapshot; + final AsyncCallFuture future; - static private class CopySnapshotContext extends AsyncRpcConext { - final SnapshotInfo srcSnapshot; - final SnapshotInfo destSnapshot; - final AsyncCallFuture future; - public CopySnapshotContext(AsyncCompletionCallback callback, - SnapshotInfo srcSnapshot, - SnapshotInfo destSnapshot, - AsyncCallFuture future) { - super(callback); - this.srcSnapshot = srcSnapshot; - this.destSnapshot = destSnapshot; - this.future = future; - } + public CopySnapshotContext(AsyncCompletionCallback callback, SnapshotInfo srcSnapshot, + SnapshotInfo destSnapshot, AsyncCallFuture future) { + super(callback); + this.srcSnapshot = srcSnapshot; + this.destSnapshot = destSnapshot; + this.future = future; + } - } + } - protected Void createSnapshotAsyncCallback(AsyncCallbackDispatcher callback, - CreateSnapshotContext context) { - CreateCmdResult result = callback.getResult(); - SnapshotObject snapshot = (SnapshotObject)context.snapshot; - AsyncCallFuture future = context.future; - SnapshotResult snapResult = new SnapshotResult(snapshot, result.getAnswer()); - if (result.isFailed()) { - s_logger.debug("create snapshot " + context.snapshot.getName() + " failed: " + result.getResult()); - try { - snapshot.processEvent(Snapshot.Event.OperationFailed); - snapshot.processEvent(Event.OperationFailed); - } catch (Exception e) { - s_logger.debug("Failed to update snapshot state due to " + e.getMessage()); - } + protected Void createSnapshotAsyncCallback(AsyncCallbackDispatcher callback, + CreateSnapshotContext context) { + CreateCmdResult result = callback.getResult(); + SnapshotObject snapshot = (SnapshotObject) context.snapshot; + AsyncCallFuture future = context.future; + SnapshotResult snapResult = new SnapshotResult(snapshot, result.getAnswer()); + if (result.isFailed()) { + s_logger.debug("create snapshot " + context.snapshot.getName() + " failed: " + result.getResult()); + try { + snapshot.processEvent(Snapshot.Event.OperationFailed); + snapshot.processEvent(Event.OperationFailed); + } catch (Exception e) { + s_logger.debug("Failed to update snapshot state due to " + e.getMessage()); + } - snapResult.setResult(result.getResult()); - future.complete(snapResult); - return null; - } + snapResult.setResult(result.getResult()); + future.complete(snapResult); + return null; + } - try { - snapshot.processEvent(Event.OperationSuccessed, result.getAnswer()); - snapshot.processEvent(Snapshot.Event.OperationSucceeded); - } catch (Exception e) { - s_logger.debug("Failed to create snapshot: ", e); - snapResult.setResult(e.toString()); - try { + try { + snapshot.processEvent(Event.OperationSuccessed, result.getAnswer()); + snapshot.processEvent(Snapshot.Event.OperationSucceeded); + } catch (Exception e) { + s_logger.debug("Failed to create snapshot: ", e); + snapResult.setResult(e.toString()); + try { snapshot.processEvent(Snapshot.Event.OperationFailed); } catch (NoTransitionException e1) { s_logger.debug("Failed to change snapshot state: " + e1.toString()); } - } + } - future.complete(snapResult); - return null; - } + future.complete(snapResult); + return null; + } + @Override + public SnapshotResult takeSnapshot(SnapshotInfo snap) { + SnapshotObject snapshot = (SnapshotObject) snap; + SnapshotObject snapshotOnPrimary = null; + try { + snapshotOnPrimary = (SnapshotObject) snap.getDataStore().create(snapshot); + } catch (Exception e) { + s_logger.debug("Failed to create snapshot state on data store due to " + e.getMessage()); + throw new CloudRuntimeException(e); + } - @Override - public SnapshotResult takeSnapshot(SnapshotInfo snap) { - SnapshotObject snapshot = (SnapshotObject)snap; + try { + snapshotOnPrimary.processEvent(Snapshot.Event.CreateRequested); + } catch (NoTransitionException e) { + s_logger.debug("Failed to change snapshot state: " + e.toString()); + throw new CloudRuntimeException(e); + } - SnapshotObject snapshotOnPrimary = null; - try { - snapshotOnPrimary = (SnapshotObject)snap.getDataStore().create(snapshot); - } catch(Exception e) { - s_logger.debug("Failed to create snapshot state on data store due to " + e.getMessage()); - throw new CloudRuntimeException(e); - } + try { + snapshotOnPrimary.processEvent(Event.CreateOnlyRequested); + } catch (Exception e) { + s_logger.debug("Failed to change snapshot state: " + e.toString()); + try { + snapshotOnPrimary.processEvent(Snapshot.Event.OperationFailed); + } catch (NoTransitionException e1) { + s_logger.debug("Failed to change snapshot state: " + e1.toString()); + } + throw new CloudRuntimeException(e); + } - try { - snapshotOnPrimary.processEvent(Snapshot.Event.CreateRequested); - } catch (NoTransitionException e) { - s_logger.debug("Failed to change snapshot state: " + e.toString()); - throw new CloudRuntimeException(e); - } - - try { - snapshotOnPrimary.processEvent(Event.CreateOnlyRequested); - } catch (Exception e) { - s_logger.debug("Failed to change snapshot state: " + e.toString()); - try { - snapshotOnPrimary.processEvent(Snapshot.Event.OperationFailed); - } catch (NoTransitionException e1) { - s_logger.debug("Failed to change snapshot state: " + e1.toString()); - } - throw new CloudRuntimeException(e); - } - - AsyncCallFuture future = new AsyncCallFuture(); - try { - CreateSnapshotContext context = new CreateSnapshotContext( - null, snap.getBaseVolume(), snapshotOnPrimary, future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().createSnapshotAsyncCallback(null, null)) - .setContext(context); - PrimaryDataStoreDriver primaryStore = (PrimaryDataStoreDriver)snapshotOnPrimary.getDataStore().getDriver(); - primaryStore.takeSnapshot(snapshot, caller); - } catch (Exception e) { - s_logger.debug("Failed to take snapshot: " + snapshot.getId(), e); - try { + AsyncCallFuture future = new AsyncCallFuture(); + try { + CreateSnapshotContext context = new CreateSnapshotContext(null, + snap.getBaseVolume(), snapshotOnPrimary, future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().createSnapshotAsyncCallback(null, null)).setContext(context); + PrimaryDataStoreDriver primaryStore = (PrimaryDataStoreDriver) snapshotOnPrimary.getDataStore().getDriver(); + primaryStore.takeSnapshot(snapshot, caller); + } catch (Exception e) { + s_logger.debug("Failed to take snapshot: " + snapshot.getId(), e); + try { snapshot.processEvent(Snapshot.Event.OperationFailed); } catch (NoTransitionException e1) { - s_logger.debug("Failed to change state for event: OperationFailed" , e); + s_logger.debug("Failed to change state for event: OperationFailed", e); } - throw new CloudRuntimeException("Failed to take snapshot" + snapshot.getId()); - } + throw new CloudRuntimeException("Failed to take snapshot" + snapshot.getId()); + } - SnapshotResult result; + SnapshotResult result; - try { - result = future.get(); - if (result.isFailed()) { - s_logger.debug("Failed to create snapshot:" + result.getResult()); - throw new CloudRuntimeException(result.getResult()); - } - return result; - } catch (InterruptedException e) { - s_logger.debug("Failed to create snapshot", e); - throw new CloudRuntimeException("Failed to create snapshot", e); - } catch (ExecutionException e) { - s_logger.debug("Failed to create snapshot", e); - throw new CloudRuntimeException("Failed to create snapshot", e); - } + try { + result = future.get(); + if (result.isFailed()) { + s_logger.debug("Failed to create snapshot:" + result.getResult()); + throw new CloudRuntimeException(result.getResult()); + } + return result; + } catch (InterruptedException e) { + s_logger.debug("Failed to create snapshot", e); + throw new CloudRuntimeException("Failed to create snapshot", e); + } catch (ExecutionException e) { + s_logger.debug("Failed to create snapshot", e); + throw new CloudRuntimeException("Failed to create snapshot", e); + } - } + } - // if a snapshot has parent snapshot, the new snapshot should be stored in the same store as its parent since - // we are taking delta snapshot - private DataStore findSnapshotImageStore(SnapshotInfo snapshot){ - if ( snapshot.getParent() == null ){ - return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); - } else{ - SnapshotInfo parentSnapshot = snapshot.getParent(); - // Note that DataStore information in parentSnapshot is for primary data store here, we need to - // find the image store where the parent snapshot backup is located - SnapshotDataStoreVO parentSnapshotOnBackupStore = _snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image); - return dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), - parentSnapshotOnBackupStore.getRole()); - } - } + // if a snapshot has parent snapshot, the new snapshot should be stored in + // the same store as its parent since + // we are taking delta snapshot + private DataStore findSnapshotImageStore(SnapshotInfo snapshot) { + if (snapshot.getParent() == null) { + return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); + } else { + SnapshotInfo parentSnapshot = snapshot.getParent(); + // Note that DataStore information in parentSnapshot is for primary + // data store here, we need to + // find the image store where the parent snapshot backup is located + SnapshotDataStoreVO parentSnapshotOnBackupStore = _snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), + DataStoreRole.Image); + return dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), + parentSnapshotOnBackupStore.getRole()); + } + } + @Override + public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { + SnapshotObject snapObj = (SnapshotObject) snapshot; + AsyncCallFuture future = new AsyncCallFuture(); + SnapshotResult result = new SnapshotResult(snapshot, null); + try { - @Override - public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { - SnapshotObject snapObj = (SnapshotObject)snapshot; - AsyncCallFuture future = new AsyncCallFuture(); - SnapshotResult result = new SnapshotResult(snapshot, null); - try { + snapObj.processEvent(Snapshot.Event.BackupToSecondary); - snapObj.processEvent(Snapshot.Event.BackupToSecondary); + DataStore imageStore = this.findSnapshotImageStore(snapshot); + if (imageStore == null) { + throw new CloudRuntimeException("can not find an image stores"); + } - DataStore imageStore = this.findSnapshotImageStore(snapshot); - if (imageStore == null) { - throw new CloudRuntimeException("can not find an image stores"); - } + SnapshotInfo snapshotOnImageStore = (SnapshotInfo) imageStore.create(snapshot); - SnapshotInfo snapshotOnImageStore = (SnapshotInfo)imageStore.create(snapshot); - - snapshotOnImageStore.processEvent(Event.CreateOnlyRequested); - CopySnapshotContext context = new CopySnapshotContext(null, snapshot, - snapshotOnImageStore, future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().copySnapshotAsyncCallback(null, null)) - .setContext(context); - this.motionSrv.copyAsync(snapshot, snapshotOnImageStore, caller); - } catch (Exception e) { - s_logger.debug("Failed to copy snapshot", e); - result.setResult("Failed to copy snapshot:" +e.toString()); - try { + snapshotOnImageStore.processEvent(Event.CreateOnlyRequested); + CopySnapshotContext context = new CopySnapshotContext(null, snapshot, + snapshotOnImageStore, future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher + .create(this); + caller.setCallback(caller.getTarget().copySnapshotAsyncCallback(null, null)).setContext(context); + this.motionSrv.copyAsync(snapshot, snapshotOnImageStore, caller); + } catch (Exception e) { + s_logger.debug("Failed to copy snapshot", e); + result.setResult("Failed to copy snapshot:" + e.toString()); + try { snapObj.processEvent(Snapshot.Event.OperationFailed); } catch (NoTransitionException e1) { s_logger.debug("Failed to change state: " + e1.toString()); } - future.complete(result); - } + future.complete(result); + } - try { - SnapshotResult res = future.get(); - if (res.isFailed()) { - throw new CloudRuntimeException(res.getResult()); - } - SnapshotInfo destSnapshot = res.getSnashot(); - return destSnapshot; - } catch (InterruptedException e) { - s_logger.debug("failed copy snapshot", e); - throw new CloudRuntimeException("Failed to copy snapshot" , e); - } catch (ExecutionException e) { - s_logger.debug("Failed to copy snapshot", e); - throw new CloudRuntimeException("Failed to copy snapshot" , e); - } + try { + SnapshotResult res = future.get(); + if (res.isFailed()) { + throw new CloudRuntimeException(res.getResult()); + } + SnapshotInfo destSnapshot = res.getSnashot(); + return destSnapshot; + } catch (InterruptedException e) { + s_logger.debug("failed copy snapshot", e); + throw new CloudRuntimeException("Failed to copy snapshot", e); + } catch (ExecutionException e) { + s_logger.debug("Failed to copy snapshot", e); + throw new CloudRuntimeException("Failed to copy snapshot", e); + } - } + } - protected Void copySnapshotAsyncCallback(AsyncCallbackDispatcher callback, - CopySnapshotContext context) { - CopyCommandResult result = callback.getResult(); - SnapshotInfo destSnapshot = context.destSnapshot; - SnapshotObject srcSnapshot = (SnapshotObject)context.srcSnapshot; - AsyncCallFuture future = context.future; - SnapshotResult snapResult = new SnapshotResult(destSnapshot, result.getAnswer()); - if (result.isFailed()) { - try { - destSnapshot.processEvent(Event.OperationFailed); - srcSnapshot.processEvent(Snapshot.Event.OperationFailed); - } catch (NoTransitionException e) { - s_logger.debug("Failed to update state: " + e.toString()); - } - snapResult.setResult(result.getResult()); - future.complete(snapResult); - return null; - } + protected Void copySnapshotAsyncCallback(AsyncCallbackDispatcher callback, + CopySnapshotContext context) { + CopyCommandResult result = callback.getResult(); + SnapshotInfo destSnapshot = context.destSnapshot; + SnapshotObject srcSnapshot = (SnapshotObject) context.srcSnapshot; + AsyncCallFuture future = context.future; + SnapshotResult snapResult = new SnapshotResult(destSnapshot, result.getAnswer()); + if (result.isFailed()) { + try { + destSnapshot.processEvent(Event.OperationFailed); + srcSnapshot.processEvent(Snapshot.Event.OperationFailed); + } catch (NoTransitionException e) { + s_logger.debug("Failed to update state: " + e.toString()); + } + snapResult.setResult(result.getResult()); + future.complete(snapResult); + return null; + } - try { - CopyCmdAnswer answer = (CopyCmdAnswer)result.getAnswer(); - destSnapshot.processEvent(Event.OperationSuccessed, result.getAnswer()); - srcSnapshot.processEvent(Snapshot.Event.OperationSucceeded); - snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(destSnapshot.getId(), destSnapshot.getDataStore()), answer); - future.complete(snapResult); - } catch (Exception e) { - s_logger.debug("Failed to update snapshot state", e); - snapResult.setResult(e.toString()); - future.complete(snapResult); - } - return null; - } + try { + CopyCmdAnswer answer = (CopyCmdAnswer) result.getAnswer(); + destSnapshot.processEvent(Event.OperationSuccessed, result.getAnswer()); + srcSnapshot.processEvent(Snapshot.Event.OperationSucceeded); + snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(destSnapshot.getId(), + destSnapshot.getDataStore()), answer); + future.complete(snapResult); + } catch (Exception e) { + s_logger.debug("Failed to update snapshot state", e); + snapResult.setResult(e.toString()); + future.complete(snapResult); + } + return null; + } - @DB - protected boolean destroySnapshotBackUp(SnapshotVO snapshot) { - SnapshotDataStoreVO snapshotStore = this._snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Image); - if ( snapshotStore == null ){ + @DB + protected boolean destroySnapshotBackUp(SnapshotVO snapshot) { + SnapshotDataStoreVO snapshotStore = this._snapshotStoreDao + .findBySnapshot(snapshot.getId(), DataStoreRole.Image); + if (snapshotStore == null) { s_logger.debug("Can't find snapshot" + snapshot.getId() + " backed up into image store"); return false; - } - DataStore store = this.dataStoreMgr.getDataStore(snapshotStore.getDataStoreId(), DataStoreRole.Image); - if (store == null) { - s_logger.debug("Can't find mage store " + snapshotStore.getDataStoreId()); - return false; - } + } + DataStore store = this.dataStoreMgr.getDataStore(snapshotStore.getDataStoreId(), DataStoreRole.Image); + if (store == null) { + s_logger.debug("Can't find mage store " + snapshotStore.getDataStoreId()); + return false; + } - try { - SnapshotInfo snapshotInfo = this.snapshotfactory.getSnapshot(snapshot.getId(), store); - snapshotInfo.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); + try { + SnapshotInfo snapshotInfo = this.snapshotfactory.getSnapshot(snapshot.getId(), store); + snapshotInfo.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); - AsyncCallFuture future = new AsyncCallFuture(); - DeleteSnapshotContext context = new DeleteSnapshotContext(null, - snapshotInfo, future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().deleteSnapshotCallback(null, null)) - .setContext(context); + AsyncCallFuture future = new AsyncCallFuture(); + DeleteSnapshotContext context = new DeleteSnapshotContext(null, snapshotInfo, + future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().deleteSnapshotCallback(null, null)).setContext(context); - store.getDriver().deleteAsync(snapshotInfo, caller); + store.getDriver().deleteAsync(snapshotInfo, caller); - SnapshotResult result = future.get(); - if (result.isFailed()) { - s_logger.debug("Failed to delete snapsoht: " + result.getResult()); - } - return result.isSuccess(); - } catch (Exception e) { - s_logger.debug("Failed to delete snapshot", e); - return false; - } - } + SnapshotResult result = future.get(); + if (result.isFailed()) { + s_logger.debug("Failed to delete snapsoht: " + result.getResult()); + } + return result.isSuccess(); + } catch (Exception e) { + s_logger.debug("Failed to delete snapshot", e); + return false; + } + } - protected Void deleteSnapshotCallback(AsyncCallbackDispatcher callback, - DeleteSnapshotContext context) { - CommandResult result = callback.getResult(); - AsyncCallFuture future = context.future; - SnapshotInfo snapshot = context.snapshot; - if (result.isFailed()) { - s_logger.debug("delete snapshot failed" + result.getResult()); - snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); - SnapshotResult res = new SnapshotResult(context.snapshot, null); - future.complete(res); - return null; - } - snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed); - SnapshotResult res = new SnapshotResult(context.snapshot, null); - future.complete(res); - return null; - } + protected Void deleteSnapshotCallback(AsyncCallbackDispatcher callback, + DeleteSnapshotContext context) { + CommandResult result = callback.getResult(); + AsyncCallFuture future = context.future; + SnapshotInfo snapshot = context.snapshot; + if (result.isFailed()) { + s_logger.debug("delete snapshot failed" + result.getResult()); + snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + SnapshotResult res = new SnapshotResult(context.snapshot, null); + future.complete(res); + return null; + } + snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed); + SnapshotResult res = new SnapshotResult(context.snapshot, null); + future.complete(res); + return null; + } - @Override - public boolean deleteSnapshot(SnapshotInfo snapInfo) { - snapInfo.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); + @Override + public boolean deleteSnapshot(SnapshotInfo snapInfo) { + snapInfo.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); - AsyncCallFuture future = new AsyncCallFuture(); - DeleteSnapshotContext context = new DeleteSnapshotContext(null, - snapInfo, future); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().deleteSnapshotCallback(null, null)) - .setContext(context); - DataStore store = snapInfo.getDataStore(); - store.getDriver().deleteAsync(snapInfo, caller); + AsyncCallFuture future = new AsyncCallFuture(); + DeleteSnapshotContext context = new DeleteSnapshotContext(null, snapInfo, future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().deleteSnapshotCallback(null, null)).setContext(context); + DataStore store = snapInfo.getDataStore(); + store.getDriver().deleteAsync(snapInfo, caller); - SnapshotResult result = null; - try { - result = future.get(); - if (result.isFailed()) { - throw new CloudRuntimeException(result.getResult()); - } - return true; - } catch (InterruptedException e) { - s_logger.debug("delete snapshot is failed: " + e.toString()); - } catch (ExecutionException e) { - s_logger.debug("delete snapshot is failed: " + e.toString()); - } + SnapshotResult result = null; + try { + result = future.get(); + if (result.isFailed()) { + throw new CloudRuntimeException(result.getResult()); + } + return true; + } catch (InterruptedException e) { + s_logger.debug("delete snapshot is failed: " + e.toString()); + } catch (ExecutionException e) { + s_logger.debug("delete snapshot is failed: " + e.toString()); + } - return false; + return false; - } + } - @Override - public boolean revertSnapshot(SnapshotInfo snapshot) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean revertSnapshot(SnapshotInfo snapshot) { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManager.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManager.java index c6057704cd8..f07db7ed9a0 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManager.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManager.java @@ -22,5 +22,5 @@ import com.cloud.storage.SnapshotVO; import com.cloud.utils.fsm.NoTransitionException; public interface SnapshotStateMachineManager { - public void processEvent(SnapshotVO snapshot, Event event) throws NoTransitionException; + public void processEvent(SnapshotVO snapshot, Event event) throws NoTransitionException; } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java index 489ba280e7d..c756ddb4876 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java @@ -31,30 +31,31 @@ import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; @Component -public class SnapshotStateMachineManagerImpl implements -SnapshotStateMachineManager { - private StateMachine2 stateMachine = new StateMachine2(); +public class SnapshotStateMachineManagerImpl implements SnapshotStateMachineManager { + private StateMachine2 stateMachine = new StateMachine2(); @Inject - protected SnapshotDao snapshotDao; - public SnapshotStateMachineManagerImpl() { - stateMachine.addTransition(Snapshot.State.Allocated, Event.CreateRequested, Snapshot.State.Creating); - stateMachine.addTransition(Snapshot.State.Creating, Event.OperationSucceeded, Snapshot.State.CreatedOnPrimary); - stateMachine.addTransition(Snapshot.State.Creating, Event.OperationNotPerformed, Snapshot.State.BackedUp); - stateMachine.addTransition(Snapshot.State.Creating, Event.OperationFailed, Snapshot.State.Error); - stateMachine.addTransition(Snapshot.State.CreatedOnPrimary, Event.BackupToSecondary, Snapshot.State.BackingUp); - stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationSucceeded, Snapshot.State.BackedUp); - stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationFailed, Snapshot.State.CreatedOnPrimary); - stateMachine.addTransition(Snapshot.State.BackedUp, Event.DestroyRequested, Snapshot.State.Destroying); - stateMachine.addTransition(Snapshot.State.BackedUp, Event.CopyingRequested, Snapshot.State.Copying); - stateMachine.addTransition(Snapshot.State.Copying, Event.OperationSucceeded, Snapshot.State.BackedUp); - stateMachine.addTransition(Snapshot.State.Copying, Event.OperationFailed, Snapshot.State.BackedUp); - stateMachine.addTransition(Snapshot.State.Destroying, Event.OperationSucceeded, Snapshot.State.Destroyed); - stateMachine.addTransition(Snapshot.State.Destroying, Event.OperationFailed, Snapshot.State.Error); - - stateMachine.registerListener(new SnapshotStateListener()); - } - - public void processEvent(SnapshotVO snapshot, Event event) throws NoTransitionException { - stateMachine.transitTo(snapshot, event, null, snapshotDao); - } -} + protected SnapshotDao snapshotDao; + + public SnapshotStateMachineManagerImpl() { + stateMachine.addTransition(Snapshot.State.Allocated, Event.CreateRequested, Snapshot.State.Creating); + stateMachine.addTransition(Snapshot.State.Creating, Event.OperationSucceeded, Snapshot.State.CreatedOnPrimary); + stateMachine.addTransition(Snapshot.State.Creating, Event.OperationNotPerformed, Snapshot.State.BackedUp); + stateMachine.addTransition(Snapshot.State.Creating, Event.OperationFailed, Snapshot.State.Error); + stateMachine.addTransition(Snapshot.State.CreatedOnPrimary, Event.BackupToSecondary, Snapshot.State.BackingUp); + stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationSucceeded, Snapshot.State.BackedUp); + stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationFailed, Snapshot.State.CreatedOnPrimary); + stateMachine.addTransition(Snapshot.State.BackedUp, Event.DestroyRequested, Snapshot.State.Destroying); + stateMachine.addTransition(Snapshot.State.BackedUp, Event.CopyingRequested, Snapshot.State.Copying); + stateMachine.addTransition(Snapshot.State.Copying, Event.OperationSucceeded, Snapshot.State.BackedUp); + stateMachine.addTransition(Snapshot.State.Copying, Event.OperationFailed, Snapshot.State.BackedUp); + stateMachine.addTransition(Snapshot.State.Destroying, Event.OperationSucceeded, Snapshot.State.Destroyed); + stateMachine.addTransition(Snapshot.State.Destroying, Event.OperationFailed, Snapshot.State.Error); + + stateMachine.registerListener(new SnapshotStateListener()); + } + + @Override + public void processEvent(SnapshotVO snapshot, Event event) throws NoTransitionException { + stateMachine.transitTo(snapshot, event, null, snapshotDao); + } +} diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStrategyBase.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStrategyBase.java index 5e78b017fbb..1b579227f84 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStrategyBase.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStrategyBase.java @@ -23,16 +23,16 @@ import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy; public abstract class SnapshotStrategyBase implements SnapshotStrategy { - @Inject - SnapshotService snapshotSvr; + @Inject + SnapshotService snapshotSvr; - @Override - public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) { - return snapshotSvr.takeSnapshot(snapshot).getSnashot(); - } + @Override + public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) { + return snapshotSvr.takeSnapshot(snapshot).getSnashot(); + } - @Override - public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { - return snapshotSvr.backupSnapshot(snapshot); - } + @Override + public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { + return snapshotSvr.backupSnapshot(snapshot); + } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java index 32504eeaed5..0c3f31c9ef8 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java @@ -16,18 +16,14 @@ // under the License. package org.apache.cloudstack.storage.snapshot; -import java.util.List; - import javax.inject.Inject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotResult; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.storage.command.CreateObjectAnswer; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; @@ -38,11 +34,9 @@ import org.springframework.stereotype.Component; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; -import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.utils.NumbersUtil; @@ -51,165 +45,161 @@ import com.cloud.utils.fsm.NoTransitionException; @Component public class XenserverSnapshotStrategy extends SnapshotStrategyBase { - private static final Logger s_logger = Logger - .getLogger(XenserverSnapshotStrategy.class); + private static final Logger s_logger = Logger.getLogger(XenserverSnapshotStrategy.class); - @Inject - SnapshotManager snapshotMgr; - @Inject - SnapshotService snapshotSvr; - @Inject - DataStoreManager dataStoreMgr; - @Inject - SnapshotDataStoreDao snapshotStoreDao; - @Inject - ConfigurationDao configDao; - @Inject - SnapshotDao snapshotDao; - @Inject - SnapshotDataFactory snapshotDataFactory; + @Inject + SnapshotManager snapshotMgr; + @Inject + SnapshotService snapshotSvr; + @Inject + DataStoreManager dataStoreMgr; + @Inject + SnapshotDataStoreDao snapshotStoreDao; + @Inject + ConfigurationDao configDao; + @Inject + SnapshotDao snapshotDao; + @Inject + SnapshotDataFactory snapshotDataFactory; - @Override - public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { - SnapshotInfo parentSnapshot = snapshot.getParent(); - if (parentSnapshot != null && parentSnapshot.getPath().equalsIgnoreCase(snapshot.getPath())) { - s_logger.debug("backup an empty snapshot"); - //don't need to backup this snapshot - SnapshotDataStoreVO parentSnapshotOnBackupStore = this.snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image); - if (parentSnapshotOnBackupStore != null && - parentSnapshotOnBackupStore.getState() == State.Ready) { - DataStore store = dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), - parentSnapshotOnBackupStore.getRole()); + @Override + public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { + SnapshotInfo parentSnapshot = snapshot.getParent(); + if (parentSnapshot != null && parentSnapshot.getPath().equalsIgnoreCase(snapshot.getPath())) { + s_logger.debug("backup an empty snapshot"); + // don't need to backup this snapshot + SnapshotDataStoreVO parentSnapshotOnBackupStore = this.snapshotStoreDao.findBySnapshot( + parentSnapshot.getId(), DataStoreRole.Image); + if (parentSnapshotOnBackupStore != null && parentSnapshotOnBackupStore.getState() == State.Ready) { + DataStore store = dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), + parentSnapshotOnBackupStore.getRole()); - SnapshotInfo snapshotOnImageStore = (SnapshotInfo)store.create(snapshot); - snapshotOnImageStore.processEvent(Event.CreateOnlyRequested); + SnapshotInfo snapshotOnImageStore = (SnapshotInfo) store.create(snapshot); + snapshotOnImageStore.processEvent(Event.CreateOnlyRequested); - SnapshotObjectTO snapTO = new SnapshotObjectTO(); - snapTO.setPath(parentSnapshotOnBackupStore.getInstallPath()); - CreateObjectAnswer createSnapshotAnswer = new CreateObjectAnswer(snapTO); + SnapshotObjectTO snapTO = new SnapshotObjectTO(); + snapTO.setPath(parentSnapshotOnBackupStore.getInstallPath()); + CreateObjectAnswer createSnapshotAnswer = new CreateObjectAnswer(snapTO); - snapshotOnImageStore.processEvent(Event.OperationSuccessed, createSnapshotAnswer); - SnapshotObject snapObj = (SnapshotObject)snapshot; - try { - snapObj.processEvent(Snapshot.Event.OperationNotPerformed); - } catch (NoTransitionException e) { - s_logger.debug("Failed to change state: " + snapshot.getId() + ": " +e.toString()); - throw new CloudRuntimeException(e.toString()); - } - return this.snapshotDataFactory.getSnapshot(snapObj.getId(), store); - } else { - s_logger.debug("parent snapshot hasn't been backed up yet"); - } - } + snapshotOnImageStore.processEvent(Event.OperationSuccessed, createSnapshotAnswer); + SnapshotObject snapObj = (SnapshotObject) snapshot; + try { + snapObj.processEvent(Snapshot.Event.OperationNotPerformed); + } catch (NoTransitionException e) { + s_logger.debug("Failed to change state: " + snapshot.getId() + ": " + e.toString()); + throw new CloudRuntimeException(e.toString()); + } + return this.snapshotDataFactory.getSnapshot(snapObj.getId(), store); + } else { + s_logger.debug("parent snapshot hasn't been backed up yet"); + } + } - //determine full snapshot backup or not + // determine full snapshot backup or not - boolean fullBackup = false; - long preSnapshotId = 0; - if (parentSnapshot != null) { + boolean fullBackup = false; - preSnapshotId = parentSnapshot.getId(); - int _deltaSnapshotMax = NumbersUtil.parseInt(configDao.getValue("snapshot.delta.max"), SnapshotManager.DELTAMAX); - int deltaSnap = _deltaSnapshotMax; + if (parentSnapshot != null) { + int _deltaSnapshotMax = NumbersUtil.parseInt(configDao.getValue("snapshot.delta.max"), + SnapshotManager.DELTAMAX); + int deltaSnap = _deltaSnapshotMax; - int i; - SnapshotDataStoreVO parentSnapshotOnBackupStore = null; - for (i = 1; i < deltaSnap; i++) { - parentSnapshotOnBackupStore = this.snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image); + int i; + SnapshotDataStoreVO parentSnapshotOnBackupStore = null; + for (i = 1; i < deltaSnap; i++) { + parentSnapshotOnBackupStore = this.snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), + DataStoreRole.Image); - Long prevBackupId = parentSnapshotOnBackupStore.getParentSnapshotId(); + Long prevBackupId = parentSnapshotOnBackupStore.getParentSnapshotId(); - if (prevBackupId == 0) { - break; - } + if (prevBackupId == 0) { + break; + } - parentSnapshotOnBackupStore = this.snapshotStoreDao.findBySnapshot(prevBackupId, DataStoreRole.Image); - } - if (i >= deltaSnap) { - fullBackup = true; - } - } - - snapshot.addPayload(fullBackup); - return this.snapshotSvr.backupSnapshot(snapshot); - } - - protected void deleteSnapshotChain(SnapshotInfo snapshot) { - while(snapshot != null) { - SnapshotInfo child = snapshot.getChild(); - SnapshotInfo parent = snapshot.getParent(); - if (child == null) { - if (parent == null || !parent.getPath().equalsIgnoreCase(snapshot.getPath())) { - this.snapshotSvr.deleteSnapshot(snapshot); - snapshot = parent; - continue; - } - break; - } else { - break; - } - } - } + parentSnapshotOnBackupStore = this.snapshotStoreDao.findBySnapshot(prevBackupId, DataStoreRole.Image); + } + if (i >= deltaSnap) { + fullBackup = true; + } + } - @Override - public boolean deleteSnapshot(Long snapshotId) { - SnapshotVO snapshotVO = snapshotDao.findById(snapshotId); - if (snapshotVO.getState() == Snapshot.State.Destroyed) { - return true; - } - - if (!Snapshot.State.BackedUp.equals(snapshotVO.getState())) { - throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status"); - } + snapshot.addPayload(fullBackup); + return this.snapshotSvr.backupSnapshot(snapshot); + } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Calling deleteSnapshot for snapshotId: " + snapshotId); - } - - - //firt mark the snapshot as destroyed, so that ui can't see it, but we may not destroy the snapshot on the storage, as other snaphosts may depend on it. - SnapshotInfo snapshotOnPrimary = this.snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Primary); - SnapshotObject obj = (SnapshotObject)snapshotOnPrimary; - try { + protected void deleteSnapshotChain(SnapshotInfo snapshot) { + while (snapshot != null) { + SnapshotInfo child = snapshot.getChild(); + SnapshotInfo parent = snapshot.getParent(); + if (child == null) { + if (parent == null || !parent.getPath().equalsIgnoreCase(snapshot.getPath())) { + this.snapshotSvr.deleteSnapshot(snapshot); + snapshot = parent; + continue; + } + break; + } else { + break; + } + } + } + + @Override + public boolean deleteSnapshot(Long snapshotId) { + SnapshotVO snapshotVO = snapshotDao.findById(snapshotId); + if (snapshotVO.getState() == Snapshot.State.Destroyed) { + return true; + } + + if (!Snapshot.State.BackedUp.equals(snapshotVO.getState())) { + throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + + " due to it is not in BackedUp Status"); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Calling deleteSnapshot for snapshotId: " + snapshotId); + } + + // firt mark the snapshot as destroyed, so that ui can't see it, but we + // may not destroy the snapshot on the storage, as other snaphosts may + // depend on it. + SnapshotInfo snapshotOnPrimary = this.snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Primary); + SnapshotObject obj = (SnapshotObject) snapshotOnPrimary; + try { obj.processEvent(Snapshot.Event.DestroyRequested); } catch (NoTransitionException e) { s_logger.debug("Failed to destroy snapshot: " + e.toString()); return false; } - - try { - /* - if (snapshotOnPrimary != null) { - deleteSnapshotChain(snapshotOnPrimary); - }*/ - SnapshotInfo snapshotOnImage = this.snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Image); - if (snapshotOnImage != null) { - deleteSnapshotChain(snapshotOnImage); - } - - obj.processEvent(Snapshot.Event.OperationSucceeded); - } catch (Exception e) { - s_logger.debug("Failed to delete snapshot: " + e.toString()); - try { + try { + SnapshotInfo snapshotOnImage = this.snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Image); + if (snapshotOnImage != null) { + deleteSnapshotChain(snapshotOnImage); + } + + obj.processEvent(Snapshot.Event.OperationSucceeded); + } catch (Exception e) { + s_logger.debug("Failed to delete snapshot: " + e.toString()); + try { obj.processEvent(Snapshot.Event.OperationFailed); } catch (NoTransitionException e1) { s_logger.debug("Failed to change snapshot state: " + e.toString()); } - } - - return true; - } - - @Override - public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) { - snapshot = snapshotSvr.takeSnapshot(snapshot).getSnashot(); - //TODO: add async - return this.backupSnapshot(snapshot); - } + } + + return true; + } + + @Override + public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) { + snapshot = snapshotSvr.takeSnapshot(snapshot).getSnashot(); + // TODO: add async + return this.backupSnapshot(snapshot); + } @Override public boolean canHandle(Snapshot snapshot) { - return true; + return true; } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/db/SnapshotVO.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/db/SnapshotVO.java index b05b803623f..43ec6097cac 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/db/SnapshotVO.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/db/SnapshotVO.java @@ -35,87 +35,88 @@ import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; @Entity -@Table(name="snapshots") +@Table(name = "snapshots") public class SnapshotVO { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private final long id = -1; - @Column(name="data_center_id") + @Column(name = "data_center_id") long dataCenterId; - @Column(name="account_id") + @Column(name = "account_id") long accountId; - @Column(name="domain_id") + @Column(name = "domain_id") long domainId; - @Column(name="volume_id") + @Column(name = "volume_id") Long volumeId; - @Column(name="disk_offering_id") + @Column(name = "disk_offering_id") Long diskOfferingId; @Expose - @Column(name="path") + @Column(name = "path") String path; @Expose - @Column(name="name") + @Column(name = "name") String name; @Expose - @Column(name="status", updatable = true, nullable=false) - @Enumerated(value=EnumType.STRING) + @Column(name = "status", updatable = true, nullable = false) + @Enumerated(value = EnumType.STRING) private State status; - @Column(name="snapshot_type") + @Column(name = "snapshot_type") short snapshotType; - @Column(name="type_description") + @Column(name = "type_description") String typeDescription; - @Column(name="size") + @Column(name = "size") long size; - @Column(name=GenericDao.CREATED_COLUMN) + @Column(name = GenericDao.CREATED_COLUMN) Date created; - @Column(name=GenericDao.REMOVED_COLUMN) + @Column(name = GenericDao.REMOVED_COLUMN) Date removed; - @Column(name="backup_snap_id") + @Column(name = "backup_snap_id") String backupSnapshotId; - @Column(name="swift_id") + @Column(name = "swift_id") Long swiftId; - @Column(name="s3_id") + @Column(name = "s3_id") Long s3Id; - @Column(name="sechost_id") + @Column(name = "sechost_id") Long secHostId; - @Column(name="prev_snap_id") + @Column(name = "prev_snap_id") long prevSnapshotId; - @Column(name="hypervisor_type") - @Enumerated(value=EnumType.STRING) - HypervisorType hypervisorType; + @Column(name = "hypervisor_type") + @Enumerated(value = EnumType.STRING) + HypervisorType hypervisorType; @Expose - @Column(name="version") + @Column(name = "version") String version; - @Column(name="uuid") + @Column(name = "uuid") String uuid; public SnapshotVO() { this.uuid = UUID.randomUUID().toString(); } - public SnapshotVO(long dcId, long accountId, long domainId, Long volumeId, Long diskOfferingId, String path, String name, short snapshotType, String typeDescription, long size, HypervisorType hypervisorType ) { + public SnapshotVO(long dcId, long accountId, long domainId, Long volumeId, Long diskOfferingId, String path, + String name, short snapshotType, String typeDescription, long size, HypervisorType hypervisorType) { this.dataCenterId = dcId; this.accountId = accountId; this.domainId = domainId; @@ -141,16 +142,14 @@ public class SnapshotVO { return dataCenterId; } - public long getAccountId() { return accountId; } - public long getDomainId() { return domainId; } - + public long getVolumeId() { return volumeId; } @@ -210,8 +209,8 @@ public class SnapshotVO { this.snapshotType = snapshotType; } - public boolean isRecursive(){ - if ( snapshotType >= Type.HOURLY.ordinal() && snapshotType <= Type.MONTHLY.ordinal() ) { + public boolean isRecursive() { + if (snapshotType >= Type.HOURLY.ordinal() && snapshotType <= Type.MONTHLY.ordinal()) { return true; } return false; @@ -224,6 +223,7 @@ public class SnapshotVO { public String getTypeDescription() { return typeDescription; } + public void setTypeDescription(String typeDescription) { this.typeDescription = typeDescription; } @@ -252,25 +252,25 @@ public class SnapshotVO { this.status = status; } - public String getBackupSnapshotId(){ + public String getBackupSnapshotId() { return backupSnapshotId; } - public long getPrevSnapshotId(){ + public long getPrevSnapshotId() { return prevSnapshotId; } - public void setBackupSnapshotId(String backUpSnapshotId){ + public void setBackupSnapshotId(String backUpSnapshotId) { this.backupSnapshotId = backUpSnapshotId; } - public void setPrevSnapshotId(long prevSnapshotId){ + public void setPrevSnapshotId(long prevSnapshotId) { this.prevSnapshotId = prevSnapshotId; } public static Type getSnapshotType(String snapshotType) { - for ( Type type : Type.values()) { - if ( type.equals(snapshotType)) { + for (Type type : Type.values()) { + if (type.equals(snapshotType)) { return type; } } diff --git a/engine/storage/snapshot/test/src/SnapshotDataFactoryTest.java b/engine/storage/snapshot/test/src/SnapshotDataFactoryTest.java index e722ab55c70..317521de734 100644 --- a/engine/storage/snapshot/test/src/SnapshotDataFactoryTest.java +++ b/engine/storage/snapshot/test/src/SnapshotDataFactoryTest.java @@ -18,33 +18,24 @@ */ package src; -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.cloud.utils.component.ComponentContext; - import junit.framework.TestCase; //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(locations = "classpath:/SnapshotManagerTestContext.xml") public class SnapshotDataFactoryTest extends TestCase { - //@Inject SnapshotDataFactory snapshotFactory; - + // @Inject SnapshotDataFactory snapshotFactory; + @Before public void setup() throws Exception { - //ComponentContext.initComponentsLifeCycle(); - + // ComponentContext.initComponentsLifeCycle(); + } - + @Test public void testGestSnapshot() { - //snapshotFactory.getSnapshot(snapshotId); + // snapshotFactory.getSnapshot(snapshotId); } - + } diff --git a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java index a5b45e17f03..539792628c1 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java +++ b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.storage; public abstract class BaseType { + @Override public boolean equals(Object that) { if (this == that) { return true; diff --git a/engine/storage/src/org/apache/cloudstack/storage/HostEndpointRpcServer.java b/engine/storage/src/org/apache/cloudstack/storage/HostEndpointRpcServer.java deleted file mode 100644 index 01611be3c42..00000000000 --- a/engine/storage/src/org/apache/cloudstack/storage/HostEndpointRpcServer.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage; - -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; - -public interface HostEndpointRpcServer { - void sendCommandAsync(RemoteHostEndPoint ep, final Command command, final AsyncCompletionCallback callback); - Answer sendCommand(RemoteHostEndPoint ep, final Command command); -} diff --git a/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPointRpcServer.java b/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPointRpcServer.java deleted file mode 100644 index 5675b73b662..00000000000 --- a/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPointRpcServer.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage; - -import javax.annotation.PostConstruct; -import javax.inject.Inject; - -import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.framework.async.AsyncRpcConext; -import org.apache.cloudstack.framework.rpc.RpcCallbackListener; -import org.apache.cloudstack.framework.rpc.RpcException; -import org.apache.cloudstack.framework.rpc.RpcProvider; -import org.apache.cloudstack.framework.rpc.RpcServiceDispatcher; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.utils.exception.CloudRuntimeException; - -@Component -public class HypervisorHostEndPointRpcServer implements HostEndpointRpcServer { - private static final Logger s_logger = Logger.getLogger(HypervisorHostEndPointRpcServer.class); - - @Inject - private RpcProvider rpcProvider; - - public HypervisorHostEndPointRpcServer() { - } - - public HypervisorHostEndPointRpcServer(RpcProvider rpcProvider) { - rpcProvider = rpcProvider; - rpcProvider.registerRpcServiceEndpoint(RpcServiceDispatcher.getDispatcher(this)); - } - - @PostConstruct - public void Initialize() { - rpcProvider.registerRpcServiceEndpoint(RpcServiceDispatcher.getDispatcher(this)); - } - - @Override - public void sendCommandAsync(RemoteHostEndPoint host, final Command command, final AsyncCompletionCallback callback) { - rpcProvider.newCall(host.getHostAddr()).addCallbackListener(new RpcCallbackListener() { - @Override - public void onSuccess(Answer result) { - callback.complete(result); - } - - @Override - public void onFailure(RpcException e) { - Answer answer = new Answer(command, false, e.toString()); - callback.complete(answer); - } - }).apply(); - } - - private class SendCommandContext extends AsyncRpcConext { - private T answer; - - public SendCommandContext(AsyncCompletionCallback callback) { - super(callback); - } - - public void setAnswer(T answer) { - this.answer = answer; - } - - public T getAnswer() { - return this.answer; - } - - } - - @Override - public Answer sendCommand(RemoteHostEndPoint host, Command command) { - SendCommandContext context = new SendCommandContext(null); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().sendCommandCallback(null, null)) - .setContext(context); - - this.sendCommandAsync(host, command, caller); - - synchronized (context) { - try { - context.wait(); - } catch (InterruptedException e) { - s_logger.debug(e.toString()); - throw new CloudRuntimeException("wait on context is interrupted", e); - } - } - - return context.getAnswer(); - } - - protected Object sendCommandCallback(AsyncCallbackDispatcher callback, SendCommandContext context) { - context.setAnswer((Answer)callback.getResult()); - synchronized(context) { - context.notify(); - } - return null; - } -} diff --git a/engine/storage/src/org/apache/cloudstack/storage/LocalHostEndpoint.java b/engine/storage/src/org/apache/cloudstack/storage/LocalHostEndpoint.java index c0957916e7d..18fcd7178d2 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/LocalHostEndpoint.java +++ b/engine/storage/src/org/apache/cloudstack/storage/LocalHostEndpoint.java @@ -26,38 +26,34 @@ import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.command.DownloadCommand; import org.apache.cloudstack.storage.resource.LocalNfsSecondaryStorageResource; -import com.cloud.agent.Listener; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; -import com.cloud.agent.api.storage.DownloadAnswer; import com.cloud.resource.ServerResource; -import com.cloud.storage.VMTemplateStorageResourceAssoc; -import com.cloud.storage.download.DownloadListener; import com.cloud.utils.net.NetUtils; public class LocalHostEndpoint implements EndPoint { - private ScheduledExecutorService executor; - protected ServerResource resource; - public LocalHostEndpoint() { + private ScheduledExecutorService executor; + protected ServerResource resource; + + public LocalHostEndpoint() { resource = new LocalNfsSecondaryStorageResource(); - executor = Executors.newScheduledThreadPool(10); - } - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } + executor = Executors.newScheduledThreadPool(10); + } + @Override + public long getId() { + // TODO Auto-generated method stub + return 0; + } - @Override + @Override public String getHostAddr() { return "127.0.0.0"; } - @Override public String getPublicAddr() { - String hostIp= NetUtils.getDefaultHostIp(); + String hostIp = NetUtils.getDefaultHostIp(); if (hostIp != null) return hostIp; else @@ -65,70 +61,41 @@ public class LocalHostEndpoint implements EndPoint { } @Override - public Answer sendMessage(Command cmd) { - if ((cmd instanceof CopyCommand) || (cmd instanceof DownloadCommand)) { - return resource.executeRequest(cmd); - } - // TODO Auto-generated method stub - return new Answer(cmd, false, "unsupported command:" + cmd.toString()); - } + public Answer sendMessage(Command cmd) { + if ((cmd instanceof CopyCommand) || (cmd instanceof DownloadCommand)) { + return resource.executeRequest(cmd); + } + // TODO Auto-generated method stub + return new Answer(cmd, false, "unsupported command:" + cmd.toString()); + } - private class CmdRunner implements Runnable { - final Command cmd; - final AsyncCompletionCallback callback; - public CmdRunner(Command cmd, AsyncCompletionCallback callback) { - this.cmd = cmd; - this.callback = callback; - } - @Override - public void run() { - Answer answer = sendMessage(cmd); - callback.complete(answer); - } - } + private class CmdRunner implements Runnable { + final Command cmd; + final AsyncCompletionCallback callback; - private class CmdRunner2 implements Runnable { - final Command cmd; - final Listener listener; - public CmdRunner2(Command cmd, Listener listener) { - this.cmd = cmd; - this.listener = listener; - } - @Override - public void run() { - try { - DownloadAnswer answer = (DownloadAnswer) sendMessage(cmd); - Answer[] answers = new Answer[1]; - answers[0] = answer; - listener.processAnswers(getId(), 0, answers); - if (listener instanceof DownloadListener) { - DownloadListener dwldListener = (DownloadListener)listener; - dwldListener.getCallback().complete(answer); - } - } catch (Exception ex) { - DownloadAnswer fail = new DownloadAnswer("Error in handling DownloadCommand : " + ex.getMessage(), VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR); - Answer[] answers = new Answer[1]; - answers[0] = fail; - listener.processAnswers(getId(), 0, answers); - if (listener instanceof DownloadListener) { - DownloadListener dwldListener = (DownloadListener)listener; - dwldListener.getCallback().complete(fail); - } - } - } - } - @Override + public CmdRunner(Command cmd, AsyncCompletionCallback callback) { + this.cmd = cmd; + this.callback = callback; + } + + @Override + public void run() { + Answer answer = sendMessage(cmd); + callback.complete(answer); + } + } + + @Override public void sendMessageAsync(Command cmd, AsyncCompletionCallback callback) { - executor.schedule(new CmdRunner(cmd, callback), 10, TimeUnit.SECONDS); - } + executor.schedule(new CmdRunner(cmd, callback), 10, TimeUnit.SECONDS); + } public ServerResource getResource() { return resource; } + public void setResource(ServerResource resource) { this.resource = resource; } - - } diff --git a/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java b/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java index 5b0debba344..cd64ab2457c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java +++ b/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java @@ -47,19 +47,17 @@ import com.cloud.utils.exception.CloudRuntimeException; public class RemoteHostEndPoint implements EndPoint { private static final Logger s_logger = Logger.getLogger(RemoteHostEndPoint.class); - private long hostId; - private String hostAddress; - private String publicAddress; + private long hostId; + private String hostAddress; + private String publicAddress; @Inject AgentManager agentMgr; @Inject - HostEndpointRpcServer rpcServer; - @Inject protected HypervisorGuruManager _hvGuruMgr; private ScheduledExecutorService executor; public RemoteHostEndPoint() { - executor = Executors.newScheduledThreadPool(10); + executor = Executors.newScheduledThreadPool(10); } private void configure(long hostId, String hostAddress, String publicAddress) { @@ -79,7 +77,7 @@ public class RemoteHostEndPoint implements EndPoint { return this.hostAddress; } - + @Override public String getPublicAddr() { return this.publicAddress; } @@ -91,27 +89,27 @@ public class RemoteHostEndPoint implements EndPoint { @Override public Answer sendMessage(Command cmd) { - String errMsg = null; - try { - long newHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(hostId, cmd); - return agentMgr.send(newHostId, cmd); - } catch (AgentUnavailableException e) { - errMsg = e.toString(); - s_logger.debug("Failed to send command, due to Agent:" + getId() + ", " + e.toString()); - } catch (OperationTimedoutException e) { - errMsg = e.toString(); - s_logger.debug("Failed to send command, due to Agent:" + getId() + ", " + e.toString()); - } - throw new CloudRuntimeException("Failed to send command, due to Agent:" + getId() + ", " + errMsg); + String errMsg = null; + try { + long newHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(hostId, cmd); + return agentMgr.send(newHostId, cmd); + } catch (AgentUnavailableException e) { + errMsg = e.toString(); + s_logger.debug("Failed to send command, due to Agent:" + getId() + ", " + e.toString()); + } catch (OperationTimedoutException e) { + errMsg = e.toString(); + s_logger.debug("Failed to send command, due to Agent:" + getId() + ", " + e.toString()); + } + throw new CloudRuntimeException("Failed to send command, due to Agent:" + getId() + ", " + errMsg); } private class CmdRunner implements Listener, Runnable { - final AsyncCompletionCallback callback; + final AsyncCompletionCallback callback; Answer answer; public CmdRunner(AsyncCompletionCallback callback) { - this.callback = callback; - } + this.callback = callback; + } @Override public boolean processAnswers(long agentId, long seq, Answer[] answers) { @@ -166,12 +164,12 @@ public class RemoteHostEndPoint implements EndPoint { public void run() { callback.complete(answer); } - } + } @Override public void sendMessageAsync(Command cmd, AsyncCompletionCallback callback) { try { - long newHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(this.hostId, cmd); + long newHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(this.hostId, cmd); agentMgr.send(newHostId, new Commands(cmd), new CmdRunner(callback)); } catch (AgentUnavailableException e) { throw new CloudRuntimeException("Unable to send message", e); diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java index 3a66b859b39..010e4685b20 100755 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java @@ -53,140 +53,153 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; public abstract class AbstractStoragePoolAllocator extends AdapterBase implements StoragePoolAllocator { - private static final Logger s_logger = Logger.getLogger(AbstractStoragePoolAllocator.class); - @Inject StorageManager storageMgr; - protected @Inject PrimaryDataStoreDao _storagePoolDao; - @Inject VolumeDao _volumeDao; - @Inject ConfigurationDao _configDao; - @Inject ClusterDao _clusterDao; - protected @Inject DataStoreManager dataStoreMgr; - protected BigDecimal _storageOverprovisioningFactor = new BigDecimal(1); + private static final Logger s_logger = Logger.getLogger(AbstractStoragePoolAllocator.class); + @Inject + StorageManager storageMgr; + protected @Inject + PrimaryDataStoreDao _storagePoolDao; + @Inject + VolumeDao _volumeDao; + @Inject + ConfigurationDao _configDao; + @Inject + ClusterDao _clusterDao; + protected @Inject + DataStoreManager dataStoreMgr; + protected BigDecimal _storageOverprovisioningFactor = new BigDecimal(1); long _extraBytesPerVolume = 0; Random _rand; boolean _dontMatter; protected String _allocationAlgorithm = "random"; @Inject DiskOfferingDao _diskOfferingDao; - + @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - + Map configs = _configDao.getConfiguration(null, params); - + String globalStorageOverprovisioningFactor = configs.get("storage.overprovisioning.factor"); - _storageOverprovisioningFactor = new BigDecimal(NumbersUtil.parseFloat(globalStorageOverprovisioningFactor, 2.0f)); - + _storageOverprovisioningFactor = new BigDecimal(NumbersUtil.parseFloat(globalStorageOverprovisioningFactor, + 2.0f)); + _extraBytesPerVolume = 0; - + _rand = new Random(System.currentTimeMillis()); _dontMatter = Boolean.parseBoolean(configs.get("storage.overwrite.provisioning")); String allocationAlgorithm = configs.get("vm.allocation.algorithm"); if (allocationAlgorithm != null) { - _allocationAlgorithm = allocationAlgorithm; + _allocationAlgorithm = allocationAlgorithm; } return true; } - - protected abstract List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo); - + + protected abstract List select(DiskProfile dskCh, + VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, + int returnUpTo); + @Override - public - List allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { - List pools = select(dskCh, vmProfile, plan, avoid, returnUpTo); - return reOrder(pools, vmProfile, plan); + public List allocateToPool(DiskProfile dskCh, + VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, + int returnUpTo) { + List pools = select(dskCh, vmProfile, plan, avoid, returnUpTo); + return reOrder(pools, vmProfile, plan); } - - protected List reorderPoolsByNumberOfVolumes(DeploymentPlan plan, List pools, Account account) { - if(account == null){ + + protected List reorderPoolsByNumberOfVolumes(DeploymentPlan plan, List pools, + Account account) { + if (account == null) { return pools; } long dcId = plan.getDataCenterId(); Long podId = plan.getPodId(); Long clusterId = plan.getClusterId(); - - List poolIdsByVolCount = _volumeDao.listPoolIdsByVolumeCount(dcId, podId, clusterId, account.getAccountId()); + + List poolIdsByVolCount = _volumeDao.listPoolIdsByVolumeCount(dcId, podId, clusterId, + account.getAccountId()); if (s_logger.isDebugEnabled()) { - s_logger.debug("List of pools in ascending order of number of volumes for account id: "+ account.getAccountId() + " is: "+ poolIdsByVolCount); + s_logger.debug("List of pools in ascending order of number of volumes for account id: " + + account.getAccountId() + " is: " + poolIdsByVolCount); } - - //now filter the given list of Pools by this ordered list - Map poolMap = new HashMap(); + + // now filter the given list of Pools by this ordered list + Map poolMap = new HashMap(); for (StoragePool pool : pools) { poolMap.put(pool.getId(), pool); } List matchingPoolIds = new ArrayList(poolMap.keySet()); - + poolIdsByVolCount.retainAll(matchingPoolIds); - + List reorderedPools = new ArrayList(); - for(Long id: poolIdsByVolCount){ + for (Long id : poolIdsByVolCount) { reorderedPools.add(poolMap.get(id)); } - + return reorderedPools; } - - protected List reOrder(List pools, - VirtualMachineProfile vmProfile, - DeploymentPlan plan) { - Account account = null; - if(vmProfile.getVirtualMachine() != null){ - account = vmProfile.getOwner(); - } - - if(_allocationAlgorithm.equals("random") || _allocationAlgorithm.equals("userconcentratedpod_random") || (account == null)) { - // Shuffle this so that we don't check the pools in the same order. - Collections.shuffle(pools); - }else if(_allocationAlgorithm.equals("userdispersing")){ - pools = reorderPoolsByNumberOfVolumes(plan, pools, account); - } - return pools; - } - - protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, - DeploymentPlan plan) { - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Checking if storage pool is suitable, name: " + pool.getName()+ " ,poolId: "+ pool.getId()); + + protected List reOrder(List pools, + VirtualMachineProfile vmProfile, DeploymentPlan plan) { + Account account = null; + if (vmProfile.getVirtualMachine() != null) { + account = vmProfile.getOwner(); } - if (avoid.shouldAvoid(pool)) { - if (s_logger.isDebugEnabled()) { + + if (_allocationAlgorithm.equals("random") || _allocationAlgorithm.equals("userconcentratedpod_random") + || (account == null)) { + // Shuffle this so that we don't check the pools in the same order. + Collections.shuffle(pools); + } else if (_allocationAlgorithm.equals("userdispersing")) { + pools = reorderPoolsByNumberOfVolumes(plan, pools, account); + } + return pools; + } + + protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, DeploymentPlan plan) { + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Checking if storage pool is suitable, name: " + pool.getName() + " ,poolId: " + + pool.getId()); + } + if (avoid.shouldAvoid(pool)) { + if (s_logger.isDebugEnabled()) { s_logger.debug("StoragePool is in avoid set, skipping this pool"); - } - return false; - } - - if(dskCh.getType().equals(Type.ROOT) && pool.getPoolType().equals(StoragePoolType.Iscsi)){ - if (s_logger.isDebugEnabled()) { - s_logger.debug("Disk needed for ROOT volume, but StoragePoolType is Iscsi, skipping this and trying other available pools"); - } + } return false; } - + + if (dskCh.getType().equals(Type.ROOT) && pool.getPoolType().equals(StoragePoolType.Iscsi)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Disk needed for ROOT volume, but StoragePoolType is Iscsi, skipping this and trying other available pools"); + } + return false; + } + DiskOfferingVO diskOffering = _diskOfferingDao.findById(dskCh.getDiskOfferingId()); if (diskOffering.getSystemUse() && pool.getPoolType() == StoragePoolType.RBD) { - s_logger.debug("Skipping RBD pool " + pool.getName() + " as a suitable pool. RBD is not supported for System VM's"); + s_logger.debug("Skipping RBD pool " + pool.getName() + + " as a suitable pool. RBD is not supported for System VM's"); return false; } - - Long clusterId = pool.getClusterId(); - ClusterVO cluster = _clusterDao.findById(clusterId); - if (!(cluster.getHypervisorType() == dskCh.getHypervisorType())) { - if (s_logger.isDebugEnabled()) { + Long clusterId = pool.getClusterId(); + ClusterVO cluster = _clusterDao.findById(clusterId); + if (!(cluster.getHypervisorType() == dskCh.getHypervisorType())) { + if (s_logger.isDebugEnabled()) { s_logger.debug("StoragePool's Cluster does not have required hypervisorType, skipping this pool"); } - return false; - } + return false; + } - // check capacity - Volume volume = _volumeDao.findById(dskCh.getVolumeId()); + // check capacity + Volume volume = _volumeDao.findById(dskCh.getVolumeId()); List requestVolumes = new ArrayList(); requestVolumes.add(volume); return storageMgr.storagePoolHasEnoughSpace(requestVolumes, pool); - } + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java index 5b1f8cd699a..0933adcd3bc 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java @@ -40,7 +40,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Component -@Local(value=StoragePoolAllocator.class) +@Local(value = StoragePoolAllocator.class) public class ClusterScopeStoragePoolAllocator extends AbstractStoragePoolAllocator { private static final Logger s_logger = Logger.getLogger(ClusterScopeStoragePoolAllocator.class); protected String _allocationAlgorithm = "random"; @@ -49,19 +49,21 @@ public class ClusterScopeStoragePoolAllocator extends AbstractStoragePoolAllocat DiskOfferingDao _diskOfferingDao; @Override - protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, + DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { s_logger.debug("ClusterScopeStoragePoolAllocator looking for storage pool"); - List suitablePools = new ArrayList(); + List suitablePools = new ArrayList(); - long dcId = plan.getDataCenterId(); - Long podId = plan.getPodId(); - Long clusterId = plan.getClusterId(); + long dcId = plan.getDataCenterId(); + Long podId = plan.getPodId(); + Long clusterId = plan.getClusterId(); - if(dskCh.getTags() != null && dskCh.getTags().length != 0){ - s_logger.debug("Looking for pools in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId + " having tags:" + Arrays.toString(dskCh.getTags())); - }else{ - s_logger.debug("Looking for pools in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId); + if (dskCh.getTags() != null && dskCh.getTags().length != 0) { + s_logger.debug("Looking for pools in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId + + " having tags:" + Arrays.toString(dskCh.getTags())); + } else { + s_logger.debug("Looking for pools in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId); } List pools = _storagePoolDao.findPoolsByTags(dcId, podId, clusterId, dskCh.getTags()); @@ -75,30 +77,31 @@ public class ClusterScopeStoragePoolAllocator extends AbstractStoragePoolAllocat if (pools.size() == 0) { if (s_logger.isDebugEnabled()) { - String storageType = dskCh.useLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString(); + String storageType = dskCh.useLocalStorage() ? ServiceOffering.StorageType.local.toString() + : ServiceOffering.StorageType.shared.toString(); s_logger.debug("No storage pools available for " + storageType + " volume allocation, returning"); } return suitablePools; } - for (StoragePoolVO pool: pools) { - if(suitablePools.size() == returnUpTo){ - break; - } - StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId()); - if (filter(avoid, pol, dskCh, plan)) { - suitablePools.add(pol); + for (StoragePoolVO pool : pools) { + if (suitablePools.size() == returnUpTo) { + break; + } + StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId()); + if (filter(avoid, pol, dskCh, plan)) { + suitablePools.add(pol); } else { avoid.addPool(pool.getId()); - } + } } if (s_logger.isDebugEnabled()) { - s_logger.debug("FirstFitStoragePoolAllocator returning "+suitablePools.size() +" suitable storage pools"); + s_logger.debug("FirstFitStoragePoolAllocator returning " + suitablePools.size() + " suitable storage pools"); } return suitablePools; - } + } @Override public boolean configure(String name, Map params) throws ConfigurationException { diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java index 02032ee4fbd..979ea73cd23 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java @@ -36,18 +36,21 @@ import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; -@Local(value=StoragePoolAllocator.class) +@Local(value = StoragePoolAllocator.class) public class GarbageCollectingStoragePoolAllocator extends AbstractStoragePoolAllocator { private static final Logger s_logger = Logger.getLogger(GarbageCollectingStoragePoolAllocator.class); StoragePoolAllocator _firstFitStoragePoolAllocator; StoragePoolAllocator _localStoragePoolAllocator; - @Inject StorageManager storageMgr; - @Inject ConfigurationDao _configDao; + @Inject + StorageManager storageMgr; + @Inject + ConfigurationDao _configDao; boolean _storagePoolCleanupEnabled; @Override - public List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + public List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, + DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { s_logger.debug("GarbageCollectingStoragePoolAllocator looking for storage pool"); if (!_storagePoolCleanupEnabled) { s_logger.debug("Storage pool cleanup is not enabled, so GarbageCollectingStoragePoolAllocator is being skipped."); @@ -65,7 +68,8 @@ public class GarbageCollectingStoragePoolAllocator extends AbstractStoragePoolAl } // Try to find a storage pool after cleanup - ExcludeList myAvoids = new ExcludeList(avoid.getDataCentersToAvoid(), avoid.getPodsToAvoid(), avoid.getClustersToAvoid(), avoid.getHostsToAvoid(), avoid.getPoolsToAvoid()); + ExcludeList myAvoids = new ExcludeList(avoid.getDataCentersToAvoid(), avoid.getPodsToAvoid(), + avoid.getClustersToAvoid(), avoid.getHostsToAvoid(), avoid.getPoolsToAvoid()); return allocator.allocateToPool(dskCh, vmProfile, plan, myAvoids, returnUpTo); } @@ -80,7 +84,8 @@ public class GarbageCollectingStoragePoolAllocator extends AbstractStoragePoolAl _localStoragePoolAllocator.configure("GCLocalStoragePoolAllocator", params); String storagePoolCleanupEnabled = _configDao.getValue("storage.pool.cleanup.enabled"); - _storagePoolCleanupEnabled = (storagePoolCleanupEnabled == null) ? true : Boolean.parseBoolean(storagePoolCleanupEnabled); + _storagePoolCleanupEnabled = (storagePoolCleanupEnabled == null) ? true : Boolean + .parseBoolean(storagePoolCleanupEnabled); return true; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java index 632ba439cb0..ef9e84eee15 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java @@ -65,7 +65,8 @@ public class LocalStoragePoolAllocator extends AbstractStoragePoolAllocator { ConfigurationDao _configDao; @Override - protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, + DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { List suitablePools = new ArrayList(); @@ -78,13 +79,13 @@ public class LocalStoragePoolAllocator extends AbstractStoragePoolAllocator { // data disk and host identified from deploying vm (attach volume case) if (dskCh.getType() == Volume.Type.DATADISK && plan.getHostId() != null) { List hostPools = _poolHostDao.listByHostId(plan.getHostId()); - for (StoragePoolHostVO hostPool: hostPools) { + for (StoragePoolHostVO hostPool : hostPools) { StoragePoolVO pool = _storagePoolDao.findById(hostPool.getPoolId()); if (pool != null && pool.isLocal()) { - StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId()); - if (filter(avoid, pol, dskCh, plan)) { - s_logger.debug("Found suitable local storage pool " + pool.getId() + ", adding to list"); - suitablePools.add(pol); + StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId()); + if (filter(avoid, pol, dskCh, plan)) { + s_logger.debug("Found suitable local storage pool " + pool.getId() + ", adding to list"); + suitablePools.add(pol); } else { avoid.addPool(pool.getId()); } @@ -95,18 +96,19 @@ public class LocalStoragePoolAllocator extends AbstractStoragePoolAllocator { } } } else { - List availablePools = _storagePoolDao.findLocalStoragePoolsByTags(plan.getDataCenterId(), plan.getPodId(), plan.getClusterId(), dskCh.getTags()); - for (StoragePoolVO pool : availablePools) { - if (suitablePools.size() == returnUpTo) { - break; - } - StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId()); - if (filter(avoid, pol, dskCh, plan)) { - suitablePools.add(pol); + List availablePools = _storagePoolDao.findLocalStoragePoolsByTags(plan.getDataCenterId(), + plan.getPodId(), plan.getClusterId(), dskCh.getTags()); + for (StoragePoolVO pool : availablePools) { + if (suitablePools.size() == returnUpTo) { + break; + } + StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId()); + if (filter(avoid, pol, dskCh, plan)) { + suitablePools.add(pol); } else { avoid.addPool(pool.getId()); } - } + } // add remaining pools in cluster, that did not match tags, to avoid // set diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java index 4663b12e97e..d0571382191 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java @@ -34,22 +34,24 @@ import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; -@Local(value=StoragePoolAllocator.class) +@Local(value = StoragePoolAllocator.class) public class UseLocalForRootAllocator extends LocalStoragePoolAllocator implements StoragePoolAllocator { @Inject DataCenterDao _dcDao; @Override - public List allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + public List allocateToPool(DiskProfile dskCh, + VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, + int returnUpTo) { DataCenterVO dc = _dcDao.findById(plan.getDataCenterId()); if (!dc.isLocalStorageEnabled()) { return null; } - + return super.allocateToPool(dskCh, vmProfile, plan, avoid, returnUpTo); } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java index e9769802a37..8155edfb8cd 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java @@ -38,34 +38,35 @@ import com.cloud.vm.VirtualMachineProfile; @Component public class ZoneWideStoragePoolAllocator extends AbstractStoragePoolAllocator { - private static final Logger s_logger = Logger.getLogger(ZoneWideStoragePoolAllocator.class); - @Inject PrimaryDataStoreDao _storagePoolDao; - @Inject DataStoreManager dataStoreMgr; + private static final Logger s_logger = Logger.getLogger(ZoneWideStoragePoolAllocator.class); + @Inject + PrimaryDataStoreDao _storagePoolDao; + @Inject + DataStoreManager dataStoreMgr; - @Override - protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, - DeploymentPlan plan) { - Volume volume = _volumeDao.findById(dskCh.getVolumeId()); + @Override + protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, DeploymentPlan plan) { + Volume volume = _volumeDao.findById(dskCh.getVolumeId()); List requestVolumes = new ArrayList(); requestVolumes.add(volume); return storageMgr.storagePoolHasEnoughSpace(requestVolumes, pool); - } + } - @Override - protected List select(DiskProfile dskCh, - VirtualMachineProfile vmProfile, - DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { - s_logger.debug("ZoneWideStoragePoolAllocator to find storage pool"); - List suitablePools = new ArrayList(); - HypervisorType hypervisor = dskCh.getHypervisorType(); - if (hypervisor != null) { - if (hypervisor != HypervisorType.KVM) { - s_logger.debug("Only kvm supports zone wide storage"); - return suitablePools; - } - } + @Override + protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, + DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + s_logger.debug("ZoneWideStoragePoolAllocator to find storage pool"); + List suitablePools = new ArrayList(); + HypervisorType hypervisor = dskCh.getHypervisorType(); + if (hypervisor != null) { + if (hypervisor != HypervisorType.KVM) { + s_logger.debug("Only kvm supports zone wide storage"); + return suitablePools; + } + } - List storagePools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), dskCh.getTags()); + List storagePools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), + dskCh.getTags()); // add remaining pools in zone, that did not match tags, to avoid set List allPools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), null); @@ -74,17 +75,17 @@ public class ZoneWideStoragePoolAllocator extends AbstractStoragePoolAllocator { avoid.addPool(pool.getId()); } - for (StoragePoolVO storage : storagePools) { - if (suitablePools.size() == returnUpTo) { - break; - } - StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(storage.getId()); - if (filter(avoid, pol, dskCh, plan)) { - suitablePools.add(pol); + for (StoragePoolVO storage : storagePools) { + if (suitablePools.size() == returnUpTo) { + break; + } + StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(storage.getId()); + if (filter(avoid, pol, dskCh, plan)) { + suitablePools.add(pol); } else { avoid.addPool(pol.getId()); } - } - return suitablePools; - } + } + return suitablePools; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/backup/SnapshotOnBackupStoreInfo.java b/engine/storage/src/org/apache/cloudstack/storage/backup/SnapshotOnBackupStoreInfo.java index 5f5ce2f4a92..36da9665bcc 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/backup/SnapshotOnBackupStoreInfo.java +++ b/engine/storage/src/org/apache/cloudstack/storage/backup/SnapshotOnBackupStoreInfo.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.storage.backup; import org.apache.cloudstack.storage.backup.datastore.BackupStoreInfo; public interface SnapshotOnBackupStoreInfo { - public String getName(); - public BackupStoreInfo getBackupStore(); + public String getName(); + + public BackupStoreInfo getBackupStore(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/backup/datastore/BackupStoreInfo.java b/engine/storage/src/org/apache/cloudstack/storage/backup/datastore/BackupStoreInfo.java index ca1454af570..fc41d4739c1 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/backup/datastore/BackupStoreInfo.java +++ b/engine/storage/src/org/apache/cloudstack/storage/backup/datastore/BackupStoreInfo.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.storage.backup.datastore; import org.apache.cloudstack.storage.backup.SnapshotOnBackupStoreInfo; public interface BackupStoreInfo { - public SnapshotOnBackupStoreInfo getSnapshot(long snapshotId); - public boolean deleteSnapshot(SnapshotOnBackupStoreInfo snapshot); + public SnapshotOnBackupStoreInfo getSnapshot(long snapshotId); + + public boolean deleteSnapshot(SnapshotOnBackupStoreInfo snapshot); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManager.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManager.java index 177dc3e89e7..ef215284ddd 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManager.java @@ -25,13 +25,18 @@ import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.storage.command.CommandResult; public interface DataObjectManager { - public void createAsync(DataObject data, DataStore store, AsyncCompletionCallback callback, boolean noCopy); + public void createAsync(DataObject data, DataStore store, AsyncCompletionCallback callback, + boolean noCopy); + /* - * Only create internal state, without actually send down create command. + * Only create internal state, without actually send down create command. * It's up to device driver decides whether to create object before copying */ public DataObject createInternalStateOnly(DataObject data, DataStore store); + public void update(DataObject data, String path, Long size); + public void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback); + public void deleteAsync(DataObject data, AsyncCompletionCallback callback); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManagerImpl.java index bcd327faae9..6e97e6f9f74 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataObjectManagerImpl.java @@ -40,17 +40,15 @@ import com.cloud.utils.fsm.NoTransitionException; @Component public class DataObjectManagerImpl implements DataObjectManager { - private static final Logger s_logger = Logger - .getLogger(DataObjectManagerImpl.class); + private static final Logger s_logger = Logger.getLogger(DataObjectManagerImpl.class); @Inject ObjectInDataStoreManager objectInDataStoreMgr; @Inject DataMotionService motionSrv; protected long waitingTime = 1800; // half an hour protected long waitingRetries = 10; - - protected DataObject waitingForCreated(DataObject dataObj, - DataStore dataStore) { + + protected DataObject waitingForCreated(DataObject dataObj, DataStore dataStore) { long retries = this.waitingRetries; DataObjectInStore obj = null; do { @@ -61,8 +59,7 @@ public class DataObjectManagerImpl implements DataObjectManager { throw new CloudRuntimeException("sleep interrupted", e); } - obj = objectInDataStoreMgr.findObject(dataObj, - dataStore); + obj = objectInDataStoreMgr.findObject(dataObj, dataStore); if (obj == null) { s_logger.debug("can't find object in db, maybe it's cleaned up already, exit waiting"); break; @@ -75,40 +72,35 @@ public class DataObjectManagerImpl implements DataObjectManager { if (obj == null || retries <= 0) { s_logger.debug("waiting too long for template downloading, marked it as failed"); - throw new CloudRuntimeException( - "waiting too long for template downloading, marked it as failed"); + throw new CloudRuntimeException("waiting too long for template downloading, marked it as failed"); } return objectInDataStoreMgr.get(dataObj, dataStore); } + class CreateContext extends AsyncRpcConext { final DataObject objInStrore; - public CreateContext(AsyncCompletionCallback callback, - DataObject objInStore) { + public CreateContext(AsyncCompletionCallback callback, DataObject objInStore) { super(callback); - this.objInStrore = objInStore; + this.objInStrore = objInStore; } } - + @Override - public void createAsync(DataObject data, DataStore store, - AsyncCompletionCallback callback, boolean noCopy) { - DataObjectInStore obj = objectInDataStoreMgr.findObject( - data, store); + public void createAsync(DataObject data, DataStore store, AsyncCompletionCallback callback, + boolean noCopy) { + DataObjectInStore obj = objectInDataStoreMgr.findObject(data, store); DataObject objInStore = null; boolean freshNewTemplate = false; if (obj == null) { try { - objInStore = objectInDataStoreMgr.create( - data, store); + objInStore = objectInDataStoreMgr.create(data, store); freshNewTemplate = true; } catch (Throwable e) { - obj = objectInDataStoreMgr.findObject(data, - store); + obj = objectInDataStoreMgr.findObject(data, store); if (obj == null) { - CreateCmdResult result = new CreateCmdResult( - null, null); + CreateCmdResult result = new CreateCmdResult(null, null); result.setSuccess(false); result.setResult(e.toString()); callback.complete(result); @@ -117,11 +109,9 @@ public class DataObjectManagerImpl implements DataObjectManager { } } - if (!freshNewTemplate - && obj.getState() != ObjectInDataStoreStateMachine.State.Ready) { + if (!freshNewTemplate && obj.getState() != ObjectInDataStoreStateMachine.State.Ready) { try { - objInStore = waitingForCreated( - data, store); + objInStore = waitingForCreated(data, store); } catch (Exception e) { CreateCmdResult result = new CreateCmdResult(null, null); result.setSuccess(false); @@ -130,8 +120,7 @@ public class DataObjectManagerImpl implements DataObjectManager { return; } - CreateCmdResult result = new CreateCmdResult( - null, null); + CreateCmdResult result = new CreateCmdResult(null, null); callback.complete(result); return; } @@ -143,12 +132,10 @@ public class DataObjectManagerImpl implements DataObjectManager { } else { event = ObjectInDataStoreStateMachine.Event.CreateRequested; } - objectInDataStoreMgr.update(objInStore, - event); + objectInDataStoreMgr.update(objInStore, event); } catch (NoTransitionException e) { try { - objectInDataStoreMgr.update(objInStore, - ObjectInDataStoreStateMachine.Event.OperationFailed); + objectInDataStoreMgr.update(objInStore, ObjectInDataStoreStateMachine.Event.OperationFailed); } catch (NoTransitionException e1) { s_logger.debug("state transation failed", e1); } @@ -159,24 +146,19 @@ public class DataObjectManagerImpl implements DataObjectManager { return; } - CreateContext context = new CreateContext( - callback, objInStore); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().createAsynCallback(null, null)) - .setContext(context); + CreateContext context = new CreateContext(callback, objInStore); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().createAsynCallback(null, null)).setContext(context); store.getDriver().createAsync(objInStore, caller); return; } - + protected Void createAsynCallback(AsyncCallbackDispatcher callback, CreateContext context) { CreateCmdResult result = callback.getResult(); DataObject objInStrore = context.objInStrore; - CreateCmdResult upResult = new CreateCmdResult( - null, null); + CreateCmdResult upResult = new CreateCmdResult(null, null); if (result.isFailed()) { upResult.setResult(result.getResult()); context.getParentCallback().complete(upResult); @@ -184,12 +166,10 @@ public class DataObjectManagerImpl implements DataObjectManager { } try { - objectInDataStoreMgr.update(objInStrore, - ObjectInDataStoreStateMachine.Event.OperationSuccessed); + objectInDataStoreMgr.update(objInStrore, ObjectInDataStoreStateMachine.Event.OperationSuccessed); } catch (NoTransitionException e) { try { - objectInDataStoreMgr.update(objInStrore, - ObjectInDataStoreStateMachine.Event.OperationFailed); + objectInDataStoreMgr.update(objInStrore, ObjectInDataStoreStateMachine.Event.OperationFailed); } catch (NoTransitionException e1) { s_logger.debug("failed to change state", e1); } @@ -198,18 +178,16 @@ public class DataObjectManagerImpl implements DataObjectManager { context.getParentCallback().complete(upResult); return null; } - + context.getParentCallback().complete(result); return null; } - + class CopyContext extends AsyncRpcConext { DataObject destObj; DataObject srcObj; - public CopyContext(AsyncCompletionCallback callback, - DataObject srcObj, - DataObject destObj) { + public CopyContext(AsyncCompletionCallback callback, DataObject srcObj, DataObject destObj) { super(callback); this.srcObj = srcObj; this.destObj = destObj; @@ -217,16 +195,13 @@ public class DataObjectManagerImpl implements DataObjectManager { } @Override - public void copyAsync(DataObject srcData, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback) { try { - objectInDataStoreMgr.update(destData, - ObjectInDataStoreStateMachine.Event.CopyingRequested); + objectInDataStoreMgr.update(destData, ObjectInDataStoreStateMachine.Event.CopyingRequested); } catch (NoTransitionException e) { s_logger.debug("failed to change state", e); try { - objectInDataStoreMgr.update(destData, - ObjectInDataStoreStateMachine.Event.OperationFailed); + objectInDataStoreMgr.update(destData, ObjectInDataStoreStateMachine.Event.OperationFailed); } catch (NoTransitionException e1) { } @@ -235,18 +210,14 @@ public class DataObjectManagerImpl implements DataObjectManager { callback.complete(res); } - CopyContext anotherCall = new CopyContext( - callback, srcData, destData); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback(caller.getTarget().copyCallback(null, null)) - .setContext(anotherCall); + CopyContext anotherCall = new CopyContext(callback, srcData, destData); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().copyCallback(null, null)).setContext(anotherCall); motionSrv.copyAsync(srcData, destData, caller); } - - protected Void copyCallback( - AsyncCallbackDispatcher callback, + + protected Void copyCallback(AsyncCallbackDispatcher callback, CopyContext context) { CopyCommandResult result = callback.getResult(); DataObject destObj = context.destObj; @@ -257,66 +228,56 @@ public class DataObjectManagerImpl implements DataObjectManager { } catch (NoTransitionException e) { s_logger.debug("Failed to update copying state", e); } - CreateCmdResult res = new CreateCmdResult( - null, null); + CreateCmdResult res = new CreateCmdResult(null, null); res.setResult(result.getResult()); context.getParentCallback().complete(res); } try { - objectInDataStoreMgr.update(destObj, - ObjectInDataStoreStateMachine.Event.OperationSuccessed); + objectInDataStoreMgr.update(destObj, ObjectInDataStoreStateMachine.Event.OperationSuccessed); } catch (NoTransitionException e) { s_logger.debug("Failed to update copying state: ", e); try { - objectInDataStoreMgr.update(destObj, - ObjectInDataStoreStateMachine.Event.OperationFailed); + objectInDataStoreMgr.update(destObj, ObjectInDataStoreStateMachine.Event.OperationFailed); } catch (NoTransitionException e1) { } - CreateCmdResult res = new CreateCmdResult( - null, null); + CreateCmdResult res = new CreateCmdResult(null, null); res.setResult("Failed to update copying state: " + e.toString()); context.getParentCallback().complete(res); } - CreateCmdResult res = new CreateCmdResult( - result.getPath(), null); + CreateCmdResult res = new CreateCmdResult(result.getPath(), null); context.getParentCallback().complete(res); return null; } - - class DeleteContext extends AsyncRpcConext { + class DeleteContext extends AsyncRpcConext { private final DataObject obj; + public DeleteContext(AsyncCompletionCallback callback, DataObject obj) { super(callback); this.obj = obj; } - + } + @Override - public void deleteAsync(DataObject data, - AsyncCompletionCallback callback) { + public void deleteAsync(DataObject data, AsyncCompletionCallback callback) { try { objectInDataStoreMgr.update(data, Event.DestroyRequested); } catch (NoTransitionException e) { s_logger.debug("destroy failed", e); - CreateCmdResult res = new CreateCmdResult( - null, null); + CreateCmdResult res = new CreateCmdResult(null, null); callback.complete(res); } - - DeleteContext context = new DeleteContext( - callback, data); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().deleteAsynCallback(null, null)) - .setContext(context); + + DeleteContext context = new DeleteContext(callback, data); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().deleteAsynCallback(null, null)).setContext(context); data.getDataStore().getDriver().deleteAsync(data, caller); return; } - + protected Void deleteAsynCallback(AsyncCallbackDispatcher callback, DeleteContext context) { DataObject destObj = context.obj; @@ -326,47 +287,44 @@ public class DataObjectManagerImpl implements DataObjectManager { try { objectInDataStoreMgr.update(destObj, Event.OperationFailed); } catch (NoTransitionException e) { - s_logger.debug("delete failed", e); + s_logger.debug("delete failed", e); } - + } else { try { objectInDataStoreMgr.update(destObj, Event.OperationSuccessed); } catch (NoTransitionException e) { - s_logger.debug("delete failed", e); + s_logger.debug("delete failed", e); } } - + context.getParentCallback().complete(res); return null; } @Override public DataObject createInternalStateOnly(DataObject data, DataStore store) { - DataObjectInStore obj = objectInDataStoreMgr.findObject( - data, store); + DataObjectInStore obj = objectInDataStoreMgr.findObject(data, store); DataObject objInStore = null; if (obj == null) { - objInStore = objectInDataStoreMgr.create( - data, store); + objInStore = objectInDataStoreMgr.create(data, store); } try { ObjectInDataStoreStateMachine.Event event = null; event = ObjectInDataStoreStateMachine.Event.CreateRequested; - objectInDataStoreMgr.update(objInStore, - event); - + objectInDataStoreMgr.update(objInStore, event); + objectInDataStoreMgr.update(objInStore, ObjectInDataStoreStateMachine.Event.OperationSuccessed); } catch (NoTransitionException e) { s_logger.debug("Failed to update state", e); throw new CloudRuntimeException("Failed to update state", e); } - + return objInStore; } @Override public void update(DataObject data, String path, Long size) { - throw new CloudRuntimeException("not implemented"); + throw new CloudRuntimeException("not implemented"); } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java index 0fdad7ce9f0..7120da175d0 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java @@ -53,11 +53,12 @@ public class DataStoreManagerImpl implements DataStoreManager { } throw new CloudRuntimeException("un recognized type" + role); } + @Override - public DataStore registerDataStore(Map params, - String providerUuid) { + public DataStore registerDataStore(Map params, String providerUuid) { return null; } + @Override public DataStore getDataStore(String uuid, DataStoreRole role) { if (role == DataStoreRole.Primary) { @@ -68,15 +69,11 @@ public class DataStoreManagerImpl implements DataStoreManager { throw new CloudRuntimeException("un recognized type" + role); } - - @Override public List getImageStoresByScope(ZoneScope scope) { return imageDataStoreMgr.listImageStoresByScope(scope); } - - @Override public DataStore getImageStore(long zoneId) { List stores = getImageStoresByScope(new ZoneScope(zoneId)); @@ -96,14 +93,15 @@ public class DataStoreManagerImpl implements DataStoreManager { public DataStore getPrimaryDataStore(long storeId) { return primaryStorMgr.getPrimaryDataStore(storeId); } + @Override public List getImageCacheStores(Scope scope) { - return imageDataStoreMgr.listImageCacheStores(scope); + return imageDataStoreMgr.listImageCacheStores(scope); } + @Override public List listImageStores() { return imageDataStoreMgr.listImageStores(); } - } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManager.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManager.java index f49929f2421..b72d07b2d88 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManager.java @@ -27,11 +27,16 @@ import com.cloud.utils.fsm.NoTransitionException; public interface ObjectInDataStoreManager { public DataObject create(DataObject dataObj, DataStore dataStore); + public boolean delete(DataObject dataObj); + public DataObject get(DataObject dataObj, DataStore store); + public boolean update(DataObject vo, Event event) throws NoTransitionException; - DataObjectInStore findObject(long objId, DataObjectType type, - long dataStoreId, DataStoreRole role); + + DataObjectInStore findObject(long objId, DataObjectType type, long dataStoreId, DataStoreRole role); + DataObjectInStore findObject(DataObject obj, DataStore store); - DataStore findStore(long objId, DataObjectType type, DataStoreRole role); + + DataStore findStore(long objId, DataObjectType type, DataStoreRole role); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java index daeaf7cfd0a..4b3d4a622d5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java @@ -23,14 +23,12 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; @@ -39,7 +37,6 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.db.ObjectInDataStoreDao; -import org.apache.cloudstack.storage.db.ObjectInDataStoreVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -52,17 +49,13 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.template.TemplateConstants; -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; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; @Component public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { - private static final Logger s_logger = Logger - .getLogger(ObjectInDataStoreManagerImpl.class); + private static final Logger s_logger = Logger.getLogger(ObjectInDataStoreManagerImpl.class); @Inject TemplateDataFactory imageFactory; @Inject @@ -91,35 +84,25 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { public ObjectInDataStoreManagerImpl() { stateMachines = new StateMachine2(); - stateMachines.addTransition(State.Allocated, Event.CreateOnlyRequested, - State.Creating); - stateMachines.addTransition(State.Creating, Event.OperationFailed, - State.Allocated); - stateMachines.addTransition(State.Creating, Event.OperationSuccessed, - State.Ready); - stateMachines.addTransition(State.Ready, Event.CopyingRequested, - State.Copying); - stateMachines.addTransition(State.Copying, Event.OperationSuccessed, - State.Ready); - stateMachines.addTransition(State.Copying, Event.OperationFailed, - State.Ready); - stateMachines.addTransition(State.Ready, Event.DestroyRequested, - State.Destroying); - stateMachines.addTransition(State.Destroying, Event.DestroyRequested, - State.Destroying); - stateMachines.addTransition(State.Destroying, Event.OperationSuccessed, - State.Destroyed); - stateMachines.addTransition(State.Destroying, Event.OperationFailed, - State.Destroying); - //TODO: further investigate why an extra event is sent when it is alreay Ready for DownloadListener - stateMachines.addTransition(State.Ready, Event.OperationSuccessed, - State.Ready); + stateMachines.addTransition(State.Allocated, Event.CreateOnlyRequested, State.Creating); + stateMachines.addTransition(State.Creating, Event.OperationFailed, State.Allocated); + stateMachines.addTransition(State.Creating, Event.OperationSuccessed, State.Ready); + stateMachines.addTransition(State.Ready, Event.CopyingRequested, State.Copying); + stateMachines.addTransition(State.Copying, Event.OperationSuccessed, State.Ready); + stateMachines.addTransition(State.Copying, Event.OperationFailed, State.Ready); + stateMachines.addTransition(State.Ready, Event.DestroyRequested, State.Destroying); + stateMachines.addTransition(State.Destroying, Event.DestroyRequested, State.Destroying); + stateMachines.addTransition(State.Destroying, Event.OperationSuccessed, State.Destroyed); + stateMachines.addTransition(State.Destroying, Event.OperationFailed, State.Destroying); + // TODO: further investigate why an extra event is sent when it is + // alreay Ready for DownloadListener + stateMachines.addTransition(State.Ready, Event.OperationSuccessed, State.Ready); } @Override public DataObject create(DataObject obj, DataStore dataStore) { if (dataStore.getRole() == DataStoreRole.Primary) { - if ( obj.getType() == DataObjectType.TEMPLATE){ + if (obj.getType() == DataObjectType.TEMPLATE) { VMTemplateStoragePoolVO vo = new VMTemplateStoragePoolVO(dataStore.getId(), obj.getId()); vo = templatePoolDao.persist(vo); } else if (obj.getType() == DataObjectType.SNAPSHOT) { @@ -132,29 +115,40 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { } } else { // Image store - switch ( obj.getType()){ + switch (obj.getType()) { case TEMPLATE: TemplateDataStoreVO ts = new TemplateDataStoreVO(); ts.setTemplateId(obj.getId()); ts.setDataStoreId(dataStore.getId()); ts.setDataStoreRole(dataStore.getRole()); - String installPath = TemplateConstants.DEFAULT_TMPLT_ROOT_DIR + "/" + TemplateConstants.DEFAULT_TMPLT_FIRST_LEVEL_DIR + templateDao.findById(obj.getId()).getAccountId() + "/" + obj.getId(); - if ( dataStore.getTO() instanceof S3TO ){ - TemplateInfo tmpl = (TemplateInfo)obj; - installPath += "/" + tmpl.getUniqueName(); // for S3, we append template name in the path for template sync since we don't have template.properties there + String installPath = TemplateConstants.DEFAULT_TMPLT_ROOT_DIR + "/" + + TemplateConstants.DEFAULT_TMPLT_FIRST_LEVEL_DIR + + templateDao.findById(obj.getId()).getAccountId() + "/" + obj.getId(); + if (dataStore.getTO() instanceof S3TO) { + TemplateInfo tmpl = (TemplateInfo) obj; + installPath += "/" + tmpl.getUniqueName(); // for S3, we + // append + // template name + // in the path + // for template + // sync since we + // don't have + // template.properties + // there } ts.setInstallPath(installPath); ts.setState(ObjectInDataStoreStateMachine.State.Allocated); ts = templateDataStoreDao.persist(ts); break; case SNAPSHOT: - SnapshotInfo snapshot = (SnapshotInfo)obj; + SnapshotInfo snapshot = (SnapshotInfo) obj; SnapshotDataStoreVO ss = new SnapshotDataStoreVO(); ss.setSnapshotId(obj.getId()); ss.setDataStoreId(dataStore.getId()); ss.setRole(dataStore.getRole()); ss.setRole(dataStore.getRole()); - ss.setInstallPath(TemplateConstants.DEFAULT_SNAPSHOT_ROOT_DIR + "/" + snapshotDao.findById(obj.getId()).getAccountId() + "/" + snapshot.getVolumeId()); + ss.setInstallPath(TemplateConstants.DEFAULT_SNAPSHOT_ROOT_DIR + "/" + + snapshotDao.findById(obj.getId()).getAccountId() + "/" + snapshot.getVolumeId()); ss.setState(ObjectInDataStoreStateMachine.State.Allocated); ss = snapshotDataStoreDao.persist(ss); break; @@ -162,59 +156,61 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { VolumeDataStoreVO vs = new VolumeDataStoreVO(); vs.setVolumeId(obj.getId()); vs.setDataStoreId(dataStore.getId()); - vs.setInstallPath(TemplateConstants.DEFAULT_VOLUME_ROOT_DIR + "/" + volumeDao.findById(obj.getId()).getAccountId() + "/" + obj.getId()); + vs.setInstallPath(TemplateConstants.DEFAULT_VOLUME_ROOT_DIR + "/" + + volumeDao.findById(obj.getId()).getAccountId() + "/" + obj.getId()); vs.setState(ObjectInDataStoreStateMachine.State.Allocated); vs = volumeDataStoreDao.persist(vs); break; } } - return this.get(obj, dataStore); + return this.get(obj, dataStore); } - @Override public boolean delete(DataObject dataObj) { long objId = dataObj.getId(); DataStore dataStore = dataObj.getDataStore(); if (dataStore.getRole() == DataStoreRole.Primary) { - if ( dataObj.getType() == DataObjectType.TEMPLATE){ + if (dataObj.getType() == DataObjectType.TEMPLATE) { VMTemplateStoragePoolVO destTmpltPool = templatePoolDao.findByPoolTemplate(dataStore.getId(), objId); - if ( destTmpltPool != null ){ + if (destTmpltPool != null) { return templatePoolDao.remove(destTmpltPool.getId()); } else { - s_logger.warn("Template " + objId + " is not found on storage pool " + dataStore.getId() + ", so no need to delete"); + s_logger.warn("Template " + objId + " is not found on storage pool " + dataStore.getId() + + ", so no need to delete"); return true; } } } else { // Image store - switch ( dataObj.getType()){ + switch (dataObj.getType()) { case TEMPLATE: TemplateDataStoreVO destTmpltStore = templateDataStoreDao.findByStoreTemplate(dataStore.getId(), objId); - if ( destTmpltStore != null ){ + if (destTmpltStore != null) { return templateDataStoreDao.remove(destTmpltStore.getId()); - } - else{ - s_logger.warn("Template " + objId + " is not found on image store " + dataStore.getId() + ", so no need to delete"); + } else { + s_logger.warn("Template " + objId + " is not found on image store " + dataStore.getId() + + ", so no need to delete"); return true; } case SNAPSHOT: - SnapshotDataStoreVO destSnapshotStore = snapshotDataStoreDao.findByStoreSnapshot(dataStore.getRole(), dataStore.getId(), objId); - if ( destSnapshotStore != null ){ + SnapshotDataStoreVO destSnapshotStore = snapshotDataStoreDao.findByStoreSnapshot(dataStore.getRole(), + dataStore.getId(), objId); + if (destSnapshotStore != null) { return snapshotDataStoreDao.remove(destSnapshotStore.getId()); - } - else{ - s_logger.warn("Snapshot " + objId + " is not found on image store " + dataStore.getId() + ", so no need to delete"); + } else { + s_logger.warn("Snapshot " + objId + " is not found on image store " + dataStore.getId() + + ", so no need to delete"); return true; } case VOLUME: VolumeDataStoreVO destVolumeStore = volumeDataStoreDao.findByStoreVolume(dataStore.getId(), objId); - if ( destVolumeStore != null ){ + if (destVolumeStore != null) { return volumeDataStoreDao.remove(destVolumeStore.getId()); - } - else{ - s_logger.warn("Volume " + objId + " is not found on image store " + dataStore.getId() + ", so no need to delete"); + } else { + s_logger.warn("Volume " + objId + " is not found on image store " + dataStore.getId() + + ", so no need to delete"); return true; } } @@ -225,17 +221,15 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { } @Override - public boolean update(DataObject data, Event event) - throws NoTransitionException { + public boolean update(DataObject data, Event event) throws NoTransitionException { DataObjectInStore obj = this.findObject(data, data.getDataStore()); if (obj == null) { - throw new CloudRuntimeException( - "can't find mapping in ObjectInDataStore table for: " - + data); + throw new CloudRuntimeException("can't find mapping in ObjectInDataStore table for: " + data); } - if ( data.getDataStore().getRole() == DataStoreRole.Image || data.getDataStore().getRole() == DataStoreRole.ImageCache){ - switch (data.getType()){ + if (data.getDataStore().getRole() == DataStoreRole.Image + || data.getDataStore().getRole() == DataStoreRole.ImageCache) { + switch (data.getType()) { case TEMPLATE: this.stateMachines.transitTo(obj, event, null, templateDataStoreDao); break; @@ -248,13 +242,13 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { } } else if (data.getType() == DataObjectType.TEMPLATE && data.getDataStore().getRole() == DataStoreRole.Primary) { - this.stateMachines.transitTo(obj, event, null, - templatePoolDao); + this.stateMachines.transitTo(obj, event, null, templatePoolDao); } else if (data.getType() == DataObjectType.SNAPSHOT && data.getDataStore().getRole() == DataStoreRole.Primary) { this.stateMachines.transitTo(obj, event, null, snapshotDataStoreDao); } else { - throw new CloudRuntimeException("Invalid data or store type: " + data.getType() + " " + data.getDataStore().getRole()); + throw new CloudRuntimeException("Invalid data or store type: " + data.getType() + " " + + data.getDataStore().getRole()); } return true; } @@ -277,13 +271,11 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { return findObject(obj.getId(), obj.getType(), store.getId(), store.getRole()); } - @Override - public DataObjectInStore findObject(long objId, DataObjectType type, - long dataStoreId, DataStoreRole role) { + public DataObjectInStore findObject(long objId, DataObjectType type, long dataStoreId, DataStoreRole role) { DataObjectInStore vo = null; if (role == DataStoreRole.Image || role == DataStoreRole.ImageCache) { - switch (type){ + switch (type) { case TEMPLATE: vo = templateDataStoreDao.findByStoreTemplate(dataStoreId, objId); break; @@ -308,11 +300,11 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { } @Override - public DataStore findStore(long objId, DataObjectType type, DataStoreRole role) { + public DataStore findStore(long objId, DataObjectType type, DataStoreRole role) { DataStore store = null; if (role == DataStoreRole.Image) { DataObjectInStore vo = null; - switch (type){ + switch (type) { case TEMPLATE: vo = templateDataStoreDao.findByTemplate(objId, role); break; diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java index fdaaace49d7..d8b2a734792 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java @@ -36,9 +36,8 @@ public interface PrimaryDataStore extends DataStore, PrimaryDataStoreInfo { boolean exists(DataObject data); TemplateInfo getTemplate(long templateId); - - SnapshotInfo getSnapshot(long snapshotId); + SnapshotInfo getSnapshot(long snapshotId); DiskFormat getDefaultDiskType(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreEntityImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreEntityImpl.java index 2dc3e255b38..f62adfce999 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreEntityImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreEntityImpl.java @@ -31,11 +31,11 @@ import com.cloud.storage.StoragePoolStatus; public class PrimaryDataStoreEntityImpl implements StorageEntity { private PrimaryDataStoreInfo dataStore; - + public PrimaryDataStoreEntityImpl(PrimaryDataStoreInfo dataStore) { this.dataStore = dataStore; } - + @Override public boolean enable() { // TODO Auto-generated method stub @@ -72,7 +72,7 @@ public class PrimaryDataStoreEntityImpl implements StorageEntity { @Override public String getCurrentState() { - return null; + return null; } @Override @@ -105,7 +105,6 @@ public class PrimaryDataStoreEntityImpl implements StorageEntity { return null; } - @Override public void addDetail(String name, String value) { // TODO Auto-generated method stub @@ -132,7 +131,7 @@ public class PrimaryDataStoreEntityImpl implements StorageEntity { @Override public State getState() { - //return this.dataStore.getManagedState(); + // return this.dataStore.getManagedState(); return null; } @@ -230,17 +229,16 @@ public class PrimaryDataStoreEntityImpl implements StorageEntity { return null; } - public String getStorageType() { // TODO Auto-generated method stub return null; } - @Override - public void persist() { - // TODO Auto-generated method stub - - } + @Override + public void persist() { + // TODO Auto-generated method stub + + } @Override public boolean isInMaintenance() { diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java index b3ed0aaab68..8613668b180 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreProviderManager.java @@ -21,11 +21,12 @@ package org.apache.cloudstack.storage.datastore; import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; - public interface PrimaryDataStoreProviderManager { public PrimaryDataStore getPrimaryDataStore(long dataStoreId); + public PrimaryDataStore getPrimaryDataStore(String uuid); boolean registerDriver(String providerName, PrimaryDataStoreDriver driver); + boolean registerHostListener(String providerName, HypervisorHostListener listener); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/protocol/DataStoreProtocol.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/protocol/DataStoreProtocol.java index b0a7d50c57d..b27c96edbb7 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/protocol/DataStoreProtocol.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/protocol/DataStoreProtocol.java @@ -17,14 +17,14 @@ package org.apache.cloudstack.storage.datastore.protocol; public enum DataStoreProtocol { - NFS("nfs"), - ISCSI("iscsi"); - + NFS("nfs"), ISCSI("iscsi"); + private String name; + DataStoreProtocol(String name) { this.name = name; } - + @Override public String toString() { return this.name; diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DataStoreProviderManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DataStoreProviderManagerImpl.java index 796afe2d4df..db056e9e4c0 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DataStoreProviderManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DataStoreProviderManagerImpl.java @@ -43,8 +43,7 @@ import com.cloud.utils.component.ManagerBase; @Component public class DataStoreProviderManagerImpl extends ManagerBase implements DataStoreProviderManager { - private static final Logger s_logger = Logger - .getLogger(DataStoreProviderManagerImpl.class); + private static final Logger s_logger = Logger.getLogger(DataStoreProviderManagerImpl.class); @Inject List providers; protected Map providerMap = new HashMap(); @@ -52,6 +51,7 @@ public class DataStoreProviderManagerImpl extends ManagerBase implements DataSto PrimaryDataStoreProviderManager primaryDataStoreProviderMgr; @Inject ImageStoreProviderManager imageDataStoreProviderMgr; + @Override public DataStoreProvider getDataStoreProvider(String name) { return providerMap.get(name); @@ -103,14 +103,14 @@ public class DataStoreProviderManagerImpl extends ManagerBase implements DataSto } @Override - public boolean configure(String name, Map params) - throws ConfigurationException { + public boolean configure(String name, Map params) throws ConfigurationException { Map copyParams = new HashMap(params); for (DataStoreProvider provider : providers) { String providerName = provider.getName(); if (providerMap.get(providerName) != null) { - s_logger.debug("Failed to register data store provider, provider name: " + providerName + " is not unique"); + s_logger.debug("Failed to register data store provider, provider name: " + providerName + + " is not unique"); return false; } @@ -127,13 +127,14 @@ public class DataStoreProviderManagerImpl extends ManagerBase implements DataSto Set types = provider.getTypes(); if (types.contains(DataStoreProviderType.PRIMARY)) { - primaryDataStoreProviderMgr.registerDriver(provider.getName(), (PrimaryDataStoreDriver)provider.getDataStoreDriver()); + primaryDataStoreProviderMgr.registerDriver(provider.getName(), + (PrimaryDataStoreDriver) provider.getDataStoreDriver()); primaryDataStoreProviderMgr.registerHostListener(provider.getName(), provider.getHostListener()); + } else if (types.contains(DataStoreProviderType.IMAGE)) { + imageDataStoreProviderMgr.registerDriver(provider.getName(), + (ImageStoreDriver) provider.getDataStoreDriver()); } - else if (types.contains(DataStoreProviderType.IMAGE)) { - imageDataStoreProviderMgr.registerDriver(provider.getName(), (ImageStoreDriver)provider.getDataStoreDriver()); - } - } catch(Exception e) { + } catch (Exception e) { s_logger.debug("configure provider failed", e); providerMap.remove(providerName); return false; @@ -148,7 +149,6 @@ public class DataStoreProviderManagerImpl extends ManagerBase implements DataSto return this.getDataStoreProvider(DataStoreProvider.DEFAULT_PRIMARY); } - @Override public DataStoreProvider getDefaultImageDataStoreProvider() { return this.getDataStoreProvider(DataStoreProvider.NFS_IMAGE); @@ -169,7 +169,7 @@ public class DataStoreProviderManagerImpl extends ManagerBase implements DataSto } else if (type.equalsIgnoreCase(DataStoreProvider.DataStoreProviderType.IMAGE.toString())) { return this.getImageDataStoreProviders(); } else if (type.equalsIgnoreCase(DataStoreProvider.DataStoreProviderType.ImageCache.toString())) { - return this.getCacheDataStoreProviders(); + return this.getCacheDataStoreProviders(); } else { throw new InvalidParameterValueException("Invalid parameter: " + type); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDao.java b/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDao.java index fb7dec0fa41..37d089d816d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDao.java @@ -22,6 +22,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreState import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface ObjectInDataStoreDao extends GenericDao, StateDao { +public interface ObjectInDataStoreDao extends GenericDao, + StateDao { } diff --git a/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDaoImpl.java index 9965d60b23d..aac1d134e34 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreDaoImpl.java @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.storage.db; + import java.util.Date; import java.util.Map; @@ -36,10 +37,11 @@ import com.cloud.utils.db.UpdateBuilder; public class ObjectInDataStoreDaoImpl extends GenericDaoBase implements ObjectInDataStoreDao { private static final Logger s_logger = Logger.getLogger(ObjectInDataStoreDaoImpl.class); private SearchBuilder updateStateSearch; + @Override public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - + super.configure(name, params); + updateStateSearch = this.createSearchBuilder(); updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ); updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ); @@ -47,14 +49,13 @@ public class ObjectInDataStoreDaoImpl extends GenericDaoBase sc = updateStateSearch.create(); sc.setParameters("id", vo.getId()); sc.setParameters("state", currentState); @@ -66,19 +67,23 @@ public class ObjectInDataStoreDaoImpl extends GenericDaoBase 0; diff --git a/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreVO.java b/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreVO.java index ecf03913c3e..df9c83641f6 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/db/ObjectInDataStoreVO.java @@ -78,13 +78,13 @@ public class ObjectInDataStoreVO implements StateObject listUpAndConnectingSecondaryStorageVmHost(Long dcId) { @@ -223,16 +218,17 @@ public class DefaultEndPointSelector implements EndPointSelector { return select(store); } - @Override public EndPoint select(DataStore store) { if (store.getRole() == DataStoreRole.Primary) { return findEndpointForPrimaryStorage(store); } else if (store.getRole() == DataStoreRole.Image) { - //in case there is no ssvm, directly send down command hypervisor host - // otherwise, send to localhost for bootstrap system vm template download + // in case there is no ssvm, directly send down command hypervisor + // host + // otherwise, send to localhost for bootstrap system vm template + // download return findEndpointForImageStorage(store); - }else { + } else { throw new CloudRuntimeException("not implemented yet"); } } @@ -242,16 +238,16 @@ public class DefaultEndPointSelector implements EndPointSelector { List endPoints = new ArrayList(); if (store.getScope().getScopeType() == ScopeType.HOST) { HostVO host = hostDao.findById(store.getScope().getScopeId()); - endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), - host.getPrivateIpAddress(), host.getPublicIpAddress())); + endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), + host.getPublicIpAddress())); } else if (store.getScope().getScopeType() == ScopeType.CLUSTER) { SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, store.getScope().getScopeId()); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); List hosts = sc.find(); for (HostVO host : hosts) { - endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), - host.getPrivateIpAddress(), host.getPublicIpAddress())); + endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), + host.getPublicIpAddress())); } } else { diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateEntityImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateEntityImpl.java index 51c8c439fc2..a8d94725175 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateEntityImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateEntityImpl.java @@ -39,7 +39,7 @@ public class TemplateEntityImpl implements TemplateEntity { } public ImageStoreInfo getImageDataStore() { - return (ImageStoreInfo)templateInfo.getDataStore(); + return (ImageStoreInfo) templateInfo.getDataStore(); } public long getImageDataStoreId() { @@ -57,7 +57,7 @@ public class TemplateEntityImpl implements TemplateEntity { @Override public long getId() { - return this.templateInfo.getId(); + return this.templateInfo.getId(); } public String getExternalId() { @@ -101,7 +101,6 @@ public class TemplateEntityImpl implements TemplateEntity { return null; } - @Override public void addDetail(String name, String value) { // TODO Auto-generated method stub diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java b/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java index deb702f3571..a2d61f91fbe 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.springframework.stereotype.Component; import com.cloud.storage.DataStoreRole; -import com.cloud.storage.ImageStore; import com.cloud.storage.ScopeType; import com.cloud.utils.exception.CloudRuntimeException; @@ -43,59 +42,59 @@ public class ImageStoreHelper { ImageStoreDetailsDao imageStoreDetailsDao; public ImageStoreVO createImageStore(Map params) { - ImageStoreVO store = imageStoreDao.findByName((String)params.get("name")); + ImageStoreVO store = imageStoreDao.findByName((String) params.get("name")); if (store != null) { return store; } store = new ImageStoreVO(); - store.setProtocol((String)params.get("protocol")); - store.setProviderName((String)params.get("providerName")); - store.setScope((ScopeType)params.get("scope")); - store.setDataCenterId((Long)params.get("zoneId")); - String uuid = (String)params.get("uuid"); + store.setProtocol((String) params.get("protocol")); + store.setProviderName((String) params.get("providerName")); + store.setScope((ScopeType) params.get("scope")); + store.setDataCenterId((Long) params.get("zoneId")); + String uuid = (String) params.get("uuid"); if (uuid != null) { store.setUuid(uuid); } else { store.setUuid(UUID.randomUUID().toString()); } - store.setName((String)params.get("name")); - if ( store.getName() == null ){ + store.setName((String) params.get("name")); + if (store.getName() == null) { store.setName(store.getUuid()); } - store.setUrl((String)params.get("url")); - store.setRole((DataStoreRole)params.get("role")); + store.setUrl((String) params.get("url")); + store.setRole((DataStoreRole) params.get("role")); store = imageStoreDao.persist(store); return store; } public ImageStoreVO createImageStore(Map params, Map details) { - ImageStoreVO store = imageStoreDao.findByName((String)params.get("name")); + ImageStoreVO store = imageStoreDao.findByName((String) params.get("name")); if (store != null) { return store; } store = new ImageStoreVO(); - store.setProtocol((String)params.get("protocol")); - store.setProviderName((String)params.get("providerName")); - store.setScope((ScopeType)params.get("scope")); - store.setDataCenterId((Long)params.get("zoneId")); - String uuid = (String)params.get("uuid"); + store.setProtocol((String) params.get("protocol")); + store.setProviderName((String) params.get("providerName")); + store.setScope((ScopeType) params.get("scope")); + store.setDataCenterId((Long) params.get("zoneId")); + String uuid = (String) params.get("uuid"); if (uuid != null) { store.setUuid(uuid); } else { store.setUuid(UUID.randomUUID().toString()); } - store.setUrl((String)params.get("url")); - store.setName((String)params.get("name")); - if ( store.getName() == null ){ + store.setUrl((String) params.get("url")); + store.setName((String) params.get("name")); + if (store.getName() == null) { store.setName(store.getUuid()); } - store.setRole((DataStoreRole)params.get("role")); + store.setRole((DataStoreRole) params.get("role")); store = imageStoreDao.persist(store); // persist details - if (details != null){ + if (details != null) { Iterator keyIter = details.keySet().iterator(); - while (keyIter.hasNext()){ + while (keyIter.hasNext()) { String key = keyIter.next(); ImageStoreDetailVO detail = new ImageStoreDetailVO(); detail.setStoreId(store.getId()); diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreProviderManager.java b/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreProviderManager.java index f8fa28176a0..be66cc51401 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreProviderManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreProviderManager.java @@ -27,10 +27,16 @@ import org.apache.cloudstack.storage.image.ImageStoreDriver; public interface ImageStoreProviderManager { ImageStoreEntity getImageStore(long dataStoreId); + ImageStoreEntity getImageStore(String uuid); + List listImageStores(); + List listImageStoresByScope(ZoneScope scope); + List listImageStoreByProvider(String provider); + List listImageCacheStores(Scope scope); + boolean registerDriver(String uuid, ImageStoreDriver driver); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDaoImpl.java index 70316b9ee1c..acbbc7d74a8 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDaoImpl.java @@ -23,12 +23,9 @@ import java.util.Map; import javax.naming.ConfigurationException; - -import org.apache.cloudstack.engine.subsystem.api.storage.Scope; import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.storage.DataStoreRole; @@ -39,12 +36,9 @@ import com.cloud.utils.db.SearchCriteria; @Component public class ImageStoreDaoImpl extends GenericDaoBase implements ImageStoreDao { - - private static final Logger s_logger = Logger.getLogger(ImageStoreDaoImpl.class); private SearchBuilder nameSearch; private SearchBuilder providerSearch; - @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); @@ -87,7 +81,8 @@ public class ImageStoreDaoImpl extends GenericDaoBase implem scc.addOr("dcId", SearchCriteria.Op.EQ, scope.getScopeId()); sc.addAnd("scope", SearchCriteria.Op.SC, scc); } - // we should return all image stores if cross-zone scope is passed (scopeId = null) + // we should return all image stores if cross-zone scope is passed + // (scopeId = null) return listBy(sc); } @@ -109,5 +104,4 @@ public class ImageStoreDaoImpl extends GenericDaoBase implem return listBy(sc); } - } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java index 8f711c686de..ad52042bc7c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java @@ -26,14 +26,13 @@ import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao; import org.springframework.stereotype.Component; -import com.cloud.host.DetailVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @Component -@Local(value=ImageStoreDetailsDao.class) +@Local(value = ImageStoreDetailsDao.class) public class ImageStoreDetailsDaoImpl extends GenericDaoBase implements ImageStoreDetailsDao { protected final SearchBuilder storeSearch; @@ -62,16 +61,16 @@ public class ImageStoreDetailsDaoImpl extends GenericDaoBase getDetails(long storeId) { - SearchCriteria sc = storeSearch.create(); - sc.setParameters("store", storeId); + SearchCriteria sc = storeSearch.create(); + sc.setParameters("store", storeId); - List details = listBy(sc); - Map detailsMap = new HashMap(); - for (ImageStoreDetailVO detail : details) { - detailsMap.put(detail.getName(), detail.getValue()); - } + List details = listBy(sc); + Map detailsMap = new HashMap(); + for (ImageStoreDetailVO detail : details) { + detailsMap.put(detail.getName(), detail.getValue()); + } - return detailsMap; + return detailsMap; } @Override @@ -86,5 +85,4 @@ public class ImageStoreDetailsDaoImpl extends GenericDaoBase params) throws ConfigurationException { - super.configure(name, params); + super.configure(name, params); storeSearch = createSearchBuilder(); storeSearch.and("store_id", storeSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ); @@ -85,13 +84,11 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase sc = updateStateSearch.create(); sc.setParameters("id", dataObj.getId()); sc.setParameters("state", currentState); @@ -108,20 +105,23 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase 0; } - @Override public List listByStoreId(long id, DataStoreRole role) { SearchCriteria sc = storeSearch.create(); @@ -157,8 +157,6 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase listDestroyed(long id) { SearchCriteria sc = destroyedSearch.create(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java index a90a2f620e0..362f7a6aa96 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.storage.image.db; + import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -34,7 +35,6 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; - import com.cloud.storage.DataStoreRole; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.utils.db.GenericDaoBase; @@ -57,13 +57,12 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase storeTemplateStateSearch; private SearchBuilder storeTemplateDownloadStatusSearch; - - @Inject private DataStoreManager _storeMgr; + @Inject + private DataStoreManager _storeMgr; @Override public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - + super.configure(name, params); storeSearch = createSearchBuilder(); storeSearch.and("store_id", storeSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ); @@ -81,8 +80,7 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase sc = updateStateSearch.create(); sc.setParameters("id", dataObj.getId()); sc.setParameters("state", currentState); @@ -136,7 +138,7 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase 0; } - @Override public List listByStoreId(long id) { SearchCriteria sc = storeSearch.create(); @@ -209,33 +214,31 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase sc = storeTemplateStateSearch.create(); sc.setParameters("template_id", templateId); sc.setParameters("store_id", storeId); - sc.setParameters("states", (Object[])states); + sc.setParameters("states", (Object[]) states); sc.setParameters("destroyed", false); return search(sc, null); } - - @Override public List listByTemplateStoreDownloadStatus(long templateId, long storeId, Status... status) { SearchCriteria sc = storeTemplateDownloadStatusSearch.create(); sc.setParameters("template_id", templateId); sc.setParameters("store_id", storeId); - sc.setParameters("downloadState", (Object[])status); + sc.setParameters("downloadState", (Object[]) status); sc.setParameters("destroyed", false); return search(sc, null); } - @Override public List listByTemplateZoneDownloadStatus(long templateId, Long zoneId, Status... status) { // get all elgible image stores List imgStores = this._storeMgr.getImageStoresByScope(new ZoneScope(zoneId)); - if ( imgStores != null ){ + if (imgStores != null) { List result = new ArrayList(); - for (DataStore store : imgStores){ - List sRes = this.listByTemplateStoreDownloadStatus(templateId, store.getId(), status); - if ( sRes != null && sRes.size() > 0){ + for (DataStore store : imgStores) { + List sRes = this.listByTemplateStoreDownloadStatus(templateId, store.getId(), + status); + if (sRes != null && sRes.size() > 0) { result.addAll(sRes); } } @@ -244,15 +247,15 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase imgStores = this._storeMgr.getImageStoresByScope(new ZoneScope(zoneId)); - if ( imgStores != null ){ - for (DataStore store : imgStores){ - List sRes = this.listByTemplateStoreDownloadStatus(templateId, store.getId(), status); - if ( sRes != null && sRes.size() > 0){ + if (imgStores != null) { + for (DataStore store : imgStores) { + List sRes = this.listByTemplateStoreDownloadStatus(templateId, store.getId(), + status); + if (sRes != null && sRes.size() > 0) { Collections.shuffle(sRes); return sRes.get(0); } @@ -270,7 +273,6 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase sc = storeTemplateSearch.create(); @@ -283,7 +285,6 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase sc = templateRoleSearch.create(); @@ -305,15 +306,15 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase imgStores = null; - if ( role == DataStoreRole.Image){ + if (role == DataStoreRole.Image) { imgStores = this._storeMgr.getImageStoresByScope(new ZoneScope(zoneId)); - } else if (role == DataStoreRole.ImageCache){ + } else if (role == DataStoreRole.ImageCache) { imgStores = this._storeMgr.getImageCacheStores(new ZoneScope(zoneId)); } - if ( imgStores != null ){ - for (DataStore store : imgStores){ + if (imgStores != null) { + for (DataStore store : imgStores) { List sRes = this.listByTemplateStore(templateId, store.getId()); - if ( sRes != null && sRes.size() > 0){ + if (sRes != null && sRes.size() > 0) { return sRes.get(0); } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/VolumeDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/VolumeDataStoreDaoImpl.java index 96cfc91bb43..56020720914 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/VolumeDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/VolumeDataStoreDaoImpl.java @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.storage.image.db; + import java.util.Date; import java.util.List; import java.util.Map; @@ -24,14 +25,11 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; -import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.storage.VolumeHostVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -49,8 +47,7 @@ public class VolumeDataStoreDaoImpl extends GenericDaoBase params) throws ConfigurationException { - super.configure(name, params); - + super.configure(name, params); storeSearch = createSearchBuilder(); storeSearch.and("store_id", storeSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ); @@ -75,14 +72,13 @@ public class VolumeDataStoreDaoImpl extends GenericDaoBase sc = updateStateSearch.create(); sc.setParameters("id", dataObj.getId()); sc.setParameters("state", currentState); @@ -93,7 +89,7 @@ public class VolumeDataStoreDaoImpl extends GenericDaoBase 0; } - @Override public List listByStoreId(long id) { SearchCriteria sc = storeSearch.create(); @@ -134,7 +133,6 @@ public class VolumeDataStoreDaoImpl extends GenericDaoBase sc = volumeSearch.create(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionService.java b/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionService.java index b37641300ed..b00e95d4d7d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionService.java @@ -21,10 +21,10 @@ package org.apache.cloudstack.storage.image.motion; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.db.ObjectInDataStoreVO; -import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; public interface ImageMotionService { - void copyTemplateAsync(TemplateInfo destTemplate, TemplateInfo srcTemplate, AsyncCompletionCallback callback); + void copyTemplateAsync(TemplateInfo destTemplate, TemplateInfo srcTemplate, + AsyncCompletionCallback callback); + boolean copyIso(String isoUri, String destIsoUri); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotEntityImpl.java b/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotEntityImpl.java index a59e5947a18..fb3ec48d744 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotEntityImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotEntityImpl.java @@ -27,160 +27,160 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; public class SnapshotEntityImpl implements SnapshotEntity { - @Override - public String getUuid() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public long getId() { + // TODO Auto-generated method stub + return 0; + } - @Override - public String getCurrentState() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getCurrentState() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getDesiredState() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getDesiredState() { + // TODO Auto-generated method stub + return null; + } - @Override - public Date getCreatedTime() { - // TODO Auto-generated method stub - return null; - } + @Override + public Date getCreatedTime() { + // TODO Auto-generated method stub + return null; + } - @Override - public Date getLastUpdatedTime() { - // TODO Auto-generated method stub - return null; - } + @Override + public Date getLastUpdatedTime() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getOwner() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getOwner() { + // TODO Auto-generated method stub + return null; + } - @Override - public List getApplicableActions() { - // TODO Auto-generated method stub - return null; - } + @Override + public List getApplicableActions() { + // TODO Auto-generated method stub + return null; + } - @Override - public long getAccountId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public long getAccountId() { + // TODO Auto-generated method stub + return 0; + } - @Override - public long getVolumeId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public long getVolumeId() { + // TODO Auto-generated method stub + return 0; + } - @Override - public String getName() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } - @Override - public Date getCreated() { - // TODO Auto-generated method stub - return null; - } + @Override + public Date getCreated() { + // TODO Auto-generated method stub + return null; + } - @Override - public HypervisorType getHypervisorType() { - // TODO Auto-generated method stub - return null; - } + @Override + public HypervisorType getHypervisorType() { + // TODO Auto-generated method stub + return null; + } - @Override - public boolean isRecursive() { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isRecursive() { + // TODO Auto-generated method stub + return false; + } - @Override - public short getsnapshotType() { - // TODO Auto-generated method stub - return 0; - } + @Override + public short getsnapshotType() { + // TODO Auto-generated method stub + return 0; + } - @Override - public long getDomainId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public long getDomainId() { + // TODO Auto-generated method stub + return 0; + } - @Override - public String reserveForBackup(int expiration) { - // TODO Auto-generated method stub - return null; - } + @Override + public String reserveForBackup(int expiration) { + // TODO Auto-generated method stub + return null; + } - @Override - public void backup(String reservationToken) { - // TODO Auto-generated method stub + @Override + public void backup(String reservationToken) { + // TODO Auto-generated method stub - } + } - @Override - public void restore(String vm) { - // TODO Auto-generated method stub + @Override + public void restore(String vm) { + // TODO Auto-generated method stub - } + } - @Override - public void destroy() { - // TODO Auto-generated method stub + @Override + public void destroy() { + // TODO Auto-generated method stub - } + } - @Override - public Map getDetails() { - // TODO Auto-generated method stub - return null; - } + @Override + public Map getDetails() { + // TODO Auto-generated method stub + return null; + } - @Override - public void addDetail(String name, String value) { - // TODO Auto-generated method stub - - } + @Override + public void addDetail(String name, String value) { + // TODO Auto-generated method stub - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - - } + } - @Override - public void updateDetail(String name, String value) { - // TODO Auto-generated method stub - - } + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub - @Override - public State getState() { - // TODO Auto-generated method stub - return null; - } + } - @Override - public Type getRecurringType() { - // TODO Auto-generated method stub - return null; - } + @Override + public void updateDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public State getState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Type getRecurringType() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java b/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java index d131008d65e..501f0447cb7 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java @@ -27,34 +27,27 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; -import org.apache.cloudstack.storage.command.AttachPrimaryDataStoreCmd; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.alert.AlertManager; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolHostVO; import com.cloud.storage.StoragePoolStatus; import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @Component public class PrimaryDataStoreHelper { - private static final Logger s_logger = Logger - .getLogger(PrimaryDataStoreHelper.class); + private static final Logger s_logger = Logger.getLogger(PrimaryDataStoreHelper.class); @Inject private PrimaryDataStoreDao dataStoreDao; @Inject @@ -65,12 +58,13 @@ public class PrimaryDataStoreHelper { protected CapacityDao _capacityDao; @Inject protected StoragePoolHostDao storagePoolHostDao; + public DataStore createPrimaryDataStore(PrimaryDataStoreParameters params) { StoragePoolVO dataStoreVO = dataStoreDao.findPoolByUUID(params.getUuid()); if (dataStoreVO != null) { throw new CloudRuntimeException("duplicate uuid: " + params.getUuid()); } - + dataStoreVO = new StoragePoolVO(); dataStoreVO.setStorageProviderName(params.getProviderName()); dataStoreVO.setHostAddress(params.getHost()); @@ -84,7 +78,7 @@ public class PrimaryDataStoreHelper { dataStoreVO.setClusterId(params.getClusterId()); dataStoreVO.setStatus(StoragePoolStatus.Initialized); dataStoreVO.setUserInfo(params.getUserInfo()); - + Map details = params.getDetails(); String tags = params.getTags(); if (tags != null) { @@ -98,40 +92,41 @@ public class PrimaryDataStoreHelper { details.put(tag, "true"); } } - + dataStoreVO = dataStoreDao.persist(dataStoreVO, details); return dataStoreMgr.getDataStore(dataStoreVO.getId(), DataStoreRole.Primary); } - + public DataStore attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { StoragePoolHostVO poolHost = storagePoolHostDao.findByPoolHost(store.getId(), scope.getScopeId()); if (poolHost == null) { poolHost = new StoragePoolHostVO(store.getId(), scope.getScopeId(), existingInfo.getLocalPath()); storagePoolHostDao.persist(poolHost); } - + StoragePoolVO pool = this.dataStoreDao.findById(store.getId()); pool.setScope(scope.getScopeType()); pool.setAvailableBytes(existingInfo.getAvailableBytes()); pool.setCapacityBytes(existingInfo.getCapacityBytes()); pool.setStatus(StoragePoolStatus.Up); this.dataStoreDao.update(pool.getId(), pool); - this.storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_LOCAL_STORAGE, pool.getCapacityBytes() - pool.getAvailableBytes()); + this.storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_LOCAL_STORAGE, + pool.getCapacityBytes() - pool.getAvailableBytes()); return dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary); } - + public DataStore attachCluster(DataStore store) { StoragePoolVO pool = this.dataStoreDao.findById(store.getId()); - + storageMgr.createCapacityEntry(pool.getId()); - + pool.setScope(ScopeType.CLUSTER); pool.setStatus(StoragePoolStatus.Up); this.dataStoreDao.update(pool.getId(), pool); return dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary); } - + public DataStore attachZone(DataStore store) { StoragePoolVO pool = this.dataStoreDao.findById(store.getId()); pool.setScope(ScopeType.ZONE); @@ -139,27 +134,24 @@ public class PrimaryDataStoreHelper { this.dataStoreDao.update(pool.getId(), pool); return dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary); } - + public boolean maintain(DataStore store) { StoragePoolVO pool = this.dataStoreDao.findById(store.getId()); pool.setStatus(StoragePoolStatus.Maintenance); this.dataStoreDao.update(pool.getId(), pool); return true; } - + public boolean cancelMaintain(DataStore store) { StoragePoolVO pool = this.dataStoreDao.findById(store.getId()); pool.setStatus(StoragePoolStatus.Up); dataStoreDao.update(store.getId(), pool); return true; } - protected boolean deletePoolStats(Long poolId) { - CapacityVO capacity1 = _capacityDao.findByHostIdType(poolId, - CapacityVO.CAPACITY_TYPE_STORAGE); - CapacityVO capacity2 = _capacityDao.findByHostIdType(poolId, - CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED); + CapacityVO capacity1 = _capacityDao.findByHostIdType(poolId, Capacity.CAPACITY_TYPE_STORAGE); + CapacityVO capacity2 = _capacityDao.findByHostIdType(poolId, Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); if (capacity1 != null) { _capacityDao.remove(capacity1.getId()); } @@ -167,31 +159,27 @@ public class PrimaryDataStoreHelper { if (capacity2 != null) { _capacityDao.remove(capacity2.getId()); } - + return true; } - + public boolean deletePrimaryDataStore(DataStore store) { - List hostPoolRecords = this.storagePoolHostDao - .listByPoolId(store.getId()); + List hostPoolRecords = this.storagePoolHostDao.listByPoolId(store.getId()); StoragePoolVO poolVO = this.dataStoreDao.findById(store.getId()); Transaction txn = Transaction.currentTxn(); txn.start(); for (StoragePoolHostVO host : hostPoolRecords) { - storagePoolHostDao.deleteStoragePoolHostDetails( - host.getHostId(), host.getPoolId()); + storagePoolHostDao.deleteStoragePoolHostDetails(host.getHostId(), host.getPoolId()); } poolVO.setUuid(null); this.dataStoreDao.update(poolVO.getId(), poolVO); dataStoreDao.remove(poolVO.getId()); deletePoolStats(poolVO.getId()); // Delete op_host_capacity entries - this._capacityDao.removeBy(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, - null, null, null, poolVO.getId()); + this._capacityDao.removeBy(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, null, null, null, poolVO.getId()); txn.commit(); - s_logger.debug("Storage pool id=" + poolVO.getId() - + " is removed successfully"); + s_logger.debug("Storage pool id=" + poolVO.getId() + " is removed successfully"); return true; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/PrimaryDataStoreDetailsDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/PrimaryDataStoreDetailsDaoImpl.java index b0a387a0fbb..9d174348c73 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/PrimaryDataStoreDetailsDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/PrimaryDataStoreDetailsDaoImpl.java @@ -30,25 +30,25 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @Component -public class PrimaryDataStoreDetailsDaoImpl extends GenericDaoBase implements PrimaryDataStoreDetailsDao { - +public class PrimaryDataStoreDetailsDaoImpl extends GenericDaoBase implements + PrimaryDataStoreDetailsDao { + protected final SearchBuilder PoolSearch = null; - + protected PrimaryDataStoreDetailsDaoImpl() { /* - super(); - PoolSearch = createSearchBuilder(); - PoolSearch.and("pool", PoolSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - PoolSearch.done(); - */ + * super(); PoolSearch = createSearchBuilder(); PoolSearch.and("pool", + * PoolSearch.entity().getPoolId(), SearchCriteria.Op.EQ); + * PoolSearch.done(); + */ } - + @Override public void update(long poolId, Map details) { Transaction txn = Transaction.currentTxn(); SearchCriteria sc = PoolSearch.create(); sc.setParameters("pool", poolId); - + txn.start(); expunge(sc); for (Map.Entry entry : details.entrySet()) { @@ -57,18 +57,18 @@ public class PrimaryDataStoreDetailsDaoImpl extends GenericDaoBase getDetails(long poolId) { - SearchCriteria sc = PoolSearch.create(); - sc.setParameters("pool", poolId); - - List details = listBy(sc); - Map detailsMap = new HashMap(); - for (PrimaryDataStoreDetailVO detail : details) { - detailsMap.put(detail.getName(), detail.getValue()); - } - - return detailsMap; + SearchCriteria sc = PoolSearch.create(); + sc.setParameters("pool", poolId); + + List details = listBy(sc); + Map detailsMap = new HashMap(); + for (PrimaryDataStoreDetailVO detail : details) { + detailsMap.put(detail.getName(), detail.getValue()); + } + + return detailsMap; } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDao.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDao.java index 63cdb16c596..1827edfe861 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDao.java @@ -23,7 +23,9 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreState import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; -public interface TemplatePrimaryDataStoreDao extends GenericDao, StateDao { +public interface TemplatePrimaryDataStoreDao extends GenericDao, + StateDao { public TemplatePrimaryDataStoreVO findByTemplateIdAndPoolId(long templateId, long poolId); + public TemplatePrimaryDataStoreVO findByTemplateIdAndPoolIdAndReady(long templateId, long poolId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java index ad561502266..7c986403636 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java @@ -35,9 +35,11 @@ import com.cloud.utils.db.SearchCriteriaService; import com.cloud.utils.db.UpdateBuilder; @Component -public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase implements TemplatePrimaryDataStoreDao { +public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase implements + TemplatePrimaryDataStoreDao { private static final Logger s_logger = Logger.getLogger(TemplatePrimaryDataStoreDaoImpl.class); protected final SearchBuilder updateSearchBuilder; + public TemplatePrimaryDataStoreDaoImpl() { updateSearchBuilder = createSearchBuilder(); updateSearchBuilder.and("id", updateSearchBuilder.entity().getId(), Op.EQ); @@ -45,9 +47,11 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = SearchCriteria2.create(TemplatePrimaryDataStoreVO.class); + SearchCriteriaService sc = SearchCriteria2 + .create(TemplatePrimaryDataStoreVO.class); sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); return sc.find(); @@ -55,7 +59,8 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = SearchCriteria2.create(TemplatePrimaryDataStoreVO.class); + SearchCriteriaService sc = SearchCriteria2 + .create(TemplatePrimaryDataStoreVO.class); sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); sc.addAnd(sc.getEntity().getState(), Op.EQ, ObjectInDataStoreStateMachine.State.Ready); @@ -63,34 +68,42 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = updateSearchBuilder.create(); sc.setParameters("id", vo.getId()); sc.setParameters("state", currentState); sc.setParameters("updatedCount", vo.getUpdatedCount()); - + vo.incrUpdatedCount(); - + UpdateBuilder builder = getUpdateBuilder(vo); builder.set(vo, "state", nextState); builder.set(vo, "lastUpdated", new Date()); - - int rows = update((TemplatePrimaryDataStoreVO)vo, sc); + + int rows = update(vo, sc); if (rows == 0 && s_logger.isDebugEnabled()) { - TemplatePrimaryDataStoreVO template = findByIdIncludingRemoved(vo.getId()); + TemplatePrimaryDataStoreVO template = findByIdIncludingRemoved(vo.getId()); if (template != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); - str.append(": DB Data={id=").append(template.getId()).append("; state=").append(template.getState()).append("; updatecount=").append(template.getUpdatedCount()).append(";updatedTime=").append(template.getLastUpdated()); - str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()).append("; updatedTime=").append(vo.getLastUpdated()); - str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated).append("; updatedTime=").append(oldUpdatedTime); + str.append(": DB Data={id=").append(template.getId()).append("; state=").append(template.getState()) + .append("; updatecount=").append(template.getUpdatedCount()).append(";updatedTime=") + .append(template.getLastUpdated()); + str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState) + .append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()) + .append("; updatedTime=").append(vo.getLastUpdated()); + str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState) + .append("; event=").append(event).append("; updatecount=").append(oldUpdated) + .append("; updatedTime=").append(oldUpdatedTime); } else { - s_logger.debug("Unable to update template: id=" + vo.getId() + ", as there is no such template exists in the database anymore"); + s_logger.debug("Unable to update template: id=" + vo.getId() + + ", as there is no such template exists in the database anymore"); } } return rows > 0; } - + } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreVO.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreVO.java index 48a9f334a19..44765ed40a3 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreVO.java @@ -82,22 +82,22 @@ public class TemplatePrimaryDataStoreVO implements StateObject driverMaps; - @Inject StorageManager storageMgr; + @Inject + StorageManager storageMgr; @PostConstruct public void config() { @@ -56,7 +57,8 @@ public class PrimaryDataStoreProviderManagerImpl implements PrimaryDataStoreProv StoragePoolVO dataStoreVO = dataStoreDao.findById(dataStoreId); String providerName = dataStoreVO.getStorageProviderName(); DataStoreProvider provider = providerManager.getDataStoreProvider(providerName); - PrimaryDataStoreImpl dataStore = PrimaryDataStoreImpl.createDataStore(dataStoreVO, driverMaps.get(provider.getName()), provider); + PrimaryDataStoreImpl dataStore = PrimaryDataStoreImpl.createDataStore(dataStoreVO, + driverMaps.get(provider.getName()), provider); return dataStore; } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java index 2c3ab9969a0..6431308ff74 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/datastore/provider/DefaultHostListener.java @@ -38,16 +38,21 @@ import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.utils.exception.CloudRuntimeException; public class DefaultHostListener implements HypervisorHostListener { - private static final Logger s_logger = Logger - .getLogger(DefaultHostListener.class); - @Inject AgentManager agentMgr; - @Inject DataStoreManager dataStoreMgr; - @Inject AlertManager alertMgr; - @Inject StoragePoolHostDao storagePoolHostDao; - @Inject PrimaryDataStoreDao primaryStoreDao; + private static final Logger s_logger = Logger.getLogger(DefaultHostListener.class); + @Inject + AgentManager agentMgr; + @Inject + DataStoreManager dataStoreMgr; + @Inject + AlertManager alertMgr; + @Inject + StoragePoolHostDao storagePoolHostDao; + @Inject + PrimaryDataStoreDao primaryStoreDao; + @Override public boolean hostConnect(long hostId, long poolId) { - StoragePool pool = (StoragePool)this.dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary); + StoragePool pool = (StoragePool) this.dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary); ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool); final Answer answer = agentMgr.easySend(hostId, cmd); @@ -58,20 +63,23 @@ public class DefaultHostListener implements HypervisorHostListener { if (!answer.getResult()) { String msg = "Unable to attach storage pool" + poolId + " to the host" + hostId; alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); - throw new CloudRuntimeException("Unable establish connection from storage head to storage pool " + pool.getId() + " due to " + answer.getDetails() + pool.getId()); + throw new CloudRuntimeException("Unable establish connection from storage head to storage pool " + + pool.getId() + " due to " + answer.getDetails() + pool.getId()); } - assert (answer instanceof ModifyStoragePoolAnswer) : "Well, now why won't you actually return the ModifyStoragePoolAnswer when it's ModifyStoragePoolCommand? Pool=" + pool.getId() + "Host=" + hostId; + assert (answer instanceof ModifyStoragePoolAnswer) : "Well, now why won't you actually return the ModifyStoragePoolAnswer when it's ModifyStoragePoolCommand? Pool=" + + pool.getId() + "Host=" + hostId; ModifyStoragePoolAnswer mspAnswer = (ModifyStoragePoolAnswer) answer; StoragePoolHostVO poolHost = storagePoolHostDao.findByPoolHost(pool.getId(), hostId); if (poolHost == null) { - poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); + poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath() + .replaceAll("//", "/")); storagePoolHostDao.persist(poolHost); } else { poolHost.setLocalPath(mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); } - + StoragePoolVO poolVO = this.primaryStoreDao.findById(poolId); poolVO.setAvailableBytes(mspAnswer.getPoolInfo().getAvailableBytes()); poolVO.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes()); diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategy.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategy.java deleted file mode 100644 index 99b34cbcf18..00000000000 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage.volume; - -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.datastore.PrimaryDataStore; -import org.apache.cloudstack.storage.volume.VolumeServiceImpl.CreateBaseImageResult; - -public interface TemplateInstallStrategy { - public Void installAsync(TemplateInfo template, PrimaryDataStore store, AsyncCompletionCallback callback); -} diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategyImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategyImpl.java deleted file mode 100644 index 42d49df6c13..00000000000 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/TemplateInstallStrategyImpl.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage.volume; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager; -import org.apache.cloudstack.storage.datastore.PrimaryDataStore; -import org.apache.cloudstack.storage.volume.VolumeServiceImpl.CreateBaseImageResult; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - -@Component -public class TemplateInstallStrategyImpl implements TemplateInstallStrategy { - private static final Logger s_logger = Logger - .getLogger(TemplateInstallStrategyImpl.class); - @Inject - ObjectInDataStoreManager objectInDataStoreMgr; - @Inject - DataMotionService motionSrv; - @Inject - TemplateDataFactory imageFactory; - protected long waitingTime = 1800; // half an hour - protected long waitingRetries = 10; -/* - protected TemplateInfo waitingForTemplateDownload(TemplateInfo template, - PrimaryDataStore dataStore) { - long retries = this.waitingRetries; - ObjectInDataStoreVO obj = null; - do { - try { - Thread.sleep(waitingTime); - } catch (InterruptedException e) { - s_logger.debug("sleep interrupted", e); - throw new CloudRuntimeException("sleep interrupted", e); - } - - obj = objectInDataStoreMgr.findObject(template.getId(), - template.getType(), dataStore.getId(), dataStore.getRole()); - if (obj == null) { - s_logger.debug("can't find object in db, maybe it's cleaned up already, exit waiting"); - break; - } - if (obj.getState() == ObjectInDataStoreStateMachine.State.Ready) { - break; - } - retries--; - } while (retries > 0); - - if (obj == null || retries <= 0) { - s_logger.debug("waiting too long for template downloading, marked it as failed"); - throw new CloudRuntimeException( - "waiting too long for template downloading, marked it as failed"); - } - return imageFactory.getTemplate(template.getId(), dataStore); - } - - class InstallContext extends AsyncRpcConext { - final TemplateInfo destTemplate; - final TemplateInfo srcTemplate; - - public InstallContext(AsyncCompletionCallback callback, - TemplateInfo destTemplate, TemplateInfo srcTemplate) { - super(callback); - this.destTemplate = destTemplate; - this.srcTemplate = srcTemplate; - } - - } - - @Override - public Void installAsync(TemplateInfo template, PrimaryDataStore store, - AsyncCompletionCallback callback) { - ObjectInDataStoreVO obj = objectInDataStoreMgr.findObject( - template.getId(), template.getType(), store.getId(), - store.getRole()); - TemplateInfo templateOnPrimaryStoreObj = null; - boolean freshNewTemplate = false; - if (obj == null) { - try { - templateOnPrimaryStoreObj = objectInDataStoreMgr.create( - template, store); - freshNewTemplate = true; - } catch (Throwable e) { - obj = objectInDataStoreMgr.findObject(template.getId(), - template.getType(), store.getId(), store.getRole()); - if (obj == null) { - CreateBaseImageResult result = new CreateBaseImageResult( - null); - result.setSuccess(false); - result.setResult(e.toString()); - callback.complete(result); - return null; - } - } - } - - if (!freshNewTemplate - && obj.getState() != ObjectInDataStoreStateMachine.State.Ready) { - try { - templateOnPrimaryStoreObj = waitingForTemplateDownload( - template, store); - } catch (Exception e) { - CreateBaseImageResult result = new CreateBaseImageResult(null); - result.setSuccess(false); - result.setResult(e.toString()); - callback.complete(result); - return null; - } - - CreateBaseImageResult result = new CreateBaseImageResult( - templateOnPrimaryStoreObj); - callback.complete(result); - return null; - } - - try { - objectInDataStoreMgr.update(templateOnPrimaryStoreObj, - ObjectInDataStoreStateMachine.Event.CreateRequested); - } catch (NoTransitionException e) { - try { - objectInDataStoreMgr.update(templateOnPrimaryStoreObj, - ObjectInDataStoreStateMachine.Event.OperationFailed); - } catch (NoTransitionException e1) { - s_logger.debug("state transation failed", e1); - } - CreateBaseImageResult result = new CreateBaseImageResult(null); - result.setSuccess(false); - result.setResult(e.toString()); - callback.complete(result); - return null; - } - - InstallContext context = new InstallContext( - callback, templateOnPrimaryStoreObj, template); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback( - caller.getTarget().installTemplateCallback(null, null)) - .setContext(context); - - store.getDriver().createAsync(templateOnPrimaryStoreObj, caller); - return null; - } - - class CopyTemplateContext extends AsyncRpcConext { - TemplateInfo template; - - public CopyTemplateContext(AsyncCompletionCallback callback, - TemplateInfo template) { - super(callback); - this.template = template; - } - } - - protected Void installTemplateCallback( - AsyncCallbackDispatcher callback, - InstallContext context) { - CreateCmdResult result = callback.getResult(); - TemplateInfo templateOnPrimaryStoreObj = context.destTemplate; - CreateBaseImageResult upResult = new CreateBaseImageResult( - templateOnPrimaryStoreObj); - if (result.isFailed()) { - upResult.setResult(result.getResult()); - context.getParentCallback().complete(upResult); - return null; - } - - ObjectInDataStoreVO obj = objectInDataStoreMgr.findObject( - templateOnPrimaryStoreObj.getId(), templateOnPrimaryStoreObj - .getType(), templateOnPrimaryStoreObj.getDataStore() - .getId(), templateOnPrimaryStoreObj.getDataStore() - .getRole()); - - obj.setInstallPath(result.getPath()); - obj.setSize(result.getSize()); - try { - objectInDataStoreMgr.update(obj, - ObjectInDataStoreStateMachine.Event.OperationSuccessed); - } catch (NoTransitionException e) { - try { - objectInDataStoreMgr.update(obj, - ObjectInDataStoreStateMachine.Event.OperationFailed); - } catch (NoTransitionException e1) { - s_logger.debug("failed to change state", e1); - } - - upResult.setResult(e.toString()); - context.getParentCallback().complete(upResult); - return null; - } - - moveTemplate(context.srcTemplate, templateOnPrimaryStoreObj, obj, - context.getParentCallback()); - return null; - } - - protected void moveTemplate(TemplateInfo srcTemplate, - TemplateInfo destTemplate, ObjectInDataStoreVO obj, - AsyncCompletionCallback callback) { - // move template into primary storage - try { - objectInDataStoreMgr.update(destTemplate, - ObjectInDataStoreStateMachine.Event.CopyingRequested); - } catch (NoTransitionException e) { - s_logger.debug("failed to change state", e); - try { - objectInDataStoreMgr.update(destTemplate, - ObjectInDataStoreStateMachine.Event.OperationFailed); - } catch (NoTransitionException e1) { - - } - CreateBaseImageResult res = new CreateBaseImageResult(destTemplate); - res.setResult("Failed to change state: " + e.toString()); - callback.complete(res); - } - - CopyTemplateContext anotherCall = new CopyTemplateContext( - callback, destTemplate); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher - .create(this); - caller.setCallback(caller.getTarget().copyTemplateCallback(null, null)) - .setContext(anotherCall); - - motionSrv.copyAsync(srcTemplate, destTemplate, caller); - } - - protected Void copyTemplateCallback( - AsyncCallbackDispatcher callback, - CopyTemplateContext context) { - CopyCommandResult result = callback.getResult(); - TemplateInfo templateOnPrimaryStoreObj = context.template; - if (result.isFailed()) { - CreateBaseImageResult res = new CreateBaseImageResult( - templateOnPrimaryStoreObj); - res.setResult(result.getResult()); - context.getParentCallback().complete(res); - } - DataObjectInStore obj = objectInDataStoreMgr.findObject( - templateOnPrimaryStoreObj, templateOnPrimaryStoreObj.getDataStore()); - - - CreateBaseImageResult res = new CreateBaseImageResult( - templateOnPrimaryStoreObj); - try { - objectInDataStoreMgr.update(obj, - ObjectInDataStoreStateMachine.Event.OperationSuccessed); - } catch (NoTransitionException e) { - s_logger.debug("Failed to update copying state: ", e); - try { - objectInDataStoreMgr.update(templateOnPrimaryStoreObj, - ObjectInDataStoreStateMachine.Event.OperationFailed); - } catch (NoTransitionException e1) { - } - - res.setResult("Failed to update copying state: " + e.toString()); - context.getParentCallback().complete(res); - } - context.getParentCallback().complete(res); - return null; - }*/ - @Override - public Void installAsync(TemplateInfo template, PrimaryDataStore store, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java index e7a42dea750..8d0a5a82bb1 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java @@ -41,6 +41,7 @@ public class VolumeDataFactoryImpl implements VolumeDataFactory { VolumeDataStoreDao volumeStoreDao; @Inject DataStoreManager storeMgr; + @Override public VolumeInfo getVolume(long volumeId, DataStore store) { VolumeVO volumeVO = volumeDao.findById(volumeId); @@ -57,7 +58,7 @@ public class VolumeDataFactoryImpl implements VolumeDataFactory { if (volumeVO.getPoolId() == null) { DataStore store = null; VolumeDataStoreVO volumeStore = volumeStoreDao.findByVolume(volumeId); - if ( volumeStore != null ){ + if (volumeStore != null) { store = this.storeMgr.getDataStore(volumeStore.getDataStoreId(), DataStoreRole.Image); } vol = VolumeObject.getVolumeObject(store, volumeVO); @@ -70,8 +71,8 @@ public class VolumeDataFactoryImpl implements VolumeDataFactory { @Override public VolumeInfo getVolume(DataObject volume, DataStore store) { - VolumeInfo vol = (VolumeObject)getVolume(volume.getId(), store); - vol.addPayload(((VolumeInfo)volume).getpayload()); + VolumeInfo vol = getVolume(volume.getId(), store); + vol.addPayload(((VolumeInfo) volume).getpayload()); return vol; } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java index d3e8c543b54..454a50c38bf 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java @@ -38,11 +38,11 @@ public class VolumeEntityImpl implements VolumeEntity { private VolumeInfo volumeInfo; private final VolumeService vs; private VolumeApiResult result; - + public VolumeEntityImpl() { this.vs = null; } - + public VolumeEntityImpl(VolumeInfo volumeObject, VolumeService vs) { this.volumeInfo = volumeObject; this.vs = vs; @@ -52,7 +52,7 @@ public class VolumeEntityImpl implements VolumeEntity { return volumeInfo; } - @Override + @Override public String getUuid() { return volumeInfo.getUuid(); } @@ -92,7 +92,6 @@ public class VolumeEntityImpl implements VolumeEntity { return null; } - @Override public List getApplicableActions() { // TODO Auto-generated method stub @@ -141,7 +140,6 @@ public class VolumeEntityImpl implements VolumeEntity { } - @Override public long getSize() { return volumeInfo.getSize(); @@ -149,7 +147,7 @@ public class VolumeEntityImpl implements VolumeEntity { @Override public DiskFormat getDiskType() { - return null; + return null; } @Override @@ -164,41 +162,40 @@ public class VolumeEntityImpl implements VolumeEntity { @Override public void destroy() { - /*AsyncCallFuture future = vs.deleteVolumeAsync(volumeInfo); - try { - result = future.get(); - if (!result.isSuccess()) { - throw new CloudRuntimeException("Failed to create volume:" + result.getResult()); - } - } catch (InterruptedException e) { - throw new CloudRuntimeException("wait to delete volume info failed", e); - } catch (ExecutionException e) { - throw new CloudRuntimeException("wait to delete volume failed", e); - }*/ + /* + * AsyncCallFuture future = + * vs.deleteVolumeAsync(volumeInfo); try { result = future.get(); if + * (!result.isSuccess()) { throw new + * CloudRuntimeException("Failed to create volume:" + + * result.getResult()); } } catch (InterruptedException e) { throw new + * CloudRuntimeException("wait to delete volume info failed", e); } + * catch (ExecutionException e) { throw new + * CloudRuntimeException("wait to delete volume failed", e); } + */ } - @Override - public Map getDetails() { - // TODO Auto-generated method stub - return null; - } + @Override + public Map getDetails() { + // TODO Auto-generated method stub + return null; + } - @Override - public void addDetail(String name, String value) { - // TODO Auto-generated method stub - - } + @Override + public void addDetail(String name, String value) { + // TODO Auto-generated method stub - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - - } + } - @Override - public void updateDetail(String name, String value) { - // TODO Auto-generated method stub - - } + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public void updateDetail(String name, String value) { + // TODO Auto-generated method stub + + } } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java deleted file mode 100644 index 9349e6b11cc..00000000000 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.storage.volume; - -public interface VolumeMotionService { - boolean copyVolume(String volumeUri, String destVolumeUri); -} diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java index 77a0762f0b9..bc14b6ac673 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java @@ -104,7 +104,7 @@ public class VolumeObject implements VolumeInfo { } public void setSize(Long size) { - volumeVO.setSize(size); + volumeVO.setSize(size); } @Override @@ -122,10 +122,10 @@ public class VolumeObject implements VolumeInfo { return volumeVO.getSize(); } - public long getVolumeId() { return volumeVO.getId(); } + public boolean stateTransit(Volume.Event event) { boolean result = false; try { @@ -160,16 +160,15 @@ public class VolumeObject implements VolumeInfo { if (this.dataStore == null) { throw new CloudRuntimeException("datastore must be set before using this object"); } - DataObjectInStore obj = objectInStoreMgr.findObject(this.volumeVO.getId(), DataObjectType.VOLUME, this.dataStore.getId(), this.dataStore.getRole()); + DataObjectInStore obj = objectInStoreMgr.findObject(this.volumeVO.getId(), DataObjectType.VOLUME, + this.dataStore.getId(), this.dataStore.getRole()); if (obj.getState() != ObjectInDataStoreStateMachine.State.Ready) { - return this.dataStore.getUri() + - "&" + EncodingType.OBJTYPE + "=" + DataObjectType.VOLUME + - "&" + EncodingType.SIZE + "=" + this.volumeVO.getSize() + - "&" + EncodingType.NAME + "=" + this.volumeVO.getName(); + return this.dataStore.getUri() + "&" + EncodingType.OBJTYPE + "=" + DataObjectType.VOLUME + "&" + + EncodingType.SIZE + "=" + this.volumeVO.getSize() + "&" + EncodingType.NAME + "=" + + this.volumeVO.getName(); } else { - return this.dataStore.getUri() + - "&" + EncodingType.OBJTYPE + "=" + DataObjectType.VOLUME + - "&" + EncodingType.PATH + "=" + obj.getInstallPath(); + return this.dataStore.getUri() + "&" + EncodingType.OBJTYPE + "=" + DataObjectType.VOLUME + "&" + + EncodingType.PATH + "=" + obj.getInstallPath(); } } @@ -178,32 +177,32 @@ public class VolumeObject implements VolumeInfo { return DataObjectType.VOLUME; } - @Override - public void processEvent( - ObjectInDataStoreStateMachine.Event event) { + public void processEvent(ObjectInDataStoreStateMachine.Event event) { if (this.dataStore == null) { return; } try { Volume.Event volEvent = null; - if ( this.dataStore.getRole() == DataStoreRole.ImageCache){ + if (this.dataStore.getRole() == DataStoreRole.ImageCache) { objectInStoreMgr.update(this, event); return; } if (this.dataStore.getRole() == DataStoreRole.Image) { objectInStoreMgr.update(this, event); - if (this.volumeVO.getState() == Volume.State.Migrating || this.volumeVO.getState() == Volume.State.Copying || this.volumeVO.getState() == Volume.State.Uploaded) { - return; + if (this.volumeVO.getState() == Volume.State.Migrating + || this.volumeVO.getState() == Volume.State.Copying + || this.volumeVO.getState() == Volume.State.Uploaded) { + return; } if (event == ObjectInDataStoreStateMachine.Event.CreateOnlyRequested) { volEvent = Volume.Event.UploadRequested; } else if (event == ObjectInDataStoreStateMachine.Event.MigrationRequested) { - volEvent = Volume.Event.CopyRequested; + volEvent = Volume.Event.CopyRequested; } } else { - if (event == ObjectInDataStoreStateMachine.Event.CreateRequested || - event == ObjectInDataStoreStateMachine.Event.CreateOnlyRequested) { + if (event == ObjectInDataStoreStateMachine.Event.CreateRequested + || event == ObjectInDataStoreStateMachine.Event.CreateOnlyRequested) { volEvent = Volume.Event.CreateRequested; } else if (event == ObjectInDataStoreStateMachine.Event.CopyingRequested) { volEvent = Volume.Event.CopyRequested; @@ -221,16 +220,16 @@ public class VolumeObject implements VolumeInfo { } else if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) { volEvent = Volume.Event.OperationFailed; } else if (event == ObjectInDataStoreStateMachine.Event.ResizeRequested) { - volEvent = Volume.Event.ResizeRequested; + volEvent = Volume.Event.ResizeRequested; } this.stateTransit(volEvent); } catch (Exception e) { s_logger.debug("Failed to update state", e); throw new CloudRuntimeException("Failed to update state:" + e.toString()); - } finally{ + } finally { // in case of OperationFailed, expunge the entry - if ( event == ObjectInDataStoreStateMachine.Event.OperationFailed && (this.volumeVO.getState() != Volume.State.Copying - && this.volumeVO.getState() != Volume.State.Uploaded)){ + if (event == ObjectInDataStoreStateMachine.Event.OperationFailed + && (this.volumeVO.getState() != Volume.State.Copying && this.volumeVO.getState() != Volume.State.Uploaded)) { objectInStoreMgr.delete(this); } } @@ -359,22 +358,22 @@ public class VolumeObject implements VolumeInfo { @Override public Object getpayload() { - return this.payload; + return this.payload; } - public VolumeVO getVolume(){ + public VolumeVO getVolume() { return this.volumeVO; } - @Override - public HypervisorType getHypervisorType() { - return this.volumeDao.getHypervisorType(this.volumeVO.getId()); - } + @Override + public HypervisorType getHypervisorType() { + return this.volumeDao.getHypervisorType(this.volumeVO.getId()); + } - @Override - public Long getLastPoolId() { - return this.volumeVO.getLastPoolId(); - } + @Override + public Long getLastPoolId() { + return this.volumeVO.getLastPoolId(); + } @Override public DataTO getTO() { @@ -410,13 +409,15 @@ public class VolumeObject implements VolumeInfo { // image store or imageCache store if (answer instanceof DownloadAnswer) { DownloadAnswer dwdAnswer = (DownloadAnswer) answer; - VolumeDataStoreVO volStore = this.volumeStoreDao.findByStoreVolume(this.dataStore.getId(), this.getId()); + VolumeDataStoreVO volStore = this.volumeStoreDao.findByStoreVolume(this.dataStore.getId(), + this.getId()); volStore.setInstallPath(dwdAnswer.getInstallPath()); volStore.setChecksum(dwdAnswer.getCheckSum()); this.volumeStoreDao.update(volStore.getId(), volStore); - } else if (answer instanceof CopyCmdAnswer ){ + } else if (answer instanceof CopyCmdAnswer) { CopyCmdAnswer cpyAnswer = (CopyCmdAnswer) answer; - VolumeDataStoreVO volStore = this.volumeStoreDao.findByStoreVolume(this.dataStore.getId(), this.getId()); + VolumeDataStoreVO volStore = this.volumeStoreDao.findByStoreVolume(this.dataStore.getId(), + this.getId()); VolumeObjectTO newVol = (VolumeObjectTO) cpyAnswer.getNewData(); volStore.setInstallPath(newVol.getPath()); volStore.setSize(newVol.getSize()); @@ -433,8 +434,8 @@ public class VolumeObject implements VolumeInfo { } - @Override - public ImageFormat getFormat() { - return this.volumeVO.getFormat(); - } + @Override + public ImageFormat getFormat() { + return this.volumeVO.getFormat(); + } } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java index 53a4620c368..09752eca00a 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java @@ -25,9 +25,6 @@ import java.util.Map; import javax.inject.Inject; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; @@ -53,6 +50,8 @@ import org.apache.cloudstack.storage.datastore.PrimaryDataStore; import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -69,7 +68,6 @@ import com.cloud.host.Host; import com.cloud.storage.StoragePool; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.Volume; -import com.cloud.storage.Volume.Type; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.download.DownloadMonitor; @@ -78,9 +76,7 @@ import com.cloud.storage.template.TemplateProp; import com.cloud.user.AccountManager; import com.cloud.user.ResourceLimitService; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.UriUtils; import com.cloud.utils.db.DB; -import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.VMInstanceDao; @Component @@ -97,10 +93,9 @@ public class VolumeServiceImpl implements VolumeService { @Inject DataMotionService motionSrv; @Inject - TemplateInstallStrategy templateInstallStrategy; - @Inject VolumeDataFactory volFactory; - @Inject SnapshotManager snapshotMgr; + @Inject + SnapshotManager snapshotMgr; @Inject ResourceLimitService _resourceLimitMgr; @Inject @@ -109,7 +104,8 @@ public class VolumeServiceImpl implements VolumeService { AccountManager _accountMgr; @Inject AlertManager _alertMgr; - @Inject VMInstanceDao vmDao; + @Inject + VMInstanceDao vmDao; @Inject ConfigurationDao configDao; @Inject @@ -128,10 +124,12 @@ public class VolumeServiceImpl implements VolumeService { private final DataObject volume; private final AsyncCallFuture future; + /** * @param callback */ - public CreateVolumeContext(AsyncCompletionCallback callback, DataObject volume, AsyncCallFuture future) { + public CreateVolumeContext(AsyncCompletionCallback callback, DataObject volume, + AsyncCallFuture future) { super(callback); this.volume = volume; this.future = future; @@ -153,16 +151,17 @@ public class VolumeServiceImpl implements VolumeService { DataObject volumeOnStore = dataStore.create(volume); volumeOnStore.processEvent(Event.CreateOnlyRequested); - CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, future); + CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, + future); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().createVolumeCallback(null, null)) - .setContext(context); + caller.setCallback(caller.getTarget().createVolumeCallback(null, null)).setContext(context); dataStore.getDriver().createAsync(volumeOnStore, caller); return future; } - protected Void createVolumeCallback(AsyncCallbackDispatcher callback, CreateVolumeContext context) { + protected Void createVolumeCallback(AsyncCallbackDispatcher callback, + CreateVolumeContext context) { CreateCmdResult result = callback.getResult(); DataObject vo = context.getVolume(); String errMsg = null; @@ -172,7 +171,7 @@ public class VolumeServiceImpl implements VolumeService { vo.processEvent(Event.OperationFailed); errMsg = result.getResult(); } - VolumeApiResult volResult = new VolumeApiResult((VolumeObject)vo); + VolumeApiResult volResult = new VolumeApiResult((VolumeObject) vo); if (errMsg != null) { volResult.setResult(errMsg); } @@ -183,10 +182,12 @@ public class VolumeServiceImpl implements VolumeService { private class DeleteVolumeContext extends AsyncRpcConext { private final VolumeObject volume; private final AsyncCallFuture future; + /** * @param callback */ - public DeleteVolumeContext(AsyncCompletionCallback callback, VolumeObject volume, AsyncCallFuture future) { + public DeleteVolumeContext(AsyncCompletionCallback callback, VolumeObject volume, + AsyncCallFuture future) { super(callback); this.volume = volume; this.future = future; @@ -203,7 +204,7 @@ public class VolumeServiceImpl implements VolumeService { @DB @Override - public AsyncCallFuture expungeVolumeAsync(VolumeInfo volume) { + public AsyncCallFuture expungeVolumeAsync(VolumeInfo volume) { AsyncCallFuture future = new AsyncCallFuture(); VolumeApiResult result = new VolumeApiResult(volume); if (volume.getDataStore() == null) { @@ -212,42 +213,32 @@ public class VolumeServiceImpl implements VolumeService { return future; } - String vmName = null; VolumeVO vol = volDao.findById(volume.getId()); - if (vol.getVolumeType() == Type.ROOT && vol.getInstanceId() != null) { - VirtualMachine vm = vmDao.findByIdIncludingRemoved(vol - .getInstanceId()); - if (vm != null) { - vmName = vm.getInstanceName(); - } - } String volumePath = vol.getPath(); Long poolId = vol.getPoolId(); if (poolId == null || volumePath == null || volumePath.trim().isEmpty()) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Marking volume that was never created as destroyed: " - + vol); + s_logger.debug("Marking volume that was never created as destroyed: " + vol); } volDao.remove(vol.getId()); future.complete(result); return future; } - VolumeObject vo = (VolumeObject)volume; + VolumeObject vo = (VolumeObject) volume; volume.processEvent(Event.ExpungeRequested); - DeleteVolumeContext context = new DeleteVolumeContext(null, vo, future); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().deleteVolumeCallback(null, null)) - .setContext(context); + caller.setCallback(caller.getTarget().deleteVolumeCallback(null, null)).setContext(context); volume.getDataStore().getDriver().deleteAsync(volume, caller); return future; } - public Void deleteVolumeCallback(AsyncCallbackDispatcher callback, DeleteVolumeContext context) { + public Void deleteVolumeCallback(AsyncCallbackDispatcher callback, + DeleteVolumeContext context) { CommandResult result = callback.getResult(); VolumeObject vo = context.getVolume(); VolumeApiResult apiResult = new VolumeApiResult(vo); @@ -289,9 +280,10 @@ public class VolumeServiceImpl implements VolumeService { private final TemplateInfo srcTemplate; private final AsyncCallFuture future; final DataObject destObj; - public CreateBaseImageContext(AsyncCompletionCallback callback, VolumeInfo volume, PrimaryDataStore datastore, - TemplateInfo srcTemplate, - AsyncCallFuture future, DataObject destObj) { + + public CreateBaseImageContext(AsyncCompletionCallback callback, VolumeInfo volume, + PrimaryDataStore datastore, TemplateInfo srcTemplate, AsyncCallFuture future, + DataObject destObj) { super(callback); this.volume = volume; this.dataStore = datastore; @@ -320,6 +312,7 @@ public class VolumeServiceImpl implements VolumeService { static class CreateBaseImageResult extends CommandResult { final TemplateInfo template; + public CreateBaseImageResult(TemplateInfo template) { super(); this.template = template; @@ -327,61 +320,60 @@ public class VolumeServiceImpl implements VolumeService { } private TemplateInfo waitForTemplateDownloaded(PrimaryDataStore store, TemplateInfo template) { - int storagePoolMaxWaitSeconds = NumbersUtil.parseInt(configDao.getValue(Config.StoragePoolMaxWaitSeconds.key()), 3600); - int sleepTime = 120; - int tries = storagePoolMaxWaitSeconds/sleepTime; - while (tries > 0) { - TemplateInfo tmpl = store.getTemplate(template.getId()); - if (tmpl != null) { - return tmpl; - } - try { - Thread.sleep(sleepTime * 1000); - } catch (InterruptedException e) { - s_logger.debug("waiting for template download been interrupted: " + e.toString()); - } - tries--; - } - return null; + int storagePoolMaxWaitSeconds = NumbersUtil.parseInt( + configDao.getValue(Config.StoragePoolMaxWaitSeconds.key()), 3600); + int sleepTime = 120; + int tries = storagePoolMaxWaitSeconds / sleepTime; + while (tries > 0) { + TemplateInfo tmpl = store.getTemplate(template.getId()); + if (tmpl != null) { + return tmpl; + } + try { + Thread.sleep(sleepTime * 1000); + } catch (InterruptedException e) { + s_logger.debug("waiting for template download been interrupted: " + e.toString()); + } + tries--; + } + return null; } + @DB - protected void createBaseImageAsync(VolumeInfo volume, PrimaryDataStore dataStore, TemplateInfo template, AsyncCallFuture future) { + protected void createBaseImageAsync(VolumeInfo volume, PrimaryDataStore dataStore, TemplateInfo template, + AsyncCallFuture future) { DataObject templateOnPrimaryStoreObj = dataStore.create(template); CreateBaseImageContext context = new CreateBaseImageContext(null, volume, - dataStore, - template, - future, templateOnPrimaryStoreObj); + dataStore, template, future, templateOnPrimaryStoreObj); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().copyBaseImageCallback(null, null)) - .setContext(context); + caller.setCallback(caller.getTarget().copyBaseImageCallback(null, null)).setContext(context); try { - templateOnPrimaryStoreObj.processEvent(Event.CreateOnlyRequested); + templateOnPrimaryStoreObj.processEvent(Event.CreateOnlyRequested); } catch (Exception e) { s_logger.info("Got exception in case of multi-thread"); - try { - templateOnPrimaryStoreObj = waitForTemplateDownloaded(dataStore, template); - } catch(Exception e1) { - s_logger.debug("wait for template:" + template.getId() + " downloading finished, but failed"); - VolumeApiResult result = new VolumeApiResult(volume); - result.setResult(e1.toString()); - future.complete(result); - return; - } - if (templateOnPrimaryStoreObj == null) { - VolumeApiResult result = new VolumeApiResult(volume); + try { + templateOnPrimaryStoreObj = waitForTemplateDownloaded(dataStore, template); + } catch (Exception e1) { + s_logger.debug("wait for template:" + template.getId() + " downloading finished, but failed"); + VolumeApiResult result = new VolumeApiResult(volume); + result.setResult(e1.toString()); + future.complete(result); + return; + } + if (templateOnPrimaryStoreObj == null) { + VolumeApiResult result = new VolumeApiResult(volume); result.setResult("wait for template:" + template.getId() + " downloading finished, but failed"); future.complete(result); return; - } else { - s_logger.debug("waiting for template:" + template.getId() + " downloading finished, success"); - createVolumeFromBaseImageAsync(volume, templateOnPrimaryStoreObj, dataStore, future); - return; - } + } else { + s_logger.debug("waiting for template:" + template.getId() + " downloading finished, success"); + createVolumeFromBaseImageAsync(volume, templateOnPrimaryStoreObj, dataStore, future); + return; + } } - try { motionSrv.copyAsync(template, templateOnPrimaryStoreObj, caller); } catch (Exception e) { @@ -395,7 +387,8 @@ public class VolumeServiceImpl implements VolumeService { } @DB - protected Void copyBaseImageCallback(AsyncCallbackDispatcher callback, CreateBaseImageContext context) { + protected Void copyBaseImageCallback(AsyncCallbackDispatcher callback, + CreateBaseImageContext context) { CopyCommandResult result = callback.getResult(); VolumeApiResult res = new VolumeApiResult(context.getVolume()); @@ -416,34 +409,33 @@ public class VolumeServiceImpl implements VolumeService { private class CreateVolumeFromBaseImageContext extends AsyncRpcConext { private final DataObject vo; private final AsyncCallFuture future; - private final DataStore primaryStore; private final DataObject templateOnStore; private final SnapshotInfo snapshot; + public CreateVolumeFromBaseImageContext(AsyncCompletionCallback callback, DataObject vo, - DataStore primaryStore, - DataObject templateOnStore, - AsyncCallFuture future, SnapshotInfo snapshot) { + DataStore primaryStore, DataObject templateOnStore, AsyncCallFuture future, + SnapshotInfo snapshot) { super(callback); this.vo = vo; this.future = future; - this.primaryStore = primaryStore; this.templateOnStore = templateOnStore; this.snapshot = snapshot; } - public AsyncCallFuture getFuture() { return this.future; } } @DB - protected void createVolumeFromBaseImageAsync(VolumeInfo volume, DataObject templateOnPrimaryStore, PrimaryDataStore pd, AsyncCallFuture future) { + protected void createVolumeFromBaseImageAsync(VolumeInfo volume, DataObject templateOnPrimaryStore, + PrimaryDataStore pd, AsyncCallFuture future) { DataObject volumeOnPrimaryStorage = pd.create(volume); volumeOnPrimaryStorage.processEvent(Event.CreateOnlyRequested); - CreateVolumeFromBaseImageContext context = new CreateVolumeFromBaseImageContext(null, volumeOnPrimaryStorage, pd, templateOnPrimaryStore, future, null); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + CreateVolumeFromBaseImageContext context = new CreateVolumeFromBaseImageContext( + null, volumeOnPrimaryStorage, pd, templateOnPrimaryStore, future, null); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); caller.setCallback(caller.getTarget().createVolumeFromBaseImageCallBack(null, null)); caller.setContext(context); @@ -452,10 +444,12 @@ public class VolumeServiceImpl implements VolumeService { } @DB - protected Void createVolumeFromBaseImageCallBack(AsyncCallbackDispatcher callback, CreateVolumeFromBaseImageContext context) { + protected Void createVolumeFromBaseImageCallBack( + AsyncCallbackDispatcher callback, + CreateVolumeFromBaseImageContext context) { DataObject vo = context.vo; CopyCommandResult result = callback.getResult(); - VolumeApiResult volResult = new VolumeApiResult((VolumeObject)vo); + VolumeApiResult volResult = new VolumeApiResult((VolumeObject) vo); if (result.isSuccess()) { vo.processEvent(Event.OperationSuccessed, result.getAnswer()); @@ -471,11 +465,11 @@ public class VolumeServiceImpl implements VolumeService { @DB @Override - public AsyncCallFuture createVolumeFromTemplateAsync(VolumeInfo volume, long dataStoreId, TemplateInfo template) { + public AsyncCallFuture createVolumeFromTemplateAsync(VolumeInfo volume, long dataStoreId, + TemplateInfo template) { PrimaryDataStore pd = dataStoreMgr.getPrimaryDataStore(dataStoreId); TemplateInfo templateOnPrimaryStore = pd.getTemplate(template.getId()); AsyncCallFuture future = new AsyncCallFuture(); - VolumeApiResult result = new VolumeApiResult(volume); if (templateOnPrimaryStore == null) { createBaseImageAsync(volume, pd, template, future); @@ -488,8 +482,7 @@ public class VolumeServiceImpl implements VolumeService { @Override @DB - public boolean destroyVolume(long volumeId) - throws ConcurrentOperationException { + public boolean destroyVolume(long volumeId) throws ConcurrentOperationException { VolumeInfo vol = volFactory.getVolume(volumeId); vol.processEvent(Event.DestroyRequested); @@ -501,59 +494,59 @@ public class VolumeServiceImpl implements VolumeService { } @Override - public AsyncCallFuture createVolumeFromSnapshot( - VolumeInfo volume, DataStore store, SnapshotInfo snapshot) { + public AsyncCallFuture createVolumeFromSnapshot(VolumeInfo volume, DataStore store, + SnapshotInfo snapshot) { AsyncCallFuture future = new AsyncCallFuture(); try { - DataObject volumeOnStore = store.create(volume); - volumeOnStore.processEvent(Event.CreateOnlyRequested); - snapshot.processEvent(Event.CopyingRequested); - CreateVolumeFromBaseImageContext context = new CreateVolumeFromBaseImageContext(null, - volume, store, volumeOnStore, future, snapshot); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().createVolumeFromSnapshotCallback(null, null)) - .setContext(context); - motionSrv.copyAsync(snapshot, volumeOnStore, caller); + DataObject volumeOnStore = store.create(volume); + volumeOnStore.processEvent(Event.CreateOnlyRequested); + snapshot.processEvent(Event.CopyingRequested); + CreateVolumeFromBaseImageContext context = new CreateVolumeFromBaseImageContext( + null, volume, store, volumeOnStore, future, snapshot); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().createVolumeFromSnapshotCallback(null, null)).setContext(context); + motionSrv.copyAsync(snapshot, volumeOnStore, caller); } catch (Exception e) { - s_logger.debug("create volume from snapshot failed", e); - VolumeApiResult result = new VolumeApiResult(volume); - result.setResult(e.toString()); - future.complete(result); + s_logger.debug("create volume from snapshot failed", e); + VolumeApiResult result = new VolumeApiResult(volume); + result.setResult(e.toString()); + future.complete(result); } return future; } - protected Void createVolumeFromSnapshotCallback(AsyncCallbackDispatcher callback, - CreateVolumeFromBaseImageContext context) { - CopyCommandResult result = callback.getResult(); - VolumeInfo volume = (VolumeInfo)context.templateOnStore; - SnapshotInfo snapshot = context.snapshot; - VolumeApiResult apiResult = new VolumeApiResult(volume); - Event event = null; - if (result.isFailed()) { - apiResult.setResult(result.getResult()); - event = Event.OperationFailed; - } else { - event = Event.OperationSuccessed; - } + protected Void createVolumeFromSnapshotCallback( + AsyncCallbackDispatcher callback, + CreateVolumeFromBaseImageContext context) { + CopyCommandResult result = callback.getResult(); + VolumeInfo volume = (VolumeInfo) context.templateOnStore; + SnapshotInfo snapshot = context.snapshot; + VolumeApiResult apiResult = new VolumeApiResult(volume); + Event event = null; + if (result.isFailed()) { + apiResult.setResult(result.getResult()); + event = Event.OperationFailed; + } else { + event = Event.OperationSuccessed; + } - try { - if (result.isSuccess()) { - volume.processEvent(event, result.getAnswer()); - } else { - volume.processEvent(event); - } - snapshot.processEvent(event); - } catch (Exception e) { - s_logger.debug("create volume from snapshot failed", e); - apiResult.setResult(e.toString()); - } + try { + if (result.isSuccess()) { + volume.processEvent(event, result.getAnswer()); + } else { + volume.processEvent(event); + } + snapshot.processEvent(event); + } catch (Exception e) { + s_logger.debug("create volume from snapshot failed", e); + apiResult.setResult(e.toString()); + } - AsyncCallFuture future = context.future; - future.complete(apiResult); - return null; + AsyncCallFuture future = context.future; + future.complete(apiResult); + return null; } protected VolumeVO duplicateVolumeOnAnotherStorage(Volume volume, StoragePool pool) { @@ -568,113 +561,107 @@ public class VolumeServiceImpl implements VolumeService { return volDao.persist(newVol); } - private class CopyVolumeContext extends AsyncRpcConext { final VolumeInfo srcVolume; final VolumeInfo destVolume; - final DataStore destStore; final AsyncCallFuture future; + /** * @param callback */ - public CopyVolumeContext(AsyncCompletionCallback callback, AsyncCallFuture future, VolumeInfo srcVolume, VolumeInfo destVolume, - DataStore destStore) { + public CopyVolumeContext(AsyncCompletionCallback callback, AsyncCallFuture future, + VolumeInfo srcVolume, VolumeInfo destVolume, DataStore destStore) { super(callback); this.srcVolume = srcVolume; this.destVolume = destVolume; - this.destStore = destStore; this.future = future; } } - + protected AsyncCallFuture copyVolumeFromImageToPrimary(VolumeInfo srcVolume, DataStore destStore) { - AsyncCallFuture future = new AsyncCallFuture(); - VolumeApiResult res = new VolumeApiResult(srcVolume); - VolumeInfo destVolume = null; - try { - destVolume = (VolumeInfo)destStore.create(srcVolume); - destVolume.processEvent(Event.CopyingRequested); - srcVolume.processEvent(Event.CopyingRequested); + AsyncCallFuture future = new AsyncCallFuture(); + VolumeApiResult res = new VolumeApiResult(srcVolume); + VolumeInfo destVolume = null; + try { + destVolume = (VolumeInfo) destStore.create(srcVolume); + destVolume.processEvent(Event.CopyingRequested); + srcVolume.processEvent(Event.CopyingRequested); - CopyVolumeContext context = new CopyVolumeContext(null, future, srcVolume, - destVolume, - destStore); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().copyVolumeFromImageToPrimaryCallback(null, null)) - .setContext(context); + CopyVolumeContext context = new CopyVolumeContext(null, future, + srcVolume, destVolume, destStore); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); + caller.setCallback(caller.getTarget().copyVolumeFromImageToPrimaryCallback(null, null)).setContext(context); - motionSrv.copyAsync(srcVolume, destVolume, caller); - return future; - } catch (Exception e) { - s_logger.error("failed to copy volume from image store", e); - if (destVolume != null) { - destVolume.processEvent(Event.OperationFailed); - } - - srcVolume.processEvent(Event.OperationFailed); - res.setResult(e.toString()); - future.complete(res); - return future; - } + motionSrv.copyAsync(srcVolume, destVolume, caller); + return future; + } catch (Exception e) { + s_logger.error("failed to copy volume from image store", e); + if (destVolume != null) { + destVolume.processEvent(Event.OperationFailed); + } + + srcVolume.processEvent(Event.OperationFailed); + res.setResult(e.toString()); + future.complete(res); + return future; + } } - protected Void copyVolumeFromImageToPrimaryCallback(AsyncCallbackDispatcher callback, CopyVolumeContext context) { - VolumeInfo srcVolume = context.srcVolume; - VolumeInfo destVolume = context.destVolume; - CopyCommandResult result = callback.getResult(); - AsyncCallFuture future = context.future; - VolumeApiResult res = new VolumeApiResult(destVolume); - try { - if (res.isFailed()) { - destVolume.processEvent(Event.OperationFailed); - srcVolume.processEvent(Event.OperationFailed); - res.setResult(result.getResult()); - future.complete(res); - } + protected Void copyVolumeFromImageToPrimaryCallback( + AsyncCallbackDispatcher callback, + CopyVolumeContext context) { + VolumeInfo srcVolume = context.srcVolume; + VolumeInfo destVolume = context.destVolume; + CopyCommandResult result = callback.getResult(); + AsyncCallFuture future = context.future; + VolumeApiResult res = new VolumeApiResult(destVolume); + try { + if (res.isFailed()) { + destVolume.processEvent(Event.OperationFailed); + srcVolume.processEvent(Event.OperationFailed); + res.setResult(result.getResult()); + future.complete(res); + } - srcVolume.processEvent(Event.OperationSuccessed); - destVolume.processEvent(Event.OperationSuccessed, result.getAnswer()); - srcVolume.getDataStore().delete(srcVolume); - future.complete(res); - } catch (Exception e) { - res.setResult(e.toString()); - future.complete(res); - } - return null; + srcVolume.processEvent(Event.OperationSuccessed); + destVolume.processEvent(Event.OperationSuccessed, result.getAnswer()); + srcVolume.getDataStore().delete(srcVolume); + future.complete(res); + } catch (Exception e) { + res.setResult(e.toString()); + future.complete(res); + } + return null; } - + @Override - public AsyncCallFuture copyVolume(VolumeInfo srcVolume, - DataStore destStore) { - - if (srcVolume.getState() == Volume.State.Uploaded) { - return copyVolumeFromImageToPrimary(srcVolume, destStore); - } - + public AsyncCallFuture copyVolume(VolumeInfo srcVolume, DataStore destStore) { + + if (srcVolume.getState() == Volume.State.Uploaded) { + return copyVolumeFromImageToPrimary(srcVolume, destStore); + } + AsyncCallFuture future = new AsyncCallFuture(); VolumeApiResult res = new VolumeApiResult(srcVolume); try { if (!snapshotMgr.canOperateOnVolume(srcVolume)) { - s_logger.debug( - "There are snapshots creating on this volume, can not move this volume"); + s_logger.debug("There are snapshots creating on this volume, can not move this volume"); res.setResult("There are snapshots creating on this volume, can not move this volume"); future.complete(res); return future; } - VolumeVO destVol = duplicateVolumeOnAnotherStorage(srcVolume, (StoragePool)destStore); + VolumeVO destVol = duplicateVolumeOnAnotherStorage(srcVolume, (StoragePool) destStore); VolumeInfo destVolume = volFactory.getVolume(destVol.getId(), destStore); destVolume.processEvent(Event.MigrationRequested); srcVolume.processEvent(Event.MigrationRequested); - CopyVolumeContext context = new CopyVolumeContext(null, future, srcVolume, - destVolume, - destStore); + CopyVolumeContext context = new CopyVolumeContext(null, future, + srcVolume, destVolume, destStore); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().copyVolumeCallBack(null, null)) - .setContext(context); + caller.setCallback(caller.getTarget().copyVolumeCallBack(null, null)).setContext(context); motionSrv.copyAsync(srcVolume, destVolume, caller); } catch (Exception e) { s_logger.debug("Failed to copy volume" + e); @@ -684,7 +671,8 @@ public class VolumeServiceImpl implements VolumeService { return future; } - protected Void copyVolumeCallBack(AsyncCallbackDispatcher callback, CopyVolumeContext context) { + protected Void copyVolumeCallBack(AsyncCallbackDispatcher callback, + CopyVolumeContext context) { VolumeInfo srcVolume = context.srcVolume; VolumeInfo destVolume = context.destVolume; CopyCommandResult result = callback.getResult(); @@ -711,7 +699,7 @@ public class VolumeServiceImpl implements VolumeService { future.complete(res); return null; } catch (Exception e) { - s_logger.debug("Failed to process copy volume callback",e); + s_logger.debug("Failed to process copy volume callback", e); res.setResult(e.toString()); future.complete(res); } @@ -719,12 +707,11 @@ public class VolumeServiceImpl implements VolumeService { return null; } - private class MigrateVolumeContext extends AsyncRpcConext { final VolumeInfo srcVolume; final VolumeInfo destVolume; - final DataStore destStore; final AsyncCallFuture future; + /** * @param callback */ @@ -733,7 +720,6 @@ public class VolumeServiceImpl implements VolumeService { super(callback); this.srcVolume = srcVolume; this.destVolume = destVolume; - this.destStore = destStore; this.future = future; } } @@ -768,7 +754,6 @@ public class VolumeServiceImpl implements VolumeService { protected Void migrateVolumeCallBack(AsyncCallbackDispatcher callback, MigrateVolumeContext context) { VolumeInfo srcVolume = context.srcVolume; - VolumeInfo destVolume = context.destVolume; CopyCommandResult result = callback.getResult(); AsyncCallFuture future = context.future; VolumeApiResult res = new VolumeApiResult(srcVolume); @@ -793,6 +778,7 @@ public class VolumeServiceImpl implements VolumeService { private class MigrateVmWithVolumesContext extends AsyncRpcConext { final Map volumeToPool; final AsyncCallFuture future; + /** * @param callback */ @@ -810,7 +796,8 @@ public class VolumeServiceImpl implements VolumeService { AsyncCallFuture future = new AsyncCallFuture(); CommandResult res = new CommandResult(); try { - // Check to make sure there are no snapshot operations on a volume and + // Check to make sure there are no snapshot operations on a volume + // and // put it in the migrating state. List volumesMigrating = new ArrayList(); for (Map.Entry entry : volumeMap.entrySet()) { @@ -820,7 +807,8 @@ public class VolumeServiceImpl implements VolumeService { res.setResult("Snapshots are being created on a volume. Volumes cannot be migrated now."); future.complete(res); - // All the volumes that are already in migrating state need to be put back in ready state. + // All the volumes that are already in migrating state need + // to be put back in ready state. for (VolumeInfo volumeMigrating : volumesMigrating) { volumeMigrating.processEvent(Event.OperationFailed); } @@ -876,7 +864,6 @@ public class VolumeServiceImpl implements VolumeService { return null; } - @Override public AsyncCallFuture registerVolume(VolumeInfo volume, DataStore store) { @@ -885,7 +872,8 @@ public class VolumeServiceImpl implements VolumeService { volumeOnStore.processEvent(Event.CreateOnlyRequested); - CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, future); + CreateVolumeContext context = new CreateVolumeContext(null, volumeOnStore, + future); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); caller.setCallback(caller.getTarget().registerVolumeCallback(null, null)); caller.setContext(context); @@ -894,81 +882,81 @@ public class VolumeServiceImpl implements VolumeService { return future; } - protected Void registerVolumeCallback(AsyncCallbackDispatcher callback, CreateVolumeContext context) { + protected Void registerVolumeCallback(AsyncCallbackDispatcher callback, + CreateVolumeContext context) { CreateCmdResult result = callback.getResult(); try { - VolumeObject vo = (VolumeObject)context.volume; - if (result.isFailed()) { - vo.processEvent(Event.OperationFailed); - } else { - vo.processEvent(Event.OperationSuccessed, result.getAnswer()); - } + VolumeObject vo = (VolumeObject) context.volume; + if (result.isFailed()) { + vo.processEvent(Event.OperationFailed); + } else { + vo.processEvent(Event.OperationSuccessed, result.getAnswer()); + } - _resourceLimitMgr.incrementResourceCount(vo.getAccountId(), ResourceType.secondary_storage, - vo.getSize()); - VolumeApiResult res = new VolumeApiResult(vo); - context.future.complete(res); - return null; + _resourceLimitMgr.incrementResourceCount(vo.getAccountId(), ResourceType.secondary_storage, vo.getSize()); + VolumeApiResult res = new VolumeApiResult(vo); + context.future.complete(res); + return null; } catch (Exception e) { - s_logger.error("register volume failed: ", e); - VolumeApiResult res = new VolumeApiResult(null); - context.future.complete(res); - return null; + s_logger.error("register volume failed: ", e); + VolumeApiResult res = new VolumeApiResult(null); + context.future.complete(res); + return null; } } - - @Override - public AsyncCallFuture resize(VolumeInfo volume) { - AsyncCallFuture future = new AsyncCallFuture(); - VolumeApiResult result = new VolumeApiResult(volume); - try { - volume.processEvent(Event.ResizeRequested); - } catch (Exception e) { - s_logger.debug("Failed to change state to resize", e); - result.setResult(e.toString()); - future.complete(result); - return future; - } - CreateVolumeContext context = new CreateVolumeContext(null, volume, future); + @Override + public AsyncCallFuture resize(VolumeInfo volume) { + AsyncCallFuture future = new AsyncCallFuture(); + VolumeApiResult result = new VolumeApiResult(volume); + try { + volume.processEvent(Event.ResizeRequested); + } catch (Exception e) { + s_logger.debug("Failed to change state to resize", e); + result.setResult(e.toString()); + future.complete(result); + return future; + } + CreateVolumeContext context = new CreateVolumeContext(null, volume, future); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); caller.setCallback(caller.getTarget().resizeVolumeCallback(caller, context)).setContext(context); - volume.getDataStore().getDriver().resize(volume, caller); - return future; - } + volume.getDataStore().getDriver().resize(volume, caller); + return future; + } - protected Void resizeVolumeCallback(AsyncCallbackDispatcher callback, CreateVolumeContext context) { - CreateCmdResult result = callback.getResult(); - AsyncCallFuture future = context.future; - VolumeInfo volume = (VolumeInfo)context.volume; + protected Void resizeVolumeCallback(AsyncCallbackDispatcher callback, + CreateVolumeContext context) { + CreateCmdResult result = callback.getResult(); + AsyncCallFuture future = context.future; + VolumeInfo volume = (VolumeInfo) context.volume; - if (result.isFailed()) { - try { - volume.processEvent(Event.OperationFailed); - } catch (Exception e) { - s_logger.debug("Failed to change state", e); - } - VolumeApiResult res = new VolumeApiResult(volume); - res.setResult(result.getResult()); - future.complete(res); - return null; - } + if (result.isFailed()) { + try { + volume.processEvent(Event.OperationFailed); + } catch (Exception e) { + s_logger.debug("Failed to change state", e); + } + VolumeApiResult res = new VolumeApiResult(volume); + res.setResult(result.getResult()); + future.complete(res); + return null; + } - try { - volume.processEvent(Event.OperationSuccessed); - } catch(Exception e) { - s_logger.debug("Failed to change state", e); - VolumeApiResult res = new VolumeApiResult(volume); - res.setResult(result.getResult()); - future.complete(res); - return null; - } + try { + volume.processEvent(Event.OperationSuccessed); + } catch (Exception e) { + s_logger.debug("Failed to change state", e); + VolumeApiResult res = new VolumeApiResult(volume); + res.setResult(result.getResult()); + future.complete(res); + return null; + } - VolumeApiResult res = new VolumeApiResult(volume); - future.complete(res); + VolumeApiResult res = new VolumeApiResult(volume); + future.complete(res); - return null; - } + return null; + } @Override public void handleVolumeSync(DataStore store) { @@ -977,8 +965,6 @@ public class VolumeServiceImpl implements VolumeService { return; } long storeId = store.getId(); - Long zoneId = store.getScope().getScopeId(); - Map volumeInfos = listVolume(store); if (volumeInfos == null) { @@ -987,10 +973,10 @@ public class VolumeServiceImpl implements VolumeService { List dbVolumes = _volumeStoreDao.listByStoreId(storeId); List toBeDownloaded = new ArrayList(dbVolumes); - for (VolumeDataStoreVO volumeStore : dbVolumes){ + for (VolumeDataStoreVO volumeStore : dbVolumes) { VolumeVO volume = _volumeDao.findById(volumeStore.getVolumeId()); - //Exists then don't download - if (volumeInfos.containsKey(volume.getId())){ + // Exists then don't download + if (volumeInfos.containsKey(volume.getId())) { TemplateProp volInfo = volumeInfos.remove(volume.getId()); toBeDownloaded.remove(volumeStore); s_logger.info("Volume Sync found " + volume.getUuid() + " already in the volume image store table"); @@ -1003,7 +989,8 @@ public class VolumeServiceImpl implements VolumeService { volumeStore.setErrorString(msg); s_logger.info("msg"); if (volumeStore.getDownloadUrl() == null) { - msg = "Volume (" + volume.getUuid() + ") with install path " + volInfo.getInstallPath() + "is corrupted, please check in image store: " + volumeStore.getDataStoreId(); + msg = "Volume (" + volume.getUuid() + ") with install path " + volInfo.getInstallPath() + + "is corrupted, please check in image store: " + volumeStore.getDataStoreId(); s_logger.warn(msg); } else { toBeDownloaded.add(volumeStore); @@ -1026,14 +1013,13 @@ public class VolumeServiceImpl implements VolumeService { if (volInfo.getSize() > 0) { try { - String url = _volumeStoreDao.findByVolume(volume.getId()).getDownloadUrl(); _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()), - com.cloud.configuration.Resource.ResourceType.secondary_storage, - volInfo.getSize() - volInfo.getPhysicalSize()); + com.cloud.configuration.Resource.ResourceType.secondary_storage, volInfo.getSize() + - volInfo.getPhysicalSize()); } catch (ResourceAllocationException e) { s_logger.warn(e.getMessage()); - _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(), - volume.getPodId(), e.getMessage(), e.getMessage()); + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, + volume.getDataCenterId(), volume.getPodId(), e.getMessage(), e.getMessage()); } finally { _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal()); @@ -1044,33 +1030,36 @@ public class VolumeServiceImpl implements VolumeService { } // Volume is not on secondary but we should download. if (volumeStore.getDownloadState() != Status.DOWNLOADED) { - s_logger.info("Volume Sync did not find " + volume.getName() + " ready on image store " + storeId + ", will request download to start/resume shortly"); + s_logger.info("Volume Sync did not find " + volume.getName() + " ready on image store " + storeId + + ", will request download to start/resume shortly"); toBeDownloaded.add(volumeStore); } } - //Download volumes which haven't been downloaded yet. + // Download volumes which haven't been downloaded yet. if (toBeDownloaded.size() > 0) { for (VolumeDataStoreVO volumeHost : toBeDownloaded) { - if (volumeHost.getDownloadUrl() == null) { // If url is null we can't initiate the download + if (volumeHost.getDownloadUrl() == null) { // If url is null we + // can't initiate the + // download continue; } s_logger.debug("Volume " + volumeHost.getVolumeId() + " needs to be downloaded to " + store.getName()); - //TODO: pass a callback later + // TODO: pass a callback later VolumeInfo vol = volFactory.getVolume(volumeHost.getVolumeId()); createVolumeAsync(vol, store); } } - //Delete volumes which are not present on DB. + // Delete volumes which are not present on DB. /* - for (Long uniqueName : volumeInfos.keySet()) { - TemplateProp vInfo = volumeInfos.get(uniqueName); - expungeVolumeAsync(volFactory.getVolume(vInfo.getId(), store)); - - String description = "Deleted volume " + vInfo.getTemplateName() + " on image store " + storeId; - s_logger.info(description); - }*/ + * for (Long uniqueName : volumeInfos.keySet()) { TemplateProp vInfo = + * volumeInfos.get(uniqueName); + * expungeVolumeAsync(volFactory.getVolume(vInfo.getId(), store)); + * + * String description = "Deleted volume " + vInfo.getTemplateName() + + * " on image store " + storeId; s_logger.info(description); } + */ } @@ -1079,7 +1068,7 @@ public class VolumeServiceImpl implements VolumeService { EndPoint ep = _epSelector.select(store); Answer answer = ep.sendMessage(cmd); if (answer != null && answer.getResult()) { - ListVolumeAnswer tanswer = (ListVolumeAnswer)answer; + ListVolumeAnswer tanswer = (ListVolumeAnswer) answer; return tanswer.getTemplateInfo(); } else { if (s_logger.isDebugEnabled()) { @@ -1092,23 +1081,23 @@ public class VolumeServiceImpl implements VolumeService { @Override public SnapshotInfo takeSnapshot(VolumeInfo volume) { - VolumeObject vol = (VolumeObject)volume; - vol.stateTransit(Volume.Event.SnapshotRequested); + VolumeObject vol = (VolumeObject) volume; + vol.stateTransit(Volume.Event.SnapshotRequested); - SnapshotInfo snapshot = null; - try { - snapshot = snapshotMgr.takeSnapshot(volume); - } catch (Exception e) { - s_logger.debug("Take snapshot: " + volume.getId() + " failed: " + e.toString()); - } finally { - if (snapshot != null) { - vol.stateTransit(Volume.Event.OperationSucceeded); - } else { - vol.stateTransit(Volume.Event.OperationFailed); - } - } + SnapshotInfo snapshot = null; + try { + snapshot = snapshotMgr.takeSnapshot(volume); + } catch (Exception e) { + s_logger.debug("Take snapshot: " + volume.getId() + " failed: " + e.toString()); + } finally { + if (snapshot != null) { + vol.stateTransit(Volume.Event.OperationSucceeded); + } else { + vol.stateTransit(Volume.Event.OperationFailed); + } + } - return snapshot; + return snapshot; } } diff --git a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/ConfiguratorTest.java b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/ConfiguratorTest.java index 6ad951a2e05..ddbccb2fdb5 100644 --- a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/ConfiguratorTest.java +++ b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/ConfiguratorTest.java @@ -18,56 +18,50 @@ */ package org.apache.cloudstack.storage.volume.test; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import java.util.HashMap; import java.util.List; -import java.util.Map; - import javax.inject.Inject; -import javax.naming.ConfigurationException; - import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.cloud.dc.ClusterVO; import com.cloud.dc.dao.ClusterDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="classpath:/testContext.xml") +@ContextConfiguration(locations = "classpath:/testContext.xml") public class ConfiguratorTest { - @Inject + @Inject List providers; - + @Inject ClusterDao clusterDao; + @Before public void setup() { - /* ClusterVO cluster = new ClusterVO(); - cluster.setHypervisorType(HypervisorType.XenServer.toString()); - Mockito.when(clusterDao.findById(Mockito.anyLong())).thenReturn(cluster); - try { - providerMgr.configure("manager", null); - } catch (ConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - }*/ + /* + * ClusterVO cluster = new ClusterVO(); + * cluster.setHypervisorType(HypervisorType.XenServer.toString()); + * Mockito + * .when(clusterDao.findById(Mockito.anyLong())).thenReturn(cluster); + * try { providerMgr.configure("manager", null); } catch + * (ConfigurationException e) { // TODO Auto-generated catch block + * e.printStackTrace(); } + */ } + @Test public void testLoadConfigurator() { - /*for (PrimaryDataStoreConfigurator configurator : configurators) { - System.out.println(configurator.getClass().getName()); - }*/ + /* + * for (PrimaryDataStoreConfigurator configurator : configurators) { + * System.out.println(configurator.getClass().getName()); } + */ } - + @Test public void testProvider() { for (PrimaryDataStoreProvider provider : providers) { @@ -76,19 +70,21 @@ public class ConfiguratorTest { } } } - + @Test public void getProvider() { - // assertNotNull(providerMgr.getDataStoreProvider("sample primary data store provider")); + // assertNotNull(providerMgr.getDataStoreProvider("sample primary data store provider")); } - + @Test public void createDataStore() { - /*PrimaryDataStoreProvider provider = providerMgr.getDataStoreProvider("sample primary data store provider"); - Map params = new HashMap(); - params.put("url", "nfs://localhost/mnt"); - params.put("clusterId", "1"); - params.put("name", "nfsprimary"); - assertNotNull(provider.registerDataStore(params));*/ + /* + * PrimaryDataStoreProvider provider = + * providerMgr.getDataStoreProvider("sample primary data store provider" + * ); Map params = new HashMap(); + * params.put("url", "nfs://localhost/mnt"); params.put("clusterId", + * "1"); params.put("name", "nfsprimary"); + * assertNotNull(provider.registerDataStore(params)); + */ } } diff --git a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/Server.java b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/Server.java index f19d68e8ea1..b7874ebb111 100644 --- a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/Server.java +++ b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/Server.java @@ -22,19 +22,22 @@ import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; public class Server { Server1 svr; + public Server() { svr = new Server1(); } + void foo() { - // svr.foo1("foo", new AsyncCallbackDispatcher(this).setOperationName("callback").setContextParam("name", "foo")); + // svr.foo1("foo", new + // AsyncCallbackDispatcher(this).setOperationName("callback").setContextParam("name", + // "foo")); } - + void foocallback(AsyncCallbackDispatcher callback) { /* - System.out.println(callback.getContextParam("name")); - String result = callback.getResult(); - System.out.println(result); - */ + * System.out.println(callback.getContextParam("name")); String result = + * callback.getResult(); System.out.println(result); + */ } - + } diff --git a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestConfiguration.java b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestConfiguration.java index 1d3202f123b..eb871a54ae2 100644 --- a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestConfiguration.java +++ b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestConfiguration.java @@ -33,7 +33,7 @@ public class TestConfiguration { public ImageMotionService imageMotion() { return Mockito.mock(ImageMotionService.class); } - + @Bean public ClusterDao clusterDao() { return Mockito.mock(ClusterDaoImpl.class); diff --git a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestInProcessAsync.java b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestInProcessAsync.java index 67418717989..df099692db4 100644 --- a/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestInProcessAsync.java +++ b/engine/storage/volume/test/org/apache/cloudstack/storage/volume/test/TestInProcessAsync.java @@ -25,14 +25,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="classpath:/resource/testContext.xml") +@ContextConfiguration(locations = "classpath:/resource/testContext.xml") public class TestInProcessAsync { Server svr; - @Before + + @Before public void setup() { svr = new Server(); } - + @Test public void testRpc() { svr.foo(); diff --git a/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java b/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java index 5de3f6be796..76ce6631c74 100644 --- a/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java +++ b/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java @@ -33,44 +33,45 @@ import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; -@Local(value=StoragePoolAllocator.class) +@Local(value = StoragePoolAllocator.class) public class RandomStoragePoolAllocator extends AbstractStoragePoolAllocator { private static final Logger s_logger = Logger.getLogger(RandomStoragePoolAllocator.class); - - @Override - public List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { - List suitablePools = new ArrayList(); - - long dcId = plan.getDataCenterId(); - Long podId = plan.getPodId(); - Long clusterId = plan.getClusterId(); + @Override + public List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, + DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + + List suitablePools = new ArrayList(); + + long dcId = plan.getDataCenterId(); + Long podId = plan.getPodId(); + Long clusterId = plan.getClusterId(); s_logger.debug("Looking for pools in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId); - List pools = _storagePoolDao.listBy(dcId, podId, clusterId, ScopeType.CLUSTER); + List pools = _storagePoolDao.listBy(dcId, podId, clusterId, ScopeType.CLUSTER); if (pools.size() == 0) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("No storage pools available for allocation, returning"); - } + if (s_logger.isDebugEnabled()) { + s_logger.debug("No storage pools available for allocation, returning"); + } return suitablePools; } - + Collections.shuffle(pools); - if (s_logger.isDebugEnabled()) { + if (s_logger.isDebugEnabled()) { s_logger.debug("RandomStoragePoolAllocator has " + pools.size() + " pools to check for allocation"); } - for (StoragePoolVO pool: pools) { - if(suitablePools.size() == returnUpTo){ - break; - } - StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId()); - - if (filter(avoid, pol, dskCh, plan)) { - suitablePools.add(pol); - } + for (StoragePoolVO pool : pools) { + if (suitablePools.size() == returnUpTo) { + break; + } + StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId()); + + if (filter(avoid, pol, dskCh, plan)) { + suitablePools.add(pol); + } } if (s_logger.isDebugEnabled()) { - s_logger.debug("RandomStoragePoolAllocator returning "+suitablePools.size() +" suitable storage pools"); + s_logger.debug("RandomStoragePoolAllocator returning " + suitablePools.size() + " suitable storage pools"); } return suitablePools; diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java index bc64250d8f8..52595a1bc94 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java @@ -24,8 +24,6 @@ import java.util.Set; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; @@ -45,10 +43,10 @@ import org.apache.cloudstack.storage.image.ImageStoreDriver; import org.apache.cloudstack.storage.image.store.ImageStoreImpl; import org.apache.cloudstack.storage.image.store.TemplateObject; import org.apache.cloudstack.storage.snapshot.SnapshotObject; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotBackupCommand2; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DeleteVolumeCommand; @@ -57,8 +55,6 @@ import com.cloud.agent.api.to.DataObjectType; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.NfsTO; -import com.cloud.api.query.dao.UserVmJoinDao; -import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventUtils; import com.cloud.host.dao.HostDao; @@ -74,43 +70,42 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.download.DownloadMonitor; -import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; -import com.cloud.storage.swift.SwiftManager; import com.cloud.user.Account; import com.cloud.user.dao.AccountDao; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.dao.UserVmDao; public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { - private static final Logger s_logger = Logger - .getLogger(CloudStackImageStoreDriverImpl.class); + private static final Logger s_logger = Logger.getLogger(CloudStackImageStoreDriverImpl.class); @Inject VMTemplateZoneDao templateZoneDao; @Inject VMTemplateDao templateDao; - @Inject DownloadMonitor _downloadMonitor; - @Inject VolumeDao volumeDao; - @Inject VolumeDataStoreDao _volumeStoreDao; - @Inject HostDao hostDao; - @Inject SnapshotDao snapshotDao; - @Inject AgentManager agentMgr; - @Inject SnapshotManager snapshotMgr; - @Inject - private SwiftManager _swiftMgr; @Inject - private S3Manager _s3Mgr; - @Inject AccountDao _accountDao; + DownloadMonitor _downloadMonitor; + @Inject + VolumeDao volumeDao; + @Inject + VolumeDataStoreDao _volumeStoreDao; + @Inject + HostDao hostDao; + @Inject + SnapshotDao snapshotDao; + @Inject + AgentManager agentMgr; + @Inject + SnapshotManager snapshotMgr; + @Inject + AccountDao _accountDao; @Inject SecondaryStorageVmManager _ssvmMgr; @Inject - private AgentManager _agentMgr; - @Inject TemplateDataStoreDao _templateStoreDao; - @Inject EndPointSelector _epSelector; - @Inject DataStoreManager _dataStoreMgr; - + TemplateDataStoreDao _templateStoreDao; + @Inject + EndPointSelector _epSelector; + @Inject + DataStoreManager _dataStoreMgr; @Override public String grantAccess(DataObject data, EndPoint ep) { @@ -123,10 +118,9 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { return null; } - @Override public DataStoreTO getStoreTO(DataStore store) { - ImageStoreImpl nfsStore = (ImageStoreImpl)store; + ImageStoreImpl nfsStore = (ImageStoreImpl) store; NfsTO nfsTO = new NfsTO(); nfsTO.setRole(store.getRole()); nfsTO.setUrl(nfsStore.getUri()); @@ -147,23 +141,21 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { class CreateContext extends AsyncRpcConext { final DataObject data; + public CreateContext(AsyncCompletionCallback callback, DataObject data) { super(callback); this.data = data; } } - @Override - public void createAsync(DataObject data, - AsyncCompletionCallback callback) { - CreateContext context = new CreateContext(callback, data); - AsyncCallbackDispatcher caller = - AsyncCallbackDispatcher.create(this); + public void createAsync(DataObject data, AsyncCompletionCallback callback) { + CreateContext context = new CreateContext(callback, data); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher + .create(this); caller.setContext(context); caller.setCallback(caller.getTarget().createAsyncCallback(null, null)); - if (data.getType() == DataObjectType.TEMPLATE) { _downloadMonitor.downloadTemplateToStorage(data, caller); } else if (data.getType() == DataObjectType.VOLUME) { @@ -171,13 +163,14 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { } } - protected Void createAsyncCallback(AsyncCallbackDispatcher callback, - CreateContext context) { - DownloadAnswer answer = callback.getResult(); - DataObject obj = context.data; - DataStore store = obj.getDataStore(); + protected Void createAsyncCallback( + AsyncCallbackDispatcher callback, + CreateContext context) { + DownloadAnswer answer = callback.getResult(); + DataObject obj = context.data; + DataStore store = obj.getDataStore(); - TemplateDataStoreVO tmpltStoreVO = _templateStoreDao.findByStoreTemplate(store.getId(),obj.getId()); + TemplateDataStoreVO tmpltStoreVO = _templateStoreDao.findByStoreTemplate(store.getId(), obj.getId()); if (tmpltStoreVO != null) { TemplateDataStoreVO updateBuilder = _templateStoreDao.createForUpdate(); updateBuilder.setDownloadPercent(answer.getDownloadPct()); @@ -196,27 +189,26 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { templateDao.update(obj.getId(), tmlptUpdater); } - AsyncCompletionCallback caller = context.getParentCallback(); + AsyncCompletionCallback caller = context.getParentCallback(); - if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR || - answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.ABANDONED || - answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.UNKNOWN) { - CreateCmdResult result = new CreateCmdResult(null, null); + if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR + || answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.ABANDONED + || answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.UNKNOWN) { + CreateCmdResult result = new CreateCmdResult(null, null); result.setSuccess(false); - result.setResult(answer.getErrorString()); - caller.complete(result); - } else if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { - if (answer.getCheckSum() != null) { - VMTemplateVO templateDaoBuilder = templateDao.createForUpdate(); - templateDaoBuilder.setChecksum(answer.getCheckSum()); - templateDao.update(obj.getId(), templateDaoBuilder); - } + result.setResult(answer.getErrorString()); + caller.complete(result); + } else if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { + if (answer.getCheckSum() != null) { + VMTemplateVO templateDaoBuilder = templateDao.createForUpdate(); + templateDaoBuilder.setChecksum(answer.getCheckSum()); + templateDao.update(obj.getId(), templateDaoBuilder); + } - - CreateCmdResult result = new CreateCmdResult(null, answer); - caller.complete(result); - } - return null; + CreateCmdResult result = new CreateCmdResult(null, answer); + caller.complete(result); + } + return null; } private void deleteVolume(DataObject data, AsyncCompletionCallback callback) { @@ -231,22 +223,17 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { DataStore store = _dataStoreMgr.getDataStore(volumeStore.getDataStoreId(), DataStoreRole.Image); EndPoint ep = _epSelector.select(store); - DeleteVolumeCommand dtCommand = new DeleteVolumeCommand( - store.getTO(), volumeStore.getVolumeId(), volumeStore.getInstallPath()); + DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(store.getTO(), volumeStore.getVolumeId(), + volumeStore.getInstallPath()); Answer answer = ep.sendMessage(dtCommand); if (answer == null || !answer.getResult()) { - s_logger.debug("Failed to delete " - + volumeStore - + " due to " - + ((answer == null) ? "answer is null" : answer - .getDetails())); + s_logger.debug("Failed to delete " + volumeStore + " due to " + + ((answer == null) ? "answer is null" : answer.getDetails())); return; } } else if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS) { - s_logger.debug("Volume: " + vol.getName() - + " is currently being uploaded; cant' delete it."); - throw new CloudRuntimeException( - "Please specify a volume that is not currently being uploaded."); + s_logger.debug("Volume: " + vol.getName() + " is currently being uploaded; cant' delete it."); + throw new CloudRuntimeException("Please specify a volume that is not currently being uploaded."); } CommandResult result = new CommandResult(); @@ -275,8 +262,9 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { // TODO: need to understand why we need to mark destroyed in // template_store_ref table here instead of in callback. - // Currently I did that in callback, so I removed previous code to mark template_host_ref - if ( sZoneId != null ){ + // Currently I did that in callback, so I removed previous code to mark + // template_host_ref + if (sZoneId != null) { UsageEventUtils.publishUsageEvent(eventType, account.getId(), sZoneId, templateId, null, null, null); } @@ -284,85 +272,83 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { TemplateDataStoreVO tmplStore = _templateStoreDao.findByStoreTemplate(storeId, templateId); String installPath = tmplStore.getInstallPath(); if (installPath != null) { - DeleteTemplateCommand cmd = new DeleteTemplateCommand(store.getTO(), installPath, template.getId(), template.getAccountId()); - EndPoint ep = _epSelector.select(templateObj); - Answer answer = ep.sendMessage(cmd); + DeleteTemplateCommand cmd = new DeleteTemplateCommand(store.getTO(), installPath, template.getId(), + template.getAccountId()); + EndPoint ep = _epSelector.select(templateObj); + Answer answer = ep.sendMessage(cmd); - if (answer == null || !answer.getResult()) { - s_logger.debug("Failed to deleted template at store: " + store.getName()); - CommandResult result = new CommandResult(); - result.setSuccess(false); - result.setResult("Delete template failed"); - callback.complete(result); + if (answer == null || !answer.getResult()) { + s_logger.debug("Failed to deleted template at store: " + store.getName()); + CommandResult result = new CommandResult(); + result.setSuccess(false); + result.setResult("Delete template failed"); + callback.complete(result); - } else { - s_logger.debug("Deleted template at: " + installPath); - CommandResult result = new CommandResult(); - result.setSuccess(true); - callback.complete(result); - } + } else { + s_logger.debug("Deleted template at: " + installPath); + CommandResult result = new CommandResult(); + result.setSuccess(true); + callback.complete(result); + } - List templateZones = templateZoneDao.listByZoneTemplate(sZoneId, templateId); - if (templateZones != null) { - for (VMTemplateZoneVO templateZone : templateZones) { - templateZoneDao.remove(templateZone.getId()); - } - } + List templateZones = templateZoneDao.listByZoneTemplate(sZoneId, templateId); + if (templateZones != null) { + for (VMTemplateZoneVO templateZone : templateZones) { + templateZoneDao.remove(templateZone.getId()); + } + } } - } private void deleteSnapshot(DataObject data, AsyncCompletionCallback callback) { - SnapshotObject snapshotObj = (SnapshotObject)data; + SnapshotObject snapshotObj = (SnapshotObject) data; DataStore secStore = snapshotObj.getDataStore(); CommandResult result = new CommandResult(); - SnapshotVO snapshot = snapshotObj.getSnapshotVO(); + SnapshotVO snapshot = snapshotObj.getSnapshotVO(); - if (snapshot == null) { - s_logger.debug("Destroying snapshot " + snapshotObj.getId() + " backup failed due to unable to find snapshot "); - result.setResult("Unable to find snapshot: " + snapshotObj.getId()); - callback.complete(result); - return; - } + if (snapshot == null) { + s_logger.debug("Destroying snapshot " + snapshotObj.getId() + + " backup failed due to unable to find snapshot "); + result.setResult("Unable to find snapshot: " + snapshotObj.getId()); + callback.complete(result); + return; + } - try { + try { String backupOfSnapshot = snapshotObj.getPath(); if (backupOfSnapshot == null) { callback.complete(result); return; } - DeleteSnapshotBackupCommand2 cmd = new DeleteSnapshotBackupCommand2( - secStore.getTO(), backupOfSnapshot); - EndPoint ep = _epSelector.select(secStore); - Answer answer = ep.sendMessage(cmd); + DeleteSnapshotBackupCommand2 cmd = new DeleteSnapshotBackupCommand2(secStore.getTO(), backupOfSnapshot); + EndPoint ep = _epSelector.select(secStore); + Answer answer = ep.sendMessage(cmd); - if (answer != null && !answer.getResult()) { - result.setResult(answer.getDetails()); - } - } catch (Exception e) { - s_logger.debug("failed to delete snapshot: " + snapshotObj.getId() + ": " + e.toString()); - result.setResult(e.toString()); - } - callback.complete(result); + if (answer != null && !answer.getResult()) { + result.setResult(answer.getDetails()); + } + } catch (Exception e) { + s_logger.debug("failed to delete snapshot: " + snapshotObj.getId() + ": " + e.toString()); + result.setResult(e.toString()); + } + callback.complete(result); } @Override - public void deleteAsync(DataObject data, - AsyncCompletionCallback callback) { + public void deleteAsync(DataObject data, AsyncCompletionCallback callback) { if (data.getType() == DataObjectType.VOLUME) { deleteVolume(data, callback); } else if (data.getType() == DataObjectType.TEMPLATE) { deleteTemplate(data, callback); } else if (data.getType() == DataObjectType.SNAPSHOT) { - deleteSnapshot(data, callback); + deleteSnapshot(data, callback); } } @Override - public void copyAsync(DataObject srcdata, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { // TODO Auto-generated method stub } @@ -373,11 +359,10 @@ public class CloudStackImageStoreDriverImpl implements ImageStoreDriver { return false; } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } } diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java index d550f0b3b48..a0b64bfc893 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.storage.datastore.lifecycle; import java.net.URI; import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -37,56 +36,51 @@ import org.apache.cloudstack.storage.image.store.lifecycle.ImageStoreLifeCycle; import org.apache.log4j.Logger; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.exception.DiscoveryException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.kvm.discoverer.KvmDummyResourceBase; import com.cloud.resource.Discoverer; -import com.cloud.resource.ResourceListener; import com.cloud.resource.ResourceManager; -import com.cloud.resource.ServerResource; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.utils.UriUtils; public class CloudStackImageStoreLifeCycleImpl implements ImageStoreLifeCycle { - private static final Logger s_logger = Logger - .getLogger(CloudStackImageStoreLifeCycleImpl.class); + private static final Logger s_logger = Logger.getLogger(CloudStackImageStoreLifeCycleImpl.class); @Inject protected ResourceManager _resourceMgr; @Inject - protected ImageStoreDao imageStoreDao; - @Inject - ImageStoreHelper imageStoreHelper; - @Inject - ImageStoreProviderManager imageStoreMgr; + protected ImageStoreDao imageStoreDao; + @Inject + ImageStoreHelper imageStoreHelper; + @Inject + ImageStoreProviderManager imageStoreMgr; protected List _discoverers; + public List getDiscoverers() { return _discoverers; } + public void setDiscoverers(List _discoverers) { this._discoverers = _discoverers; } - public CloudStackImageStoreLifeCycleImpl() { - } - + public CloudStackImageStoreLifeCycleImpl() { + } + @SuppressWarnings("unchecked") @Override public DataStore initialize(Map dsInfos) { Long dcId = (Long) dsInfos.get("zoneId"); String url = (String) dsInfos.get("url"); - String name = (String)dsInfos.get("name"); - if ( name == null ){ + String name = (String) dsInfos.get("name"); + if (name == null) { name = url; } - String providerName = (String)dsInfos.get("providerName"); - DataStoreRole role =(DataStoreRole) dsInfos.get("role"); - Map details = (Map)dsInfos.get("details"); + String providerName = (String) dsInfos.get("providerName"); + DataStoreRole role = (DataStoreRole) dsInfos.get("role"); + Map details = (Map) dsInfos.get("details"); s_logger.info("Trying to add a new host at " + url + " in data center " + dcId); @@ -94,91 +88,81 @@ public class CloudStackImageStoreLifeCycleImpl implements ImageStoreLifeCycle { try { uri = new URI(UriUtils.encodeURIComponent(url)); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("uri.scheme is null " - + url + ", add nfs:// as a prefix"); + throw new InvalidParameterValueException("uri.scheme is null " + url + ", add nfs:// as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { - if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") - || uri.getPath() == null + if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { throw new InvalidParameterValueException( "Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); } } } catch (URISyntaxException e) { - throw new InvalidParameterValueException(url - + " is not a valid uri"); + throw new InvalidParameterValueException(url + " is not a valid uri"); } - if ( dcId == null ){ - throw new InvalidParameterValueException("DataCenter id is null, and cloudstack default image storehas to be associated with a data center"); + if (dcId == null) { + throw new InvalidParameterValueException( + "DataCenter id is null, and cloudstack default image storehas to be associated with a data center"); } - Map imageStoreParameters = new HashMap(); imageStoreParameters.put("name", name); imageStoreParameters.put("zoneId", dcId); imageStoreParameters.put("url", url); imageStoreParameters.put("protocol", uri.getScheme().toLowerCase()); - imageStoreParameters.put("scope", ScopeType.ZONE); // default cloudstack provider only supports zone-wide image store + imageStoreParameters.put("scope", ScopeType.ZONE); // default cloudstack + // provider only + // supports zone-wide + // image store imageStoreParameters.put("providerName", providerName); imageStoreParameters.put("role", role); - ImageStoreVO ids = imageStoreHelper.createImageStore(imageStoreParameters, details); return imageStoreMgr.getImageStore(ids.getId()); } - @Override public boolean attachCluster(DataStore store, ClusterScope scope) { // TODO Auto-generated method stub return false; } - @Override - public boolean attachHost(DataStore store, HostScope scope, - StoragePoolInfo existingInfo) { + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { // TODO Auto-generated method stub return false; } - @Override public boolean attachZone(DataStore dataStore, ZoneScope scope) { // TODO Auto-generated method stub return false; } - @Override public boolean dettach() { // TODO Auto-generated method stub return false; } - @Override public boolean unmanaged() { // TODO Auto-generated method stub return false; } - @Override public boolean maintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean cancelMaintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean deleteDataStore(DataStore store) { // TODO Auto-generated method stub diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackImageStoreProviderImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackImageStoreProviderImpl.java index c9952e2a66d..23de36fb952 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackImageStoreProviderImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackImageStoreProviderImpl.java @@ -82,7 +82,7 @@ public class CloudStackImageStoreProviderImpl implements ImageStoreProvider { @Override public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet(); types.add(DataStoreProviderType.IMAGE); types.add(DataStoreProviderType.ImageCache); return types; @@ -90,15 +90,14 @@ public class CloudStackImageStoreProviderImpl implements ImageStoreProvider { @Override public boolean isScopeSupported(ScopeType scope) { - if ( scope == ScopeType.ZONE) + if (scope == ScopeType.ZONE) return true; return false; } @Override public boolean needDownloadSysTemplate() { - return false; + return false; } - } diff --git a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/driver/S3ImageStoreDriverImpl.java b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/driver/S3ImageStoreDriverImpl.java index 1798ded4d05..0a2a84064e7 100644 --- a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/driver/S3ImageStoreDriverImpl.java +++ b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/driver/S3ImageStoreDriverImpl.java @@ -25,8 +25,6 @@ import java.util.Set; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; @@ -48,10 +46,10 @@ import org.apache.cloudstack.storage.image.ImageStoreDriver; import org.apache.cloudstack.storage.image.store.ImageStoreImpl; import org.apache.cloudstack.storage.image.store.TemplateObject; import org.apache.cloudstack.storage.snapshot.SnapshotObject; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotBackupCommand2; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DeleteVolumeCommand; @@ -61,7 +59,6 @@ import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.S3TO; import com.cloud.api.query.dao.UserVmJoinDao; -import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventUtils; import com.cloud.host.dao.HostDao; @@ -77,46 +74,49 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.download.DownloadMonitor; -import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; -import com.cloud.storage.swift.SwiftManager; import com.cloud.user.Account; import com.cloud.user.dao.AccountDao; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.UserVmVO; import com.cloud.vm.dao.UserVmDao; public class S3ImageStoreDriverImpl implements ImageStoreDriver { - private static final Logger s_logger = Logger - .getLogger(S3ImageStoreDriverImpl.class); + private static final Logger s_logger = Logger.getLogger(S3ImageStoreDriverImpl.class); @Inject VMTemplateZoneDao templateZoneDao; @Inject VMTemplateDao templateDao; - @Inject DownloadMonitor _downloadMonitor; + @Inject + DownloadMonitor _downloadMonitor; @Inject ImageStoreDetailsDao _imageStoreDetailsDao; - @Inject VolumeDao volumeDao; - @Inject VolumeDataStoreDao _volumeStoreDao; - @Inject HostDao hostDao; - @Inject SnapshotDao snapshotDao; - @Inject AgentManager agentMgr; - @Inject SnapshotManager snapshotMgr; - @Inject - private SwiftManager _swiftMgr; @Inject - private S3Manager _s3Mgr; - @Inject AccountDao _accountDao; - @Inject UserVmDao _userVmDao; - @Inject UserVmJoinDao _userVmJoinDao; + VolumeDao volumeDao; + @Inject + VolumeDataStoreDao _volumeStoreDao; + @Inject + HostDao hostDao; + @Inject + SnapshotDao snapshotDao; + @Inject + AgentManager agentMgr; + @Inject + SnapshotManager snapshotMgr; + @Inject + AccountDao _accountDao; + @Inject + UserVmDao _userVmDao; + @Inject + UserVmJoinDao _userVmJoinDao; @Inject SecondaryStorageVmManager _ssvmMgr; @Inject - private AgentManager _agentMgr; - @Inject TemplateDataStoreDao _templateStoreDao; - @Inject EndPointSelector _epSelector; - @Inject DataStoreManager _dataStoreMgr; + TemplateDataStoreDao _templateStoreDao; + @Inject + EndPointSelector _epSelector; + @Inject + DataStoreManager _dataStoreMgr; @Override public String grantAccess(DataObject data, EndPoint ep) { @@ -129,20 +129,20 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { return null; } - @Override public DataStoreTO getStoreTO(DataStore store) { - ImageStoreImpl imgStore = (ImageStoreImpl)store; + ImageStoreImpl imgStore = (ImageStoreImpl) store; Map details = _imageStoreDetailsDao.getDetails(imgStore.getId()); return new S3TO(imgStore.getId(), imgStore.getUuid(), details.get(ApiConstants.S3_ACCESS_KEY), - details.get(ApiConstants.S3_SECRET_KEY), - details.get(ApiConstants.S3_END_POINT), - details.get(ApiConstants.S3_BUCKET_NAME), - details.get(ApiConstants.S3_HTTPS_FLAG) == null ? false : Boolean.parseBoolean(details.get(ApiConstants.S3_HTTPS_FLAG)), - details.get(ApiConstants.S3_CONNECTION_TIMEOUT) == null ? null : Integer.valueOf(details.get(ApiConstants.S3_CONNECTION_TIMEOUT)), - details.get(ApiConstants.S3_MAX_ERROR_RETRY) == null ? null : Integer.valueOf(details.get(ApiConstants.S3_MAX_ERROR_RETRY)), - details.get(ApiConstants.S3_SOCKET_TIMEOUT) == null ? null : Integer.valueOf(details.get(ApiConstants.S3_SOCKET_TIMEOUT)), - imgStore.getCreated()); + details.get(ApiConstants.S3_SECRET_KEY), details.get(ApiConstants.S3_END_POINT), + details.get(ApiConstants.S3_BUCKET_NAME), details.get(ApiConstants.S3_HTTPS_FLAG) == null ? false + : Boolean.parseBoolean(details.get(ApiConstants.S3_HTTPS_FLAG)), + details.get(ApiConstants.S3_CONNECTION_TIMEOUT) == null ? null : Integer.valueOf(details + .get(ApiConstants.S3_CONNECTION_TIMEOUT)), + details.get(ApiConstants.S3_MAX_ERROR_RETRY) == null ? null : Integer.valueOf(details + .get(ApiConstants.S3_MAX_ERROR_RETRY)), + details.get(ApiConstants.S3_SOCKET_TIMEOUT) == null ? null : Integer.valueOf(details + .get(ApiConstants.S3_SOCKET_TIMEOUT)), imgStore.getCreated()); } @@ -160,6 +160,7 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { class CreateContext extends AsyncRpcConext { final DataObject data; + public CreateContext(AsyncCompletionCallback callback, DataObject data) { super(callback); this.data = data; @@ -167,16 +168,13 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { } @Override - public void createAsync(DataObject data, - AsyncCompletionCallback callback) { + public void createAsync(DataObject data, AsyncCompletionCallback callback) { CreateContext context = new CreateContext(callback, data); - AsyncCallbackDispatcher caller = - AsyncCallbackDispatcher.create(this); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); caller.setContext(context); caller.setCallback(caller.getTarget().createAsyncCallback(null, null)); - if (data.getType() == DataObjectType.TEMPLATE) { _downloadMonitor.downloadTemplateToStorage(data, caller); } else if (data.getType() == DataObjectType.VOLUME) { @@ -196,22 +194,17 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { DataStore store = _dataStoreMgr.getDataStore(volumeStore.getDataStoreId(), DataStoreRole.Image); EndPoint ep = _epSelector.select(store); - DeleteVolumeCommand dtCommand = new DeleteVolumeCommand( - store.getTO(), volumeStore.getVolumeId(), volumeStore.getInstallPath()); + DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(store.getTO(), volumeStore.getVolumeId(), + volumeStore.getInstallPath()); Answer answer = ep.sendMessage(dtCommand); if (answer == null || !answer.getResult()) { - s_logger.debug("Failed to delete " - + volumeStore - + " due to " - + ((answer == null) ? "answer is null" : answer - .getDetails())); + s_logger.debug("Failed to delete " + volumeStore + " due to " + + ((answer == null) ? "answer is null" : answer.getDetails())); return; } } else if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS) { - s_logger.debug("Volume: " + vol.getName() - + " is currently being uploaded; cant' delete it."); - throw new CloudRuntimeException( - "Please specify a volume that is not currently being uploaded."); + s_logger.debug("Volume: " + vol.getName() + " is currently being uploaded; cant' delete it."); + throw new CloudRuntimeException("Please specify a volume that is not currently being uploaded."); } _volumeStoreDao.remove(volumeStore.getId()); volumeDao.remove(vol.getId()); @@ -221,14 +214,13 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { } } - protected Void createAsyncCallback(AsyncCallbackDispatcher callback, CreateContext context) { DownloadAnswer answer = callback.getResult(); DataObject obj = context.data; DataStore store = obj.getDataStore(); - TemplateDataStoreVO tmpltStoreVO = _templateStoreDao.findByStoreTemplate(store.getId(),obj.getId()); + TemplateDataStoreVO tmpltStoreVO = _templateStoreDao.findByStoreTemplate(store.getId(), obj.getId()); if (tmpltStoreVO != null) { TemplateDataStoreVO updateBuilder = _templateStoreDao.createForUpdate(); updateBuilder.setDownloadPercent(answer.getDownloadPct()); @@ -249,9 +241,9 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { AsyncCompletionCallback caller = context.getParentCallback(); - if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR || - answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.ABANDONED || - answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.UNKNOWN) { + if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR + || answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.ABANDONED + || answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.UNKNOWN) { CreateCmdResult result = new CreateCmdResult(null, null); result.setSuccess(false); result.setResult(answer.getErrorString()); @@ -263,7 +255,6 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { templateDao.update(obj.getId(), templateDaoBuilder); } - CreateCmdResult result = new CreateCmdResult(null, null); caller.complete(result); } @@ -287,8 +278,8 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { eventType = EventTypes.EVENT_TEMPLATE_DELETE; } - if ( sZoneId != null ){ - //TODO: how to handle region wide usage data where sZoneId == null + if (sZoneId != null) { + // TODO: how to handle region wide usage data where sZoneId == null UsageEventUtils.publishUsageEvent(eventType, account.getId(), sZoneId, templateId, null, null, null); } @@ -296,7 +287,8 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { TemplateDataStoreVO tmplStore = _templateStoreDao.findByStoreTemplate(storeId, templateId); String installPath = tmplStore.getInstallPath(); if (installPath != null) { - DeleteTemplateCommand cmd = new DeleteTemplateCommand(store.getTO(), installPath, template.getId(), template.getAccountId()); + DeleteTemplateCommand cmd = new DeleteTemplateCommand(store.getTO(), installPath, template.getId(), + template.getAccountId()); EndPoint ep = _epSelector.select(templateObj); Answer answer = ep.sendMessage(cmd); @@ -325,13 +317,14 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { } private void deleteSnapshot(DataObject data, AsyncCompletionCallback callback) { - SnapshotObject snapshotObj = (SnapshotObject)data; + SnapshotObject snapshotObj = (SnapshotObject) data; DataStore secStore = snapshotObj.getDataStore(); CommandResult result = new CommandResult(); SnapshotVO snapshot = snapshotObj.getSnapshotVO(); if (snapshot == null) { - s_logger.debug("Destroying snapshot " + snapshotObj.getId() + " backup failed due to unable to find snapshot "); + s_logger.debug("Destroying snapshot " + snapshotObj.getId() + + " backup failed due to unable to find snapshot "); result.setResult("Unable to find snapshot: " + snapshotObj.getId()); callback.complete(result); return; @@ -345,8 +338,7 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { return; } - DeleteSnapshotBackupCommand2 cmd = new DeleteSnapshotBackupCommand2( - secStore.getTO(), backupOfSnapshot); + DeleteSnapshotBackupCommand2 cmd = new DeleteSnapshotBackupCommand2(secStore.getTO(), backupOfSnapshot); EndPoint ep = _epSelector.select(secStore); Answer answer = ep.sendMessage(cmd); @@ -360,22 +352,19 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { callback.complete(result); } - @Override - public void deleteAsync(DataObject data, - AsyncCompletionCallback callback) { + public void deleteAsync(DataObject data, AsyncCompletionCallback callback) { if (data.getType() == DataObjectType.VOLUME) { deleteVolume(data, callback); } else if (data.getType() == DataObjectType.TEMPLATE) { deleteTemplate(data, callback); } else if (data.getType() == DataObjectType.SNAPSHOT) { - deleteSnapshot(data, callback); + deleteSnapshot(data, callback); } } @Override - public void copyAsync(DataObject srcdata, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { // TODO Auto-generated method stub } @@ -386,11 +375,10 @@ public class S3ImageStoreDriverImpl implements ImageStoreDriver { return false; } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } } diff --git a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java index 4ea97e57bfc..674a13d854d 100644 --- a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java @@ -16,9 +16,6 @@ // under the License. package org.apache.cloudstack.storage.datastore.lifecycle; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -38,69 +35,58 @@ import org.apache.cloudstack.storage.image.store.lifecycle.ImageStoreLifeCycle; import org.apache.log4j.Logger; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.exception.DiscoveryException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.kvm.discoverer.KvmDummyResourceBase; import com.cloud.resource.Discoverer; -import com.cloud.resource.ResourceListener; import com.cloud.resource.ResourceManager; -import com.cloud.resource.ServerResource; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.storage.s3.S3Manager; -import com.cloud.utils.UriUtils; public class S3ImageStoreLifeCycleImpl implements ImageStoreLifeCycle { - private static final Logger s_logger = Logger - .getLogger(S3ImageStoreLifeCycleImpl.class); + private static final Logger s_logger = Logger.getLogger(S3ImageStoreLifeCycleImpl.class); @Inject protected ResourceManager _resourceMgr; @Inject - protected ImageStoreDao imageStoreDao; - @Inject - ImageStoreHelper imageStoreHelper; - @Inject - ImageStoreProviderManager imageStoreMgr; + protected ImageStoreDao imageStoreDao; @Inject - S3Manager _s3Mgr; + ImageStoreHelper imageStoreHelper; + @Inject + ImageStoreProviderManager imageStoreMgr; + @Inject + S3Manager _s3Mgr; protected List _discoverers; + public List getDiscoverers() { return _discoverers; } + public void setDiscoverers(List _discoverers) { this._discoverers = _discoverers; } - public S3ImageStoreLifeCycleImpl() { - } - + public S3ImageStoreLifeCycleImpl() { + } + @SuppressWarnings("unchecked") @Override public DataStore initialize(Map dsInfos) { Long dcId = (Long) dsInfos.get("zoneId"); String url = (String) dsInfos.get("url"); - String name = (String)dsInfos.get("name"); - String providerName = (String)dsInfos.get("providerName"); - ScopeType scope = (ScopeType)dsInfos.get("scope"); - DataStoreRole role =(DataStoreRole) dsInfos.get("role"); - Map details = (Map)dsInfos.get("details"); + String name = (String) dsInfos.get("name"); + String providerName = (String) dsInfos.get("providerName"); + ScopeType scope = (ScopeType) dsInfos.get("scope"); + DataStoreRole role = (DataStoreRole) dsInfos.get("role"); + Map details = (Map) dsInfos.get("details"); s_logger.info("Trying to add a S3 store in data center " + dcId); /* - try{ - // verify S3 parameters - _s3Mgr.verifyS3Fields(details); - } - catch (DiscoveryException ex){ - throw new InvalidParameterValueException("failed to verify S3 parameters!"); - } - */ + * try{ // verify S3 parameters _s3Mgr.verifyS3Fields(details); } catch + * (DiscoveryException ex){ throw new + * InvalidParameterValueException("failed to verify S3 parameters!"); } + */ Map imageStoreParameters = new HashMap(); imageStoreParameters.put("name", name); @@ -108,7 +94,7 @@ public class S3ImageStoreLifeCycleImpl implements ImageStoreLifeCycle { imageStoreParameters.put("url", url); String protocol = "http"; String useHttps = details.get(ApiConstants.S3_HTTPS_FLAG); - if (useHttps != null && Boolean.parseBoolean(useHttps)){ + if (useHttps != null && Boolean.parseBoolean(useHttps)) { protocol = "https"; } imageStoreParameters.put("protocol", protocol); @@ -124,57 +110,48 @@ public class S3ImageStoreLifeCycleImpl implements ImageStoreLifeCycle { return imageStoreMgr.getImageStore(ids.getId()); } - @Override public boolean attachCluster(DataStore store, ClusterScope scope) { // TODO Auto-generated method stub return false; } - @Override - public boolean attachHost(DataStore store, HostScope scope, - StoragePoolInfo existingInfo) { + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { // TODO Auto-generated method stub return false; } - @Override public boolean attachZone(DataStore dataStore, ZoneScope scope) { // TODO Auto-generated method stub return false; } - @Override public boolean dettach() { // TODO Auto-generated method stub return false; } - @Override public boolean unmanaged() { // TODO Auto-generated method stub return false; } - @Override public boolean maintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean cancelMaintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean deleteDataStore(DataStore store) { // TODO Auto-generated method stub diff --git a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/provider/S3ImageStoreProviderImpl.java b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/provider/S3ImageStoreProviderImpl.java index 7efb59a6956..8bcdb44f9c0 100644 --- a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/provider/S3ImageStoreProviderImpl.java +++ b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/provider/S3ImageStoreProviderImpl.java @@ -18,12 +18,9 @@ */ package org.apache.cloudstack.storage.datastore.provider; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.UUID; - import javax.inject.Inject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; @@ -83,22 +80,21 @@ public class S3ImageStoreProviderImpl implements ImageStoreProvider { @Override public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet(); types.add(DataStoreProviderType.IMAGE); return types; } @Override public boolean isScopeSupported(ScopeType scope) { - if ( scope == ScopeType.REGION ) + if (scope == ScopeType.REGION) return true; return false; } @Override public boolean needDownloadSysTemplate() { - return true; + return true; } - } diff --git a/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/driver/SampleImageStoreDriverImpl.java b/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/driver/SampleImageStoreDriverImpl.java index 2c7ba1117b4..27e60816155 100644 --- a/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/driver/SampleImageStoreDriverImpl.java +++ b/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/driver/SampleImageStoreDriverImpl.java @@ -45,6 +45,7 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { EndPointSelector selector; @Inject VMTemplateDao imageDataDao; + public SampleImageStoreDriverImpl() { } @@ -53,7 +54,6 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { return null; } - @Override public DataStoreTO getStoreTO(DataStore store) { // TODO Auto-generated method stub @@ -78,9 +78,8 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { } @Override - public void createAsync(DataObject data, - AsyncCompletionCallback callback) { - //for default http data store, can create http based template/iso + public void createAsync(DataObject data, AsyncCompletionCallback callback) { + // for default http data store, can create http based template/iso CreateCmdResult result = new CreateCmdResult("", null); if (!data.getUri().startsWith("http")) { result.setResult("can't register an image which is not a http link"); @@ -89,7 +88,8 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { } if (data.getSize() == null && data.getType() == DataObjectType.TEMPLATE) { - //the template size is unknown during registration, need to find out the size of template + // the template size is unknown during registration, need to find + // out the size of template EndPoint ep = selector.select(data); if (ep == null) { result.setResult("can't find storage client for:" + data.getId() + "," + data.getType()); @@ -97,9 +97,9 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { return; } CreateObjectCommand createCmd = new CreateObjectCommand(data.getTO()); - CreateObjectAnswer answer = (CreateObjectAnswer)ep.sendMessage(createCmd); + CreateObjectAnswer answer = (CreateObjectAnswer) ep.sendMessage(createCmd); if (answer.getResult()) { - //update imagestorevo + // update imagestorevo result = new CreateCmdResult(null, null); } else { @@ -112,8 +112,7 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { } @Override - public void deleteAsync(DataObject data, - AsyncCompletionCallback callback) { + public void deleteAsync(DataObject data, AsyncCompletionCallback callback) { CommandResult result = new CommandResult(); callback.complete(result); } @@ -125,16 +124,14 @@ public class SampleImageStoreDriverImpl implements ImageStoreDriver { } @Override - public void copyAsync(DataObject srcdata, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { // TODO Auto-generated method stub } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } } diff --git a/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SampleImageStoreLifeCycleImpl.java b/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SampleImageStoreLifeCycleImpl.java index fbe9f196a9f..e001c0b4940 100644 --- a/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SampleImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SampleImageStoreLifeCycleImpl.java @@ -34,14 +34,14 @@ import com.cloud.agent.api.StoragePoolInfo; public class SampleImageStoreLifeCycleImpl implements ImageStoreLifeCycle { @Inject - protected ImageStoreDao imageStoreDao; - @Inject - ImageStoreHelper imageStoreHelper; - @Inject - ImageStoreProviderManager imageStoreMgr; - public SampleImageStoreLifeCycleImpl() { - } + protected ImageStoreDao imageStoreDao; + @Inject + ImageStoreHelper imageStoreHelper; + @Inject + ImageStoreProviderManager imageStoreMgr; + public SampleImageStoreLifeCycleImpl() { + } @Override public DataStore initialize(Map dsInfos) { @@ -49,57 +49,48 @@ public class SampleImageStoreLifeCycleImpl implements ImageStoreLifeCycle { return imageStoreMgr.getImageStore(ids.getId()); } - @Override public boolean attachCluster(DataStore store, ClusterScope scope) { // TODO Auto-generated method stub return false; } - @Override - public boolean attachHost(DataStore store, HostScope scope, - StoragePoolInfo existingInfo) { + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { // TODO Auto-generated method stub return false; } - @Override public boolean attachZone(DataStore dataStore, ZoneScope scope) { // TODO Auto-generated method stub return false; } - @Override public boolean dettach() { // TODO Auto-generated method stub return false; } - @Override public boolean unmanaged() { // TODO Auto-generated method stub return false; } - @Override public boolean maintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean cancelMaintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean deleteDataStore(DataStore store) { // TODO Auto-generated method stub diff --git a/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/provider/SampleImageStoreProviderImpl.java b/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/provider/SampleImageStoreProviderImpl.java index 1a0614b5e66..c0c55d667d1 100644 --- a/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/provider/SampleImageStoreProviderImpl.java +++ b/plugins/storage/image/sample/src/org/apache/cloudstack/storage/datastore/provider/SampleImageStoreProviderImpl.java @@ -46,6 +46,7 @@ public class SampleImageStoreProviderImpl implements ImageStoreProvider { ImageStoreProviderManager storeMgr; long id; String uuid; + @Override public DataStoreLifeCycle getDataStoreLifeCycle() { return lifeCycle; @@ -67,7 +68,7 @@ public class SampleImageStoreProviderImpl implements ImageStoreProvider { @Override public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet(); types.add(DataStoreProviderType.IMAGE); return types; } @@ -84,7 +85,7 @@ public class SampleImageStoreProviderImpl implements ImageStoreProvider { @Override public boolean isScopeSupported(ScopeType scope) { - if ( scope == ScopeType.ZONE) + if (scope == ScopeType.ZONE) return true; return false; } @@ -94,5 +95,4 @@ public class SampleImageStoreProviderImpl implements ImageStoreProvider { return false; } - } diff --git a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java index cdfe63e38ac..71b18d557cc 100644 --- a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java +++ b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/driver/SwiftImageStoreDriverImpl.java @@ -50,7 +50,6 @@ import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotBackupCommand2; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DeleteVolumeCommand; @@ -60,7 +59,6 @@ import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.api.query.dao.UserVmJoinDao; -import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventUtils; import com.cloud.host.dao.HostDao; @@ -83,40 +81,50 @@ import com.cloud.storage.swift.SwiftManager; import com.cloud.user.Account; import com.cloud.user.dao.AccountDao; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.UserVmVO; import com.cloud.vm.dao.UserVmDao; public class SwiftImageStoreDriverImpl implements ImageStoreDriver { - private static final Logger s_logger = Logger - .getLogger(SwiftImageStoreDriverImpl.class); + private static final Logger s_logger = Logger.getLogger(SwiftImageStoreDriverImpl.class); @Inject VMTemplateZoneDao templateZoneDao; @Inject VMTemplateDao templateDao; - @Inject DownloadMonitor _downloadMonitor; + @Inject + DownloadMonitor _downloadMonitor; @Inject ImageStoreDetailsDao _imageStoreDetailsDao; - @Inject VolumeDao volumeDao; - @Inject VolumeDataStoreDao _volumeStoreDao; - @Inject HostDao hostDao; - @Inject SnapshotDao snapshotDao; - @Inject AgentManager agentMgr; - @Inject SnapshotManager snapshotMgr; - @Inject + @Inject + VolumeDao volumeDao; + @Inject + VolumeDataStoreDao _volumeStoreDao; + @Inject + HostDao hostDao; + @Inject + SnapshotDao snapshotDao; + @Inject + AgentManager agentMgr; + @Inject + SnapshotManager snapshotMgr; + @Inject private SwiftManager _swiftMgr; @Inject private S3Manager _s3Mgr; - @Inject AccountDao _accountDao; - @Inject UserVmDao _userVmDao; - @Inject UserVmJoinDao _userVmJoinDao; + @Inject + AccountDao _accountDao; + @Inject + UserVmDao _userVmDao; + @Inject + UserVmJoinDao _userVmJoinDao; @Inject SecondaryStorageVmManager _ssvmMgr; @Inject private AgentManager _agentMgr; - @Inject TemplateDataStoreDao _templateStoreDao; - @Inject EndPointSelector _epSelector; - @Inject DataStoreManager _dataStoreMgr; - + @Inject + TemplateDataStoreDao _templateStoreDao; + @Inject + EndPointSelector _epSelector; + @Inject + DataStoreManager _dataStoreMgr; @Override public String grantAccess(DataObject data, EndPoint ep) { @@ -129,14 +137,12 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { return null; } - @Override public DataStoreTO getStoreTO(DataStore store) { - ImageStoreImpl imgStore = (ImageStoreImpl)store; + ImageStoreImpl imgStore = (ImageStoreImpl) store; Map details = _imageStoreDetailsDao.getDetails(imgStore.getId()); return new SwiftTO(imgStore.getId(), imgStore.getUri(), details.get(ApiConstants.ACCOUNT), - details.get(ApiConstants.USERNAME), - details.get(ApiConstants.KEY)); + details.get(ApiConstants.USERNAME), details.get(ApiConstants.KEY)); } @Override @@ -153,6 +159,7 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { class CreateContext extends AsyncRpcConext { final DataObject data; + public CreateContext(AsyncCompletionCallback callback, DataObject data) { super(callback); this.data = data; @@ -160,15 +167,13 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { } @Override - public void createAsync(DataObject data, - AsyncCompletionCallback callback) { + public void createAsync(DataObject data, AsyncCompletionCallback callback) { CreateContext context = new CreateContext(callback, data); - AsyncCallbackDispatcher caller = - AsyncCallbackDispatcher.create(this); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher + .create(this); caller.setContext(context); caller.setCallback(caller.getTarget().createAsyncCallback(null, null)); - if (data.getType() == DataObjectType.TEMPLATE) { _downloadMonitor.downloadTemplateToStorage(data, caller); } else if (data.getType() == DataObjectType.VOLUME) { @@ -182,7 +187,7 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { DataObject obj = context.data; DataStore store = obj.getDataStore(); - TemplateDataStoreVO tmpltStoreVO = _templateStoreDao.findByStoreTemplate(store.getId(),obj.getId()); + TemplateDataStoreVO tmpltStoreVO = _templateStoreDao.findByStoreTemplate(store.getId(), obj.getId()); if (tmpltStoreVO != null) { TemplateDataStoreVO updateBuilder = _templateStoreDao.createForUpdate(); updateBuilder.setDownloadPercent(answer.getDownloadPct()); @@ -203,11 +208,11 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { AsyncCompletionCallback caller = context.getParentCallback(); - if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR || - answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.ABANDONED || - answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.UNKNOWN) { + if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR + || answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.ABANDONED + || answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.UNKNOWN) { CreateCmdResult result = new CreateCmdResult(null, null); - //result.setSucess(false); + // result.setSucess(false); result.setResult(answer.getErrorString()); caller.complete(result); } else if (answer.getDownloadStatus() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { @@ -217,7 +222,6 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { templateDao.update(obj.getId(), templateDaoBuilder); } - CreateCmdResult result = new CreateCmdResult(null, null); caller.complete(result); } @@ -237,22 +241,17 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { DataStore store = this._dataStoreMgr.getDataStore(volumeStore.getDataStoreId(), DataStoreRole.Image); EndPoint ep = _epSelector.select(store); - DeleteVolumeCommand dtCommand = new DeleteVolumeCommand( - store.getTO(), volumeStore.getVolumeId(), volumeStore.getInstallPath()); + DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(store.getTO(), volumeStore.getVolumeId(), + volumeStore.getInstallPath()); Answer answer = ep.sendMessage(dtCommand); if (answer == null || !answer.getResult()) { - s_logger.debug("Failed to delete " - + volumeStore - + " due to " - + ((answer == null) ? "answer is null" : answer - .getDetails())); + s_logger.debug("Failed to delete " + volumeStore + " due to " + + ((answer == null) ? "answer is null" : answer.getDetails())); return; } } else if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS) { - s_logger.debug("Volume: " + vol.getName() - + " is currently being uploaded; cant' delete it."); - throw new CloudRuntimeException( - "Please specify a volume that is not currently being uploaded."); + s_logger.debug("Volume: " + vol.getName() + " is currently being uploaded; cant' delete it."); + throw new CloudRuntimeException("Please specify a volume that is not currently being uploaded."); } _volumeStoreDao.remove(volumeStore.getId()); volumeDao.remove(vol.getId()); @@ -281,8 +280,9 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { // TODO: need to understand why we need to mark destroyed in // template_store_ref table here instead of in callback. - // Currently I did that in callback, so I removed previous code to mark template_host_ref - if (sZoneId != null){ + // Currently I did that in callback, so I removed previous code to mark + // template_host_ref + if (sZoneId != null) { UsageEventUtils.publishUsageEvent(eventType, account.getId(), sZoneId, templateId, null, null, null); } @@ -290,7 +290,8 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { TemplateDataStoreVO tmplStore = _templateStoreDao.findByStoreTemplate(storeId, templateId); String installPath = tmplStore.getInstallPath(); if (installPath != null) { - DeleteTemplateCommand cmd = new DeleteTemplateCommand(store.getTO(), installPath, template.getId(), template.getAccountId()); + DeleteTemplateCommand cmd = new DeleteTemplateCommand(store.getTO(), installPath, template.getId(), + template.getAccountId()); EndPoint ep = _epSelector.select(templateObj); Answer answer = ep.sendMessage(cmd); @@ -316,16 +317,17 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { } } } - } + } private void deleteSnapshot(DataObject data, AsyncCompletionCallback callback) { - SnapshotObject snapshotObj = (SnapshotObject)data; + SnapshotObject snapshotObj = (SnapshotObject) data; DataStore secStore = snapshotObj.getDataStore(); CommandResult result = new CommandResult(); SnapshotVO snapshot = snapshotObj.getSnapshotVO(); if (snapshot == null) { - s_logger.debug("Destroying snapshot " + snapshotObj.getId() + " backup failed due to unable to find snapshot "); + s_logger.debug("Destroying snapshot " + snapshotObj.getId() + + " backup failed due to unable to find snapshot "); result.setResult("Unable to find snapshot: " + snapshotObj.getId()); callback.complete(result); return; @@ -338,8 +340,7 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { return; } - DeleteSnapshotBackupCommand2 cmd = new DeleteSnapshotBackupCommand2( - secStore.getTO(), backupOfSnapshot); + DeleteSnapshotBackupCommand2 cmd = new DeleteSnapshotBackupCommand2(secStore.getTO(), backupOfSnapshot); EndPoint ep = _epSelector.select(secStore); Answer answer = ep.sendMessage(cmd); @@ -354,20 +355,18 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { } @Override - public void deleteAsync(DataObject data, - AsyncCompletionCallback callback) { + public void deleteAsync(DataObject data, AsyncCompletionCallback callback) { if (data.getType() == DataObjectType.VOLUME) { deleteVolume(data, callback); } else if (data.getType() == DataObjectType.TEMPLATE) { deleteTemplate(data, callback); } else if (data.getType() == DataObjectType.SNAPSHOT) { - deleteSnapshot(data, callback); + deleteSnapshot(data, callback); } } @Override - public void copyAsync(DataObject srcdata, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { // TODO Auto-generated method stub } @@ -378,11 +377,10 @@ public class SwiftImageStoreDriverImpl implements ImageStoreDriver { return false; } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } } diff --git a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/lifecycle/SwiftImageStoreLifeCycleImpl.java b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/lifecycle/SwiftImageStoreLifeCycleImpl.java index 3fc68a1e8fe..3ba3b3133d0 100644 --- a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/lifecycle/SwiftImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/lifecycle/SwiftImageStoreLifeCycleImpl.java @@ -16,9 +16,6 @@ // under the License. package org.apache.cloudstack.storage.datastore.lifecycle; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -37,55 +34,47 @@ import org.apache.cloudstack.storage.image.store.lifecycle.ImageStoreLifeCycle; import org.apache.log4j.Logger; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.exception.DiscoveryException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.kvm.discoverer.KvmDummyResourceBase; import com.cloud.resource.Discoverer; -import com.cloud.resource.ResourceListener; import com.cloud.resource.ResourceManager; -import com.cloud.resource.ServerResource; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; -import com.cloud.utils.UriUtils; public class SwiftImageStoreLifeCycleImpl implements ImageStoreLifeCycle { - private static final Logger s_logger = Logger - .getLogger(SwiftImageStoreLifeCycleImpl.class); + private static final Logger s_logger = Logger.getLogger(SwiftImageStoreLifeCycleImpl.class); @Inject protected ResourceManager _resourceMgr; @Inject - protected ImageStoreDao imageStoreDao; - @Inject - ImageStoreHelper imageStoreHelper; - @Inject - ImageStoreProviderManager imageStoreMgr; + protected ImageStoreDao imageStoreDao; + @Inject + ImageStoreHelper imageStoreHelper; + @Inject + ImageStoreProviderManager imageStoreMgr; protected List _discoverers; + public List getDiscoverers() { return _discoverers; } + public void setDiscoverers(List _discoverers) { this._discoverers = _discoverers; } - public SwiftImageStoreLifeCycleImpl() { - } - + public SwiftImageStoreLifeCycleImpl() { + } @Override public DataStore initialize(Map dsInfos) { Long dcId = (Long) dsInfos.get("zoneId"); String url = (String) dsInfos.get("url"); - String name = (String)dsInfos.get("name"); - ScopeType scope = (ScopeType)dsInfos.get("scope"); - String providerName = (String)dsInfos.get("providerName"); - DataStoreRole role =(DataStoreRole) dsInfos.get("role"); + String name = (String) dsInfos.get("name"); + ScopeType scope = (ScopeType) dsInfos.get("scope"); + String providerName = (String) dsInfos.get("providerName"); + DataStoreRole role = (DataStoreRole) dsInfos.get("role"); - Map details = (Map)dsInfos.get("details"); + Map details = (Map) dsInfos.get("details"); s_logger.info("Trying to add a swift store at " + url + " in data center " + dcId); @@ -107,57 +96,48 @@ public class SwiftImageStoreLifeCycleImpl implements ImageStoreLifeCycle { return imageStoreMgr.getImageStore(ids.getId()); } - @Override public boolean attachCluster(DataStore store, ClusterScope scope) { // TODO Auto-generated method stub return false; } - @Override - public boolean attachHost(DataStore store, HostScope scope, - StoragePoolInfo existingInfo) { + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { // TODO Auto-generated method stub return false; } - @Override public boolean attachZone(DataStore dataStore, ZoneScope scope) { // TODO Auto-generated method stub return false; } - @Override public boolean dettach() { // TODO Auto-generated method stub return false; } - @Override public boolean unmanaged() { // TODO Auto-generated method stub return false; } - @Override public boolean maintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean cancelMaintain(DataStore store) { // TODO Auto-generated method stub return false; } - @Override public boolean deleteDataStore(DataStore store) { // TODO Auto-generated method stub diff --git a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/provider/SwiftImageStoreProviderImpl.java b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/provider/SwiftImageStoreProviderImpl.java index bd6f9f0c9f8..788eebcd145 100644 --- a/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/provider/SwiftImageStoreProviderImpl.java +++ b/plugins/storage/image/swift/src/org/apache/cloudstack/storage/datastore/provider/SwiftImageStoreProviderImpl.java @@ -82,22 +82,21 @@ public class SwiftImageStoreProviderImpl implements ImageStoreProvider { @Override public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet(); types.add(DataStoreProviderType.IMAGE); return types; } @Override public boolean isScopeSupported(ScopeType scope) { - if ( scope == ScopeType.REGION ) + if (scope == ScopeType.REGION) return true; return false; } @Override public boolean needDownloadSysTemplate() { - return true; + return true; } - } diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java index e801429fcd6..4c2f3894ef2 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java @@ -60,185 +60,186 @@ import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.vm.dao.VMInstanceDao; public class CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver { - private static final Logger s_logger = Logger - .getLogger(CloudStackPrimaryDataStoreDriverImpl.class); - @Inject DiskOfferingDao diskOfferingDao; - @Inject VMTemplateDao templateDao; - @Inject VolumeDao volumeDao; - @Inject HostDao hostDao; - @Inject StorageManager storageMgr; - @Inject VolumeManager volumeMgr; - @Inject VMInstanceDao vmDao; - @Inject SnapshotDao snapshotDao; - @Inject PrimaryDataStoreDao primaryStoreDao; - @Inject SnapshotManager snapshotMgr; - @Inject EndPointSelector epSelector; - @Override - public String grantAccess(DataObject data, EndPoint ep) { - // TODO Auto-generated method stub - return null; - } + private static final Logger s_logger = Logger.getLogger(CloudStackPrimaryDataStoreDriverImpl.class); + @Inject + DiskOfferingDao diskOfferingDao; + @Inject + VMTemplateDao templateDao; + @Inject + VolumeDao volumeDao; + @Inject + HostDao hostDao; + @Inject + StorageManager storageMgr; + @Inject + VolumeManager volumeMgr; + @Inject + VMInstanceDao vmDao; + @Inject + SnapshotDao snapshotDao; + @Inject + PrimaryDataStoreDao primaryStoreDao; + @Inject + SnapshotManager snapshotMgr; + @Inject + EndPointSelector epSelector; - @Override + @Override + public String grantAccess(DataObject data, EndPoint ep) { + // TODO Auto-generated method stub + return null; + } + + @Override public DataTO getTO(DataObject data) { return null; } - - @Override + @Override public DataStoreTO getStoreTO(DataStore store) { // TODO Auto-generated method stub return null; } @Override - public boolean revokeAccess(DataObject data, EndPoint ep) { - // TODO Auto-generated method stub - return false; - } + public boolean revokeAccess(DataObject data, EndPoint ep) { + // TODO Auto-generated method stub + return false; + } - @Override - public Set listObjects(DataStore store) { - // TODO Auto-generated method stub - return null; - } + @Override + public Set listObjects(DataStore store) { + // TODO Auto-generated method stub + return null; + } - public Answer createVolume( - VolumeInfo volume) throws StorageUnavailableException { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Creating volume: " + volume); - } + public Answer createVolume(VolumeInfo volume) throws StorageUnavailableException { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Creating volume: " + volume); + } - CreateObjectCommand cmd = new CreateObjectCommand(volume.getTO()); - EndPoint ep = epSelector.select(volume); - Answer answer = ep.sendMessage(cmd); - return answer; - } + CreateObjectCommand cmd = new CreateObjectCommand(volume.getTO()); + EndPoint ep = epSelector.select(volume); + Answer answer = ep.sendMessage(cmd); + return answer; + } - @Override - public void createAsync(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub - String errMsg = null; - Answer answer = null; - if (data.getType() == DataObjectType.VOLUME) { - try { - answer = createVolume((VolumeInfo)data); - } catch (StorageUnavailableException e) { - s_logger.debug("failed to create volume", e); - errMsg = e.toString(); - } catch (Exception e) { - s_logger.debug("failed to create volume", e); - errMsg = e.toString(); - } - } - CreateCmdResult result = new CreateCmdResult(null, answer); - if (errMsg != null) { - result.setResult(errMsg); - } + @Override + public void createAsync(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub + String errMsg = null; + Answer answer = null; + if (data.getType() == DataObjectType.VOLUME) { + try { + answer = createVolume((VolumeInfo) data); + } catch (StorageUnavailableException e) { + s_logger.debug("failed to create volume", e); + errMsg = e.toString(); + } catch (Exception e) { + s_logger.debug("failed to create volume", e); + errMsg = e.toString(); + } + } + CreateCmdResult result = new CreateCmdResult(null, answer); + if (errMsg != null) { + result.setResult(errMsg); + } - callback.complete(result); - } - - @Override - public void deleteAsync(DataObject data, - AsyncCompletionCallback callback) { - DeleteCommand cmd = new DeleteCommand(data.getTO()); - - CommandResult result = new CommandResult(); - try { - EndPoint ep = epSelector.select(data); - Answer answer = ep.sendMessage(cmd); - if (answer != null && !answer.getResult()) { - result.setResult(answer.getDetails()); - } - } catch (Exception ex) { - s_logger.debug("Unable to destoy volume" + data.getId(), ex); - result.setResult(ex.toString()); - } - callback.complete(result); - } - - @Override - public void copyAsync(DataObject srcdata, DataObject destData, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub - - } - - @Override - public boolean canCopy(DataObject srcData, DataObject destData) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void takeSnapshot(SnapshotInfo snapshot, - AsyncCompletionCallback callback) { - CreateCmdResult result = null; - try { - DataTO snapshotTO = snapshot.getTO(); - - CreateObjectCommand cmd = new CreateObjectCommand(snapshotTO); - EndPoint ep = this.epSelector.select(snapshot); - Answer answer = ep.sendMessage(cmd); - - result = new CreateCmdResult(null, answer); - if (answer != null && !answer.getResult()) { - result.setResult(answer.getDetails()); - } - - callback.complete(result); - return; - } catch (Exception e) { - s_logger.debug("Failed to take snapshot: " + snapshot.getId(), e); - result = new CreateCmdResult(null, null); - result.setResult(e.toString()); - } callback.complete(result); - } + } - @Override - public void revertSnapshot(SnapshotInfo snapshot, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void deleteAsync(DataObject data, AsyncCompletionCallback callback) { + DeleteCommand cmd = new DeleteCommand(data.getTO()); - } + CommandResult result = new CommandResult(); + try { + EndPoint ep = epSelector.select(data); + Answer answer = ep.sendMessage(cmd); + if (answer != null && !answer.getResult()) { + result.setResult(answer.getDetails()); + } + } catch (Exception ex) { + s_logger.debug("Unable to destoy volume" + data.getId(), ex); + result.setResult(ex.toString()); + } + callback.complete(result); + } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - VolumeObject vol = (VolumeObject)data; - StoragePool pool = (StoragePool)data.getDataStore(); - ResizeVolumePayload resizeParameter = (ResizeVolumePayload)vol.getpayload(); + @Override + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - ResizeVolumeCommand resizeCmd = new ResizeVolumeCommand( - vol.getPath(), new StorageFilerTO(pool), vol.getSize(), - resizeParameter.newSize, resizeParameter.shrinkOk, resizeParameter.instanceName); - CreateCmdResult result = new CreateCmdResult(null, null); - try { - ResizeVolumeAnswer answer = (ResizeVolumeAnswer) this.storageMgr.sendToPool(pool, - resizeParameter.hosts, resizeCmd); - if (answer != null && answer.getResult()) { - long finalSize = answer.getNewSize(); - s_logger.debug("Resize: volume started at size " + vol.getSize() - + " and ended at size " + finalSize); + } - vol.setSize(finalSize); - vol.update(); - } else if (answer != null) { - result.setResult(answer.getDetails()); - } else { - s_logger.debug("return a null answer, mark it as failed for unknown reason"); - result.setResult("return a null answer, mark it as failed for unknown reason"); - } + @Override + public boolean canCopy(DataObject srcData, DataObject destData) { + // TODO Auto-generated method stub + return false; + } - } catch (Exception e) { - s_logger.debug("sending resize command failed", e); - result.setResult(e.toString()); - } + @Override + public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) { + CreateCmdResult result = null; + try { + DataTO snapshotTO = snapshot.getTO(); - callback.complete(result); - } + CreateObjectCommand cmd = new CreateObjectCommand(snapshotTO); + EndPoint ep = this.epSelector.select(snapshot); + Answer answer = ep.sendMessage(cmd); + + result = new CreateCmdResult(null, answer); + if (answer != null && !answer.getResult()) { + result.setResult(answer.getDetails()); + } + + callback.complete(result); + return; + } catch (Exception e) { + s_logger.debug("Failed to take snapshot: " + snapshot.getId(), e); + result = new CreateCmdResult(null, null); + result.setResult(e.toString()); + } + callback.complete(result); + } + + @Override + public void revertSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub + + } + + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + VolumeObject vol = (VolumeObject) data; + StoragePool pool = (StoragePool) data.getDataStore(); + ResizeVolumePayload resizeParameter = (ResizeVolumePayload) vol.getpayload(); + + ResizeVolumeCommand resizeCmd = new ResizeVolumeCommand(vol.getPath(), new StorageFilerTO(pool), vol.getSize(), + resizeParameter.newSize, resizeParameter.shrinkOk, resizeParameter.instanceName); + CreateCmdResult result = new CreateCmdResult(null, null); + try { + ResizeVolumeAnswer answer = (ResizeVolumeAnswer) this.storageMgr.sendToPool(pool, resizeParameter.hosts, + resizeCmd); + if (answer != null && answer.getResult()) { + long finalSize = answer.getNewSize(); + s_logger.debug("Resize: volume started at size " + vol.getSize() + " and ended at size " + finalSize); + + vol.setSize(finalSize); + vol.update(); + } else if (answer != null) { + result.setResult(answer.getDetails()); + } else { + s_logger.debug("return a null answer, mark it as failed for unknown reason"); + result.setResult("return a null answer, mark it as failed for unknown reason"); + } + + } catch (Exception e) { + s_logger.debug("sending resize command failed", e); + result.setResult(e.toString()); + } + + callback.complete(result); + } } diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java index e6bdaed7987..693ab01c73b 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java @@ -55,8 +55,6 @@ import com.cloud.resource.ResourceManager; import com.cloud.server.ManagementServer; import com.cloud.storage.OCFS2Manager; import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.ScopeType; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolAutomation; @@ -77,10 +75,8 @@ import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; -public class CloudStackPrimaryDataStoreLifeCycleImpl implements - PrimaryDataStoreLifeCycle { - private static final Logger s_logger = Logger - .getLogger(CloudStackPrimaryDataStoreLifeCycleImpl.class); +public class CloudStackPrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { + private static final Logger s_logger = Logger.getLogger(CloudStackPrimaryDataStoreLifeCycleImpl.class); @Inject protected ResourceManager _resourceMgr; protected List _discoverers; @@ -95,7 +91,6 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements @Inject StorageManager storageMgr; - @Inject VolumeDao volumeDao; @Inject @@ -126,16 +121,16 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements @Inject StoragePoolAutomation storagePoolAutmation; + @SuppressWarnings("unchecked") @Override public DataStore initialize(Map dsInfos) { Long clusterId = (Long) dsInfos.get("clusterId"); Long podId = (Long) dsInfos.get("podId"); Long zoneId = (Long) dsInfos.get("zoneId"); String url = (String) dsInfos.get("url"); - String providerName = (String)dsInfos.get("providerName"); + String providerName = (String) dsInfos.get("providerName"); if (clusterId != null && podId == null) { - throw new InvalidParameterValueException( - "Cluster id requires pod id"); + throw new InvalidParameterValueException("Cluster id requires pod id"); } PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); @@ -144,15 +139,12 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements try { uri = new URI(UriUtils.encodeURIComponent(url)); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("scheme is null " - + url + ", add nfs:// as a prefix"); + throw new InvalidParameterValueException("scheme is null " + url + ", add nfs:// as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { String uriHost = uri.getHost(); String uriPath = uri.getPath(); - if (uriHost == null || uriPath == null - || uriHost.trim().isEmpty() || uriPath.trim().isEmpty()) { - throw new InvalidParameterValueException( - "host or path is null, should be nfs://hostname/path"); + if (uriHost == null || uriPath == null || uriHost.trim().isEmpty() || uriPath.trim().isEmpty()) { + throw new InvalidParameterValueException("host or path is null, should be nfs://hostname/path"); } } else if (uri.getScheme().equalsIgnoreCase("sharedMountPoint")) { String uriPath = uri.getPath(); @@ -163,18 +155,15 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements } else if (uri.getScheme().equalsIgnoreCase("rbd")) { String uriPath = uri.getPath(); if (uriPath == null) { - throw new InvalidParameterValueException( - "host or path is null, should be rbd://hostname/pool"); + throw new InvalidParameterValueException("host or path is null, should be rbd://hostname/pool"); } } } catch (URISyntaxException e) { - throw new InvalidParameterValueException(url - + " is not a valid uri"); + throw new InvalidParameterValueException(url + " is not a valid uri"); } String tags = (String) dsInfos.get("tags"); - Map details = (Map) dsInfos - .get("details"); + Map details = (Map) dsInfos.get("details"); parameters.setTags(tags); parameters.setDetails(details); @@ -188,10 +177,8 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements } String userInfo = uri.getUserInfo(); int port = uri.getPort(); - StoragePool pool = null; if (s_logger.isDebugEnabled()) { - s_logger.debug("createPool Params @ scheme - " + scheme - + " storageHost - " + storageHost + " hostPath - " + s_logger.debug("createPool Params @ scheme - " + scheme + " storageHost - " + storageHost + " hostPath - " + hostPath + " port - " + port); } if (scheme.equalsIgnoreCase("nfs")) { @@ -242,8 +229,7 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements } if (lun != -1) { if (clusterId == null) { - throw new IllegalArgumentException( - "IscsiLUN need to have clusters specified"); + throw new IllegalArgumentException("IscsiLUN need to have clusters specified"); } hostPath.replaceFirst("/", ""); parameters.setType(StoragePoolType.IscsiLUN); @@ -256,14 +242,11 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements try { pools = discoverer.find(zoneId, podId, uri, details); } catch (DiscoveryException e) { - throw new IllegalArgumentException( - "Not enough information for discovery " + uri, - e); + throw new IllegalArgumentException("Not enough information for discovery " + uri, e); } if (pools != null) { - Map.Entry> entry = pools - .entrySet().iterator().next(); - pool = entry.getKey(); + Map.Entry> entry = pools.entrySet().iterator() + .next(); details = entry.getValue(); break; } @@ -297,19 +280,17 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements parameters.setPort(0); parameters.setPath(hostPath); } else { - s_logger.warn("Unable to figure out the scheme for URI: " + uri); - throw new IllegalArgumentException( - "Unable to figure out the scheme for URI: " + uri); + s_logger.warn("Unable to figure out the scheme for URI: " + uri); + throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri); } } if (localStorage == null) { - List pools = primaryDataStoreDao - .listPoolByHostPath(storageHost, hostPath); + List pools = primaryDataStoreDao.listPoolByHostPath(storageHost, hostPath); if (!pools.isEmpty() && !scheme.equalsIgnoreCase("sharedmountpoint")) { Long oldPodId = pools.get(0).getPodId(); - throw new CloudRuntimeException("Storage pool " + uri - + " already in use by another pod (id=" + oldPodId + ")"); + throw new CloudRuntimeException("Storage pool " + uri + " already in use by another pod (id=" + + oldPodId + ")"); } } @@ -317,29 +298,23 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements String uuid = null; if (existingUuid != null) { - uuid = (String)existingUuid; - } else if (scheme.equalsIgnoreCase("sharedmountpoint") - || scheme.equalsIgnoreCase("clvm")) { + uuid = (String) existingUuid; + } else if (scheme.equalsIgnoreCase("sharedmountpoint") || scheme.equalsIgnoreCase("clvm")) { uuid = UUID.randomUUID().toString(); } else if (scheme.equalsIgnoreCase("PreSetup")) { uuid = hostPath.replace("/", ""); } else { - uuid = UUID.nameUUIDFromBytes( - new String(storageHost + hostPath).getBytes()).toString(); + uuid = UUID.nameUUIDFromBytes(new String(storageHost + hostPath).getBytes()).toString(); } - - List spHandles = primaryDataStoreDao - .findIfDuplicatePoolsExistByUUID(uuid); + List spHandles = primaryDataStoreDao.findIfDuplicatePoolsExistByUUID(uuid); if ((spHandles != null) && (spHandles.size() > 0)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Another active pool with the same uuid already exists"); } - throw new CloudRuntimeException( - "Another active pool with the same uuid already exists"); + throw new CloudRuntimeException("Another active pool with the same uuid already exists"); } - String poolName = (String) dsInfos.get("name"); parameters.setUuid(uuid); @@ -353,20 +328,13 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements } protected boolean createStoragePool(long hostId, StoragePool pool) { - s_logger.debug("creating pool " + pool.getName() + " on host " - + hostId); - if (pool.getPoolType() != StoragePoolType.NetworkFilesystem - && pool.getPoolType() != StoragePoolType.Filesystem - && pool.getPoolType() != StoragePoolType.IscsiLUN - && pool.getPoolType() != StoragePoolType.Iscsi - && pool.getPoolType() != StoragePoolType.VMFS - && pool.getPoolType() != StoragePoolType.SharedMountPoint - && pool.getPoolType() != StoragePoolType.PreSetup - && pool.getPoolType() != StoragePoolType.OCFS2 - && pool.getPoolType() != StoragePoolType.RBD - && pool.getPoolType() != StoragePoolType.CLVM) { - s_logger.warn(" Doesn't support storage pool type " - + pool.getPoolType()); + s_logger.debug("creating pool " + pool.getName() + " on host " + hostId); + if (pool.getPoolType() != StoragePoolType.NetworkFilesystem && pool.getPoolType() != StoragePoolType.Filesystem + && pool.getPoolType() != StoragePoolType.IscsiLUN && pool.getPoolType() != StoragePoolType.Iscsi + && pool.getPoolType() != StoragePoolType.VMFS && pool.getPoolType() != StoragePoolType.SharedMountPoint + && pool.getPoolType() != StoragePoolType.PreSetup && pool.getPoolType() != StoragePoolType.OCFS2 + && pool.getPoolType() != StoragePoolType.RBD && pool.getPoolType() != StoragePoolType.CLVM) { + s_logger.warn(" Doesn't support storage pool type " + pool.getPoolType()); return false; } CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, pool); @@ -377,8 +345,7 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements primaryDataStoreDao.expunge(pool.getId()); String msg = ""; if (answer != null) { - msg = "Can not create storage pool through host " + hostId - + " due to " + answer.getDetails(); + msg = "Can not create storage pool through host " + hostId + " due to " + answer.getDetails(); s_logger.warn(msg); } else { msg = "Can not create storage pool through host " + hostId @@ -393,19 +360,15 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements public boolean attachCluster(DataStore store, ClusterScope scope) { PrimaryDataStoreInfo primarystore = (PrimaryDataStoreInfo) store; // Check if there is host up in this cluster - List allHosts = _resourceMgr.listAllUpAndEnabledHosts( - Host.Type.Routing, primarystore.getClusterId(), + List allHosts = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.Routing, primarystore.getClusterId(), primarystore.getPodId(), primarystore.getDataCenterId()); if (allHosts.isEmpty()) { - throw new CloudRuntimeException( - "No host up to associate a storage pool with in cluster " - + primarystore.getClusterId()); + throw new CloudRuntimeException("No host up to associate a storage pool with in cluster " + + primarystore.getClusterId()); } - if (primarystore.getPoolType() == StoragePoolType.OCFS2 - && !_ocfs2Mgr.prepareNodes(allHosts, primarystore)) { - s_logger.warn("Can not create storage pool " + primarystore - + " on cluster " + primarystore.getClusterId()); + if (primarystore.getPoolType() == StoragePoolType.OCFS2 && !_ocfs2Mgr.prepareNodes(allHosts, primarystore)) { + s_logger.warn("Can not create storage pool " + primarystore + " on cluster " + primarystore.getClusterId()); primaryDataStoreDao.expunge(primarystore.getId()); return false; } @@ -422,18 +385,16 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements List poolHosts = new ArrayList(); for (HostVO h : allHosts) { try { - this.storageMgr.connectHostToSharedPool(h.getId(), - primarystore.getId()); + this.storageMgr.connectHostToSharedPool(h.getId(), primarystore.getId()); poolHosts.add(h); } catch (Exception e) { - s_logger.warn("Unable to establish a connection between " + h - + " and " + primarystore, e); + s_logger.warn("Unable to establish a connection between " + h + " and " + primarystore, e); } } if (poolHosts.isEmpty()) { - s_logger.warn("No host can access storage pool " + primarystore - + " on cluster " + primarystore.getClusterId()); + s_logger.warn("No host can access storage pool " + primarystore + " on cluster " + + primarystore.getClusterId()); primaryDataStoreDao.expunge(primarystore.getId()); return false; } @@ -444,17 +405,16 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements @Override public boolean attachZone(DataStore dataStore, ZoneScope scope) { - List hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType.KVM, scope.getScopeId()); - for (HostVO host : hosts) { - try { - this.storageMgr.connectHostToSharedPool(host.getId(), - dataStore.getId()); - } catch (Exception e) { - s_logger.warn("Unable to establish a connection between " + host - + " and " + dataStore, e); - } - } - this.dataStoreHelper.attachZone(dataStore); + List hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType.KVM, + scope.getScopeId()); + for (HostVO host : hosts) { + try { + this.storageMgr.connectHostToSharedPool(host.getId(), dataStore.getId()); + } catch (Exception e) { + s_logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); + } + } + this.dataStoreHelper.attachZone(dataStore); return true; } @@ -487,16 +447,13 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements @DB @Override public boolean deleteDataStore(DataStore store) { - List hostPoolRecords = this._storagePoolHostDao - .listByPoolId(store.getId()); - StoragePool pool = (StoragePool)store; + List hostPoolRecords = this._storagePoolHostDao.listByPoolId(store.getId()); + StoragePool pool = (StoragePool) store; boolean deleteFlag = false; // Remove the SR associated with the Xenserver for (StoragePoolHostVO host : hostPoolRecords) { - DeleteStoragePoolCommand deleteCmd = new DeleteStoragePoolCommand( - pool); - final Answer answer = agentMgr.easySend(host.getHostId(), - deleteCmd); + DeleteStoragePoolCommand deleteCmd = new DeleteStoragePoolCommand(pool); + final Answer answer = agentMgr.easySend(host.getHostId(), deleteCmd); if (answer != null && answer.getResult()) { deleteFlag = true; diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackPrimaryDataStoreProviderImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackPrimaryDataStoreProviderImpl.java index fed41da74fe..410416c4499 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackPrimaryDataStoreProviderImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/provider/CloudStackPrimaryDataStoreProviderImpl.java @@ -32,8 +32,7 @@ import org.apache.cloudstack.storage.datastore.lifecycle.CloudStackPrimaryDataSt import com.cloud.utils.component.ComponentContext; -public class CloudStackPrimaryDataStoreProviderImpl implements - PrimaryDataStoreProvider { +public class CloudStackPrimaryDataStoreProviderImpl implements PrimaryDataStoreProvider { private final String providerName = DataStoreProvider.DEFAULT_PRIMARY; protected PrimaryDataStoreDriver driver; @@ -74,7 +73,7 @@ public class CloudStackPrimaryDataStoreProviderImpl implements @Override public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet(); types.add(DataStoreProviderType.PRIMARY); return types; } diff --git a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java index 31be988b086..ad506d1793c 100644 --- a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java +++ b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.framework.async.AsyncRpcConext; import org.apache.cloudstack.storage.command.CommandResult; import org.apache.cloudstack.storage.command.CreateObjectAnswer; import org.apache.cloudstack.storage.command.CreateObjectCommand; -import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.datastore.DataObjectManager; import org.apache.log4j.Logger; @@ -47,7 +46,6 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.storage.encoding.DecodedDataObject; import com.cloud.utils.storage.encoding.Decoder; - public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver { private static final Logger s_logger = Logger.getLogger(SamplePrimaryDataStoreDriverImpl.class); @Inject @@ -56,6 +54,7 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver StoragePoolHostDao storeHostDao; @Inject DataObjectManager dataObjMgr; + public SamplePrimaryDataStoreDriverImpl() { } @@ -65,16 +64,15 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver return null; } - @Override public DataStoreTO getStoreTO(DataStore store) { // TODO Auto-generated method stub return null; } - private class CreateVolumeContext extends AsyncRpcConext { private final DataObject volume; + /** * @param callback */ @@ -89,33 +87,36 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver } - public Void createAsyncCallback(AsyncCallbackDispatcher callback, CreateVolumeContext context) { - /*CreateCmdResult result = null; - CreateObjectAnswer volAnswer = (CreateObjectAnswer) callback.getResult(); - if (volAnswer.getResult()) { - result = new CreateCmdResult(volAnswer.getPath(), volAnswer); - } else { - result = new CreateCmdResult("", null); - result.setResult(volAnswer.getDetails()); - } - - context.getParentCallback().complete(result);*/ + public Void createAsyncCallback(AsyncCallbackDispatcher callback, + CreateVolumeContext context) { + /* + * CreateCmdResult result = null; CreateObjectAnswer volAnswer = + * (CreateObjectAnswer) callback.getResult(); if (volAnswer.getResult()) + * { result = new CreateCmdResult(volAnswer.getPath(), volAnswer); } + * else { result = new CreateCmdResult("", null); + * result.setResult(volAnswer.getDetails()); } + * + * context.getParentCallback().complete(result); + */ return null; } @Override public void deleteAsync(DataObject vo, AsyncCompletionCallback callback) { - /*DeleteCommand cmd = new DeleteCommand(vo.getUri()); - - EndPoint ep = selector.select(vo); - AsyncRpcConext context = new AsyncRpcConext(callback); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setCallback(caller.getTarget().deleteCallback(null, null)) - .setContext(context); - ep.sendMessageAsync(cmd, caller);*/ + /* + * DeleteCommand cmd = new DeleteCommand(vo.getUri()); + * + * EndPoint ep = selector.select(vo); AsyncRpcConext + * context = new AsyncRpcConext(callback); + * AsyncCallbackDispatcher + * caller = AsyncCallbackDispatcher.create(this); + * caller.setCallback(caller.getTarget().deleteCallback(null, null)) + * .setContext(context); ep.sendMessageAsync(cmd, caller); + */ } - public Void deleteCallback(AsyncCallbackDispatcher callback, AsyncRpcConext context) { + public Void deleteCallback(AsyncCallbackDispatcher callback, + AsyncRpcConext context) { CommandResult result = new CommandResult(); Answer answer = callback.getResult(); if (!answer.getResult()) { @@ -124,83 +125,80 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver context.getParentCallback().complete(result); return null; } + /* - private class CreateVolumeFromBaseImageContext extends AsyncRpcConext { - private final VolumeObject volume; - - public CreateVolumeFromBaseImageContext(AsyncCompletionCallback callback, VolumeObject volume) { - super(callback); - this.volume = volume; - } - - public VolumeObject getVolume() { - return this.volume; - } - - } + * private class CreateVolumeFromBaseImageContext extends + * AsyncRpcConext { private final VolumeObject volume; + * + * public CreateVolumeFromBaseImageContext(AsyncCompletionCallback + * callback, VolumeObject volume) { super(callback); this.volume = volume; } + * + * public VolumeObject getVolume() { return this.volume; } + * + * } + * + * @Override public void createVolumeFromBaseImageAsync(VolumeObject volume, + * TemplateInfo template, AsyncCompletionCallback callback) { + * VolumeTO vol = this.dataStore.getVolumeTO(volume); List + * endPoints = this.dataStore.getEndPoints(); EndPoint ep = + * endPoints.get(0); String templateUri = + * template.getDataStore().grantAccess(template, ep); + * CreateVolumeFromBaseImageCommand cmd = new + * CreateVolumeFromBaseImageCommand(vol, templateUri); + * + * CreateVolumeFromBaseImageContext context = new + * CreateVolumeFromBaseImageContext(callback, volume); + * AsyncCallbackDispatcher caller + * = AsyncCallbackDispatcher.create(this); caller.setContext(context) + * .setCallback + * (caller.getTarget().createVolumeFromBaseImageAsyncCallback(null, null)); + * + * ep.sendMessageAsync(cmd, caller); } + */ + /* + * public Object + * createVolumeFromBaseImageAsyncCallback(AsyncCallbackDispatcher + * callback, + * CreateVolumeFromBaseImageContext context) { + * CreateVolumeAnswer answer = (CreateVolumeAnswer)callback.getResult(); + * CommandResult result = new CommandResult(); if (answer == null || + * answer.getDetails() != null) { result.setSuccess(false); if (answer != + * null) { result.setResult(answer.getDetails()); } } else { + * result.setSuccess(true); VolumeObject volume = context.getVolume(); + * volume.setPath(answer.getVolumeUuid()); } + * AsyncCompletionCallback parentCall = + * context.getParentCallback(); parentCall.complete(result); return null; } + */ @Override - public void createVolumeFromBaseImageAsync(VolumeObject volume, TemplateInfo template, AsyncCompletionCallback callback) { - VolumeTO vol = this.dataStore.getVolumeTO(volume); - List endPoints = this.dataStore.getEndPoints(); - EndPoint ep = endPoints.get(0); - String templateUri = template.getDataStore().grantAccess(template, ep); - CreateVolumeFromBaseImageCommand cmd = new CreateVolumeFromBaseImageCommand(vol, templateUri); - - CreateVolumeFromBaseImageContext context = new CreateVolumeFromBaseImageContext(callback, volume); - AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setContext(context) - .setCallback(caller.getTarget().createVolumeFromBaseImageAsyncCallback(null, null)); - - ep.sendMessageAsync(cmd, caller); - }*/ - /* - public Object createVolumeFromBaseImageAsyncCallback(AsyncCallbackDispatcher callback, CreateVolumeFromBaseImageContext context) { - CreateVolumeAnswer answer = (CreateVolumeAnswer)callback.getResult(); - CommandResult result = new CommandResult(); - if (answer == null || answer.getDetails() != null) { - result.setSuccess(false); - if (answer != null) { - result.setResult(answer.getDetails()); - } - } else { - result.setSuccess(true); - VolumeObject volume = context.getVolume(); - volume.setPath(answer.getVolumeUuid()); - } - AsyncCompletionCallback parentCall = context.getParentCallback(); - parentCall.complete(result); - return null; - }*/ - - @Override - public void createAsync(DataObject vol, - AsyncCompletionCallback callback) { + public void createAsync(DataObject vol, AsyncCompletionCallback callback) { EndPoint ep = selector.select(vol); CreateObjectCommand createCmd = new CreateObjectCommand(null); CreateVolumeContext context = new CreateVolumeContext(callback, vol); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); - caller.setContext(context) - .setCallback(caller.getTarget().createAsyncCallback(null, null)); + caller.setContext(context).setCallback(caller.getTarget().createAsyncCallback(null, null)); ep.sendMessageAsync(createCmd, caller); } @Override public String grantAccess(DataObject object, EndPoint ep) { - //StoragePoolHostVO poolHost = storeHostDao.findByPoolHost(object.getDataStore().getId(), ep.getId()); + // StoragePoolHostVO poolHost = + // storeHostDao.findByPoolHost(object.getDataStore().getId(), + // ep.getId()); String uri = object.getUri(); try { DecodedDataObject obj = Decoder.decode(uri); if (obj.getPath() == null) { - //create an obj + // create an obj EndPoint newEp = selector.select(object); CreateObjectCommand createCmd = new CreateObjectCommand(null); - CreateObjectAnswer answer = (CreateObjectAnswer)ep.sendMessage(createCmd); + CreateObjectAnswer answer = (CreateObjectAnswer) ep.sendMessage(createCmd); if (answer.getResult()) { - //dataObjMgr.update(object, answer.getPath(), answer.getSize()); + // dataObjMgr.update(object, answer.getPath(), + // answer.getSize()); } else { s_logger.debug("failed to create object" + answer.getDetails()); throw new CloudRuntimeException("failed to create object" + answer.getDetails()); @@ -209,7 +207,7 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver return object.getUri(); } catch (URISyntaxException e) { - throw new CloudRuntimeException("uri parsed error", e); + throw new CloudRuntimeException("uri parsed error", e); } } @@ -226,14 +224,11 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver } @Override - public void revertSnapshot(SnapshotInfo snapshot, - AsyncCompletionCallback callback) { + public void revertSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) { // TODO Auto-generated method stub } - - @Override public boolean canCopy(DataObject srcData, DataObject destData) { // TODO Auto-generated method stub @@ -241,24 +236,21 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver } @Override - public void copyAsync(DataObject srcdata, DataObject destData, - AsyncCompletionCallback callback) { + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { // TODO Auto-generated method stub } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } - @Override - public void takeSnapshot(SnapshotInfo snapshot, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } } diff --git a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java index ddd64e5ec98..504cb9a007f 100644 --- a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java +++ b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java @@ -54,18 +54,20 @@ public class SamplePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLife PrimaryDataStoreHelper primaryStoreHelper; @Inject PrimaryDataStoreProviderManager providerMgr; + public SamplePrimaryDataStoreLifeCycleImpl() { } - + @Override public DataStore initialize(Map dsInfos) { - - DataStore store = primaryStoreHelper.createPrimaryDataStore(null); + + DataStore store = primaryStoreHelper.createPrimaryDataStore(null); return providerMgr.getPrimaryDataStore(store.getId()); } protected void attachCluster(DataStore store) { - //send down AttachPrimaryDataStoreCmd command to all the hosts in the cluster + // send down AttachPrimaryDataStoreCmd command to all the hosts in the + // cluster List endPoints = selector.selectAll(store); CreatePrimaryDataStoreCmd createCmd = new CreatePrimaryDataStoreCmd(store.getUri()); EndPoint ep = endPoints.get(0); @@ -73,14 +75,14 @@ public class SamplePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLife if (host.getHypervisorType() == HypervisorType.XenServer) { ep.sendMessage(createCmd); } - + endPoints.get(0).sendMessage(createCmd); AttachPrimaryDataStoreCmd cmd = new AttachPrimaryDataStoreCmd(store.getUri()); for (EndPoint endp : endPoints) { endp.sendMessage(cmd); } } - + @Override public boolean attachCluster(DataStore dataStore, ClusterScope scope) { StoragePoolVO dataStoreVO = dataStoreDao.findById(dataStore.getId()); @@ -90,14 +92,13 @@ public class SamplePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLife dataStoreVO.setStatus(StoragePoolStatus.Attaching); dataStoreVO.setScope(scope.getScopeType()); dataStoreDao.update(dataStoreVO.getId(), dataStoreVO); - - + attachCluster(dataStore); - + dataStoreVO = dataStoreDao.findById(dataStore.getId()); dataStoreVO.setStatus(StoragePoolStatus.Up); dataStoreDao.update(dataStoreVO.getId(), dataStoreVO); - + return true; } @@ -120,8 +121,7 @@ public class SamplePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLife } @Override - public boolean attachHost(DataStore store, HostScope scope, - StoragePoolInfo existingInfo) { + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { // TODO Auto-generated method stub return false; } diff --git a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/provider/SamplePrimaryDatastoreProviderImpl.java b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/provider/SamplePrimaryDatastoreProviderImpl.java index 57424a7e0c3..87088214dbc 100644 --- a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/provider/SamplePrimaryDatastoreProviderImpl.java +++ b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/provider/SamplePrimaryDatastoreProviderImpl.java @@ -23,18 +23,15 @@ import java.util.Set; import javax.inject.Inject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.DataStoreProviderType; import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; import org.apache.cloudstack.storage.datastore.driver.SamplePrimaryDataStoreDriverImpl; import org.apache.cloudstack.storage.datastore.lifecycle.SamplePrimaryDataStoreLifeCycleImpl; import com.cloud.utils.component.ComponentContext; - public class SamplePrimaryDatastoreProviderImpl implements PrimaryDataStoreProvider { private final String providerName = "sample primary data store provider"; protected PrimaryDataStoreDriver driver; @@ -45,6 +42,7 @@ public class SamplePrimaryDatastoreProviderImpl implements PrimaryDataStoreProvi protected DataStoreLifeCycle lifecycle; protected String uuid; protected long id; + @Override public String getName() { return providerName; @@ -75,7 +73,7 @@ public class SamplePrimaryDatastoreProviderImpl implements PrimaryDataStoreProvi @Override public Set getTypes() { - Set types = new HashSet(); + Set types = new HashSet(); types.add(DataStoreProviderType.PRIMARY); return types; } diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java index eee9ba5e1d9..a296bab834a 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java @@ -44,7 +44,6 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { return null; } - @Override public DataStoreTO getStoreTO(DataStore store) { // TODO Auto-generated method stub @@ -93,19 +92,16 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { } - @Override - public void resize(DataObject data, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub - } + } - @Override - public void takeSnapshot(SnapshotInfo snapshot, - AsyncCompletionCallback callback) { - // TODO Auto-generated method stub - - } + @Override + public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) { + // TODO Auto-generated method stub + } } diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidfirePrimaryDataStoreProvider.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidfirePrimaryDataStoreProvider.java index 39adf9f1075..03f241ef132 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidfirePrimaryDataStoreProvider.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/provider/SolidfirePrimaryDataStoreProvider.java @@ -27,19 +27,17 @@ import org.springframework.stereotype.Component; @Component public class SolidfirePrimaryDataStoreProvider implements PrimaryDataStoreProvider { - private final String name = "Solidfire Primary Data Store Provider"; + private final String name = "Solidfire Primary Data Store Provider"; + public SolidfirePrimaryDataStoreProvider() { - public SolidfirePrimaryDataStoreProvider() { + // TODO Auto-generated constructor stub + } - - // TODO Auto-generated constructor stub - } - - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } @Override public DataStoreLifeCycle getDataStoreLifeCycle() { @@ -71,5 +69,4 @@ public class SolidfirePrimaryDataStoreProvider implements PrimaryDataStoreProvid return null; } - } diff --git a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java index 63669c453d7..902f5953eb1 100644 --- a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java +++ b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java @@ -21,14 +21,14 @@ import org.aspectj.lang.ProceedingJoinPoint; import com.cloud.utils.db.Transaction; public class AopTestAdvice { - public Object AopTestMethod(ProceedingJoinPoint call) throws Throwable { - Transaction txn = Transaction.open(call.getSignature().getName()); - Object ret = null; - try { - ret = call.proceed(); - } finally { - txn.close(); - } - return ret; - } + public Object AopTestMethod(ProceedingJoinPoint call) throws Throwable { + Transaction txn = Transaction.open(call.getSignature().getName()); + Object ret = null; + try { + ret = call.proceed(); + } finally { + txn.close(); + } + return ret; + } } diff --git a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java index eb6fe453886..79215618914 100644 --- a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java +++ b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java @@ -24,28 +24,29 @@ import com.cloud.agent.AgentManager; import com.cloud.host.dao.HostDao; public class ChildTestConfiguration extends TestConfiguration { - - @Override - @Bean - public HostDao hostDao() { - HostDao dao = super.hostDao(); - HostDao nDao = Mockito.spy(dao); - return nDao; - } - - @Bean - public AgentManager agentMgr() { - return Mockito.mock(AgentManager.class); - } - - @Bean - public ImageMotionService imageMotion() { - return Mockito.mock(ImageMotionService.class); - } -/* @Override - @Bean - public PrimaryDataStoreDao primaryDataStoreDao() { - return Mockito.mock(PrimaryDataStoreDaoImpl.class); - }*/ + @Override + @Bean + public HostDao hostDao() { + HostDao dao = super.hostDao(); + HostDao nDao = Mockito.spy(dao); + return nDao; + } + + @Bean + public AgentManager agentMgr() { + return Mockito.mock(AgentManager.class); + } + + @Bean + public ImageMotionService imageMotion() { + return Mockito.mock(ImageMotionService.class); + } + + /* + * @Override + * + * @Bean public PrimaryDataStoreDao primaryDataStoreDao() { return + * Mockito.mock(PrimaryDataStoreDaoImpl.class); } + */ } diff --git a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/TestConfiguration.java b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/TestConfiguration.java index 2c6092d7408..8e98771feab 100644 --- a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/TestConfiguration.java +++ b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/TestConfiguration.java @@ -26,12 +26,13 @@ import com.cloud.host.dao.HostDaoImpl; @Configuration public class TestConfiguration { - @Bean - public HostDao hostDao() { - return new HostDaoImpl(); - } - @Bean - public PrimaryDataStoreDao primaryDataStoreDao() { - return new PrimaryDataStoreDaoImpl(); - } + @Bean + public HostDao hostDao() { + return new HostDaoImpl(); + } + + @Bean + public PrimaryDataStoreDao primaryDataStoreDao() { + return new PrimaryDataStoreDaoImpl(); + } } diff --git a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/VolumeTest.java b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/VolumeTest.java index 5bc929d3efc..a745dafbc2f 100644 --- a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/VolumeTest.java +++ b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/VolumeTest.java @@ -25,11 +25,11 @@ import java.util.UUID; import javax.inject.Inject; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; -import org.apache.cloudstack.storage.command.CreateObjectAnswer; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -42,8 +42,6 @@ import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.OperationTimedoutException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; @@ -52,88 +50,91 @@ import com.cloud.org.Cluster.ClusterType; import com.cloud.org.Managed.ManagedState; import com.cloud.resource.ResourceState; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="classpath:/resource/storageContext.xml") +@ContextConfiguration(locations = "classpath:/resource/storageContext.xml") public class VolumeTest { - @Inject - HostDao hostDao; - @Inject - HostPodDao podDao; - @Inject - ClusterDao clusterDao; - @Inject - DataCenterDao dcDao; - @Inject - PrimaryDataStoreDao primaryStoreDao; - //@Inject - //PrimaryDataStoreProviderManager primaryDataStoreProviderMgr; - @Inject - AgentManager agentMgr; - Long dcId; - Long clusterId; - @Before - public void setUp() { - //create data center - DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); - dc = dcDao.persist(dc); - dcId = dc.getId(); - //create pod + @Inject + HostDao hostDao; + @Inject + HostPodDao podDao; + @Inject + ClusterDao clusterDao; + @Inject + DataCenterDao dcDao; + @Inject + PrimaryDataStoreDao primaryStoreDao; + // @Inject + // PrimaryDataStoreProviderManager primaryDataStoreProviderMgr; + @Inject + AgentManager agentMgr; + Long dcId; + Long clusterId; - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), "192.168.56.1", "192.168.56.0/24", 8, "test"); - pod = podDao.persist(pod); - //create xen cluster - ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); - cluster.setHypervisorType(HypervisorType.XenServer.toString()); - cluster.setClusterType(ClusterType.CloudManaged); - cluster.setManagedState(ManagedState.Managed); - cluster = clusterDao.persist(cluster); - clusterId = cluster.getId(); - //create xen host + @Before + public void setUp() { + // create data center + DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, + "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null); + dc = dcDao.persist(dc); + dcId = dc.getId(); + // create pod - HostVO host = new HostVO(UUID.randomUUID().toString()); - host.setName("devcloud xen host"); - host.setType(Host.Type.Routing); - host.setPrivateIpAddress("192.168.56.2"); - host.setDataCenterId(dc.getId()); - host.setVersion("6.0.1"); - host.setAvailable(true); - host.setSetup(true); - host.setLastPinged(0); - host.setResourceState(ResourceState.Enabled); - host.setClusterId(cluster.getId()); + HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), "192.168.56.1", "192.168.56.0/24", 8, + "test"); + pod = podDao.persist(pod); + // create xen cluster + ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); + cluster.setHypervisorType(HypervisorType.XenServer.toString()); + cluster.setClusterType(ClusterType.CloudManaged); + cluster.setManagedState(ManagedState.Managed); + cluster = clusterDao.persist(cluster); + clusterId = cluster.getId(); + // create xen host - host = hostDao.persist(host); - List results = new ArrayList(); - results.add(host); - Mockito.when(hostDao.listAll()).thenReturn(results); - Mockito.when(hostDao.findHypervisorHostInCluster(Mockito.anyLong())).thenReturn(results); - //CreateObjectAnswer createVolumeFromImageAnswer = new CreateObjectAnswer(null,UUID.randomUUID().toString(), null); + HostVO host = new HostVO(UUID.randomUUID().toString()); + host.setName("devcloud xen host"); + host.setType(Host.Type.Routing); + host.setPrivateIpAddress("192.168.56.2"); + host.setDataCenterId(dc.getId()); + host.setVersion("6.0.1"); + host.setAvailable(true); + host.setSetup(true); + host.setLastPinged(0); + host.setResourceState(ResourceState.Enabled); + host.setClusterId(cluster.getId()); + host = hostDao.persist(host); + List results = new ArrayList(); + results.add(host); + Mockito.when(hostDao.listAll()).thenReturn(results); + Mockito.when(hostDao.findHypervisorHostInCluster(Matchers.anyLong())).thenReturn(results); + // CreateObjectAnswer createVolumeFromImageAnswer = new + // CreateObjectAnswer(null,UUID.randomUUID().toString(), null); + // Mockito.when(primaryStoreDao.findById(Mockito.anyLong())).thenReturn(primaryStore); + } - //Mockito.when(primaryStoreDao.findById(Mockito.anyLong())).thenReturn(primaryStore); - } + private PrimaryDataStoreInfo createPrimaryDataStore() { + try { + // primaryDataStoreProviderMgr.configure("primary data store mgr", + // new HashMap()); + // PrimaryDataStoreProvider provider = + // primaryDataStoreProviderMgr.getDataStoreProvider("Solidfre Primary Data Store Provider"); + Map params = new HashMap(); + params.put("url", "nfs://test/test"); + params.put("dcId", dcId.toString()); + params.put("clusterId", clusterId.toString()); + params.put("name", "my primary data store"); + // PrimaryDataStoreInfo primaryDataStoreInfo = + // provider.registerDataStore(params); + return null; + } catch (Exception e) { + return null; + } + } - private PrimaryDataStoreInfo createPrimaryDataStore() { - try { - //primaryDataStoreProviderMgr.configure("primary data store mgr", new HashMap()); - //PrimaryDataStoreProvider provider = primaryDataStoreProviderMgr.getDataStoreProvider("Solidfre Primary Data Store Provider"); - Map params = new HashMap(); - params.put("url", "nfs://test/test"); - params.put("dcId", dcId.toString()); - params.put("clusterId", clusterId.toString()); - params.put("name", "my primary data store"); - //PrimaryDataStoreInfo primaryDataStoreInfo = provider.registerDataStore(params); - return null; - } catch (Exception e) { - return null; - } - } - - @Test - public void createPrimaryDataStoreTest() { - createPrimaryDataStore(); - } + @Test + public void createPrimaryDataStoreTest() { + createPrimaryDataStore(); + } }