diff --git a/engine/components-api/PrimaryDataStore.java b/engine/components-api/PrimaryDataStore.java deleted file mode 100644 index 87aee25bb4d..00000000000 --- a/engine/components-api/PrimaryDataStore.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.engine.subsystem.api.storage; - -import java.util.List; - -import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; -import org.apache.cloudstack.engine.subsystem.api.storage.disktype.VolumeDiskType; - - -public interface PrimaryDataStore { - VolumeEntity getVolume(String id); - List getVolumes(); - boolean deleteVolume(VolumeEntity id); - VolumeEntity createVolume(String id, VolumeDiskType diskType); - List getEndPoints(); - PrimaryDataStoreInfo getDataStoreInfo(); -} diff --git a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java index 12acc7d65a9..a5b45e17f03 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java +++ b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java @@ -19,22 +19,22 @@ package org.apache.cloudstack.storage; public abstract class BaseType { - 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 BaseType) { - BaseType th = (BaseType)that; - if (this.toString().equalsIgnoreCase(th.toString())) { - return true; - } - } else { - return false; - } - return false; - } + 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 BaseType) { + BaseType th = (BaseType) that; + if (this.toString().equalsIgnoreCase(th.toString())) { + return true; + } + } else { + return false; + } + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPoint.java b/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPoint.java index a47946a2a1e..a7c1041767f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPoint.java +++ b/engine/storage/src/org/apache/cloudstack/storage/HypervisorHostEndPoint.java @@ -30,27 +30,28 @@ import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.OperationTimedoutException; public class HypervisorHostEndPoint implements EndPoint { - private static final Logger s_logger = Logger.getLogger(HypervisorHostEndPoint.class); - private long hostId; - @Inject - AgentManager agentMgr; - public HypervisorHostEndPoint(long hostId) { - this.hostId = hostId; - } - - @Override - public Answer sendMessage(Command cmd) { - Answer answer = null; - try { - answer = agentMgr.send(hostId, cmd); - } catch (AgentUnavailableException e) { - s_logger.debug("Unable to send command:" + cmd + ", due to: " + e.toString()); - } catch (OperationTimedoutException e) { - s_logger.debug("Unable to send command:" + cmd + ", due to: " + e.toString()); - } catch (Exception e) { - s_logger.debug("Unable to send command:" + cmd + ", due to: " + e.toString()); - } - return answer; - } + private static final Logger s_logger = Logger.getLogger(HypervisorHostEndPoint.class); + private long hostId; + @Inject + AgentManager agentMgr; + + public HypervisorHostEndPoint(long hostId) { + this.hostId = hostId; + } + + @Override + public Answer sendMessage(Command cmd) { + Answer answer = null; + try { + answer = agentMgr.send(hostId, cmd); + } catch (AgentUnavailableException e) { + s_logger.debug("Unable to send command:" + cmd + ", due to: " + e.toString()); + } catch (OperationTimedoutException e) { + s_logger.debug("Unable to send command:" + cmd + ", due to: " + e.toString()); + } catch (Exception e) { + s_logger.debug("Unable to send command:" + cmd + ", due to: " + e.toString()); + } + return answer; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/StorageOrchestratorImpl.java b/engine/storage/src/org/apache/cloudstack/storage/StorageOrchestratorImpl.java index 18e94298c3b..efc9b70ef8e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/StorageOrchestratorImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/StorageOrchestratorImpl.java @@ -72,295 +72,290 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.VMInstanceDao; public class StorageOrchestratorImpl implements StorageOrchestrator { - private static final Logger s_logger = Logger.getLogger(StorageOrchestratorImpl.class); - @Inject - StoragePoolDao _storagePoolDao; - @Inject - StorageProviderManager _spManager; - @Inject - VolumeDao _volumeDao; - @Inject - VMInstanceDao _vmDao; - @Inject - DiskOfferingDao _diskOfferingDao; - @Inject - VolumeHostDao _volumeHostDao; - @Inject - StorageProviderManager _storageProviderMgr; - @Inject - VolumeManager _volumeMgr; - @Inject - SecondaryStorageManager _secondaryStorageMgr; - @Inject - ImageManager _templateMgr; - @Inject - VMTemplateDao _templateDao; - @Inject - VolumeService volumeService; - @Inject - ImageMotionService imageMotionService; - @Inject - ImageService imageService; - @Inject - PrimaryDataStoreManager primaryStorageMgr; - - @DB - protected Volume copyVolumeFromBackupStorage(VolumeVO volume, DataStore destStore, String reservationId) throws NoTransitionException { - DataStore ds = _secondaryStorageMgr.getStore(volume); - if (!ds.contains(volume)) { - throw new CloudRuntimeException("volume: " + volume + "doesn't exist on backup storage"); - } - - VolumeProfile vp = ds.prepareVolume(volume, destStore); - - VolumeStrategy vs = destStore.getVolumeStrategy(); + private static final Logger s_logger = Logger.getLogger(StorageOrchestratorImpl.class); + @Inject + StoragePoolDao _storagePoolDao; + @Inject + StorageProviderManager _spManager; + @Inject + VolumeDao _volumeDao; + @Inject + VMInstanceDao _vmDao; + @Inject + DiskOfferingDao _diskOfferingDao; + @Inject + VolumeHostDao _volumeHostDao; + @Inject + StorageProviderManager _storageProviderMgr; + @Inject + VolumeManager _volumeMgr; + @Inject + SecondaryStorageManager _secondaryStorageMgr; + @Inject + ImageManager _templateMgr; + @Inject + VMTemplateDao _templateDao; + @Inject + VolumeService volumeService; + @Inject + ImageMotionService imageMotionService; + @Inject + ImageService imageService; + @Inject + PrimaryDataStoreManager primaryStorageMgr; - Transaction txn = Transaction.currentTxn(); - volume.setReservationId(reservationId); - _volumeMgr.processEvent(volume, Volume.Event.CopyRequested); - VolumeVO destVolume = _volumeMgr.allocateDuplicateVolume(volume); - destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.CreateRequested); - txn.commit(); - - vs.copyVolumeFromBackup(vp, destVolume); - - txn.start(); - volume = _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); - destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.OperationSucceeded); - txn.commit(); - - return destVolume; - } - - @DB - protected Volume migrateVolume(VolumeVO volume, DataStore srcStore, DataStore destStore, String reservationId) throws NoTransitionException { - Transaction txn = Transaction.currentTxn(); - txn.start(); - volume.setReservationId(reservationId); - volume = _volumeMgr.processEvent(volume, Volume.Event.MigrationRequested); - Volume destVolume = _volumeMgr.allocateDuplicateVolume(volume); - destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.CreateRequested); - txn.commit(); - - VolumeStrategy vs = srcStore.getVolumeStrategy(); - vs.migrateVolume(volume, destVolume, destStore); - - txn.start(); - volume = _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); - destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.OperationSucceeded); - txn.commit(); - - volume = _volumeMgr.processEvent(volume, Volume.Event.DestroyRequested); - - vs.deleteVolume(volume); - - _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); - return destVolume; - } - - @DB - protected Volume recreateVolume(VolumeVO srcVolume, DataStore destStore, String reservationId) throws NoTransitionException { - Transaction txn = Transaction.currentTxn(); - txn.start(); - srcVolume.setReservationId(reservationId); - srcVolume = _volumeMgr.processEvent(srcVolume, Volume.Event.CopyRequested); - Volume destVolume = _volumeMgr.allocateDuplicateVolume(srcVolume); - destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.CreateRequested); - txn.commit(); - - DataStore srcStore = _storageProviderMgr.getDataStore(srcVolume.getPoolId()); - VolumeStrategy vs = srcStore.getVolumeStrategy(); - - vs.migrateVolume(srcVolume, destVolume, destStore); - - txn.start(); - srcVolume = _volumeMgr.processEvent(srcVolume, Volume.Event.OperationSucceeded); - destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.OperationSucceeded); - txn.commit(); - - srcVolume = _volumeMgr.processEvent(srcVolume, Volume.Event.DestroyRequested); - - vs.deleteVolume(srcVolume); - - _volumeMgr.processEvent(srcVolume, Volume.Event.OperationSucceeded); - - return destVolume; - } - - protected Volume createVolumeOnStorage(Volume volume, DataStore destStore, String reservationId) throws NoTransitionException { - VolumeStrategy vs = destStore.getVolumeStrategy(); - volume.setReservationId(reservationId); - volume = _volumeMgr.processEvent(volume, Volume.Event.CreateRequested); - - if (volume.getTemplateId() != null) { - DataStore ds = _secondaryStorageMgr.getImageStore(destStore); - TemplateProfile tp = ds.prepareTemplate(volume.getTemplateId(), destStore); - if (!destStore.contains(tp)) { - tp = _templateMgr.AssociateTemplateStoragePool(tp, destStore); - tp = destStore.getTemplateStrategy().install(tp); - } else { - tp = destStore.getTemplateStrategy().get(tp.getId()); - } - volume = vs.createVolumeFromBaseTemplate(volume, tp); - } else { - volume = vs.createDataVolume(volume); - } - - volume = _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); - return volume; - } - - @DB - protected void prepareVolumes(List vols, Long destPoolId, String reservationId) throws NoTransitionException { - DataStore destStore = null; - if (destPoolId != null) { - destStore = _storageProviderMgr.getDataStore(destPoolId); - } - - for (VolumeVO volume : vols) { - if (volume.getPoolId() == null && destStore == null) { - throw new CloudRuntimeException("Volume has no pool associate and also no storage pool assigned in DeployDestination, Unable to create."); - } - if (destStore == null) { - continue; - } + @DB + protected Volume copyVolumeFromBackupStorage(VolumeVO volume, DataStore destStore, String reservationId) throws NoTransitionException { + DataStore ds = _secondaryStorageMgr.getStore(volume); + if (!ds.contains(volume)) { + throw new CloudRuntimeException("volume: " + volume + "doesn't exist on backup storage"); + } - DataStore srcStore = _storageProviderMgr.getDataStore(volume.getPoolId()); - boolean needToCreateVolume = false; - boolean needToRecreateVolume = false; - boolean needToMigrateVolume = false; - boolean needToCopyFromSec = false; + VolumeProfile vp = ds.prepareVolume(volume, destStore); - Volume.State state = volume.getState(); - if (state == Volume.State.Allocated) { - needToCreateVolume = true; - } else if (state == Volume.State.UploadOp) { - needToCopyFromSec = true; - } else if (destStore.getId() != srcStore.getId()) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Mismatch in storage pool " + destStore.getId() + " assigned by deploymentPlanner and the one associated with volume " + volume); - } - - if (volume.isRecreatable()) { - needToRecreateVolume = true; - } else { - if (Volume.Type.ROOT == volume.getVolumeType()) { - needToMigrateVolume = true; - } else { - if (destStore.getCluterId() != srcStore.getCluterId()) { - needToMigrateVolume = true; - } else if (!srcStore.isSharedStorage() && srcStore.getId() != destStore.getId()) { - needToMigrateVolume = true; - } else { - continue; - } - } - } - } else { - continue; - } - - - if (needToCreateVolume) { - createVolumeOnStorage(volume, destStore, reservationId); - } else if (needToMigrateVolume) { - migrateVolume(volume, srcStore, destStore, reservationId); - } else if (needToCopyFromSec) { - copyVolumeFromBackupStorage(volume, destStore, reservationId); - } else if (needToRecreateVolume) { - recreateVolume(volume, destStore, reservationId); - } - } - } - - public void prepare(long vmId, DeploymentPlan plan, String reservationId) { + VolumeStrategy vs = destStore.getVolumeStrategy(); + + Transaction txn = Transaction.currentTxn(); + volume.setReservationId(reservationId); + _volumeMgr.processEvent(volume, Volume.Event.CopyRequested); + VolumeVO destVolume = _volumeMgr.allocateDuplicateVolume(volume); + destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.CreateRequested); + txn.commit(); + + vs.copyVolumeFromBackup(vp, destVolume); + + txn.start(); + volume = _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); + destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.OperationSucceeded); + txn.commit(); + + return destVolume; + } + + @DB + protected Volume migrateVolume(VolumeVO volume, DataStore srcStore, DataStore destStore, String reservationId) throws NoTransitionException { + Transaction txn = Transaction.currentTxn(); + txn.start(); + volume.setReservationId(reservationId); + volume = _volumeMgr.processEvent(volume, Volume.Event.MigrationRequested); + Volume destVolume = _volumeMgr.allocateDuplicateVolume(volume); + destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.CreateRequested); + txn.commit(); + + VolumeStrategy vs = srcStore.getVolumeStrategy(); + vs.migrateVolume(volume, destVolume, destStore); + + txn.start(); + volume = _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); + destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.OperationSucceeded); + txn.commit(); + + volume = _volumeMgr.processEvent(volume, Volume.Event.DestroyRequested); + + vs.deleteVolume(volume); + + _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); + return destVolume; + } + + @DB + protected Volume recreateVolume(VolumeVO srcVolume, DataStore destStore, String reservationId) throws NoTransitionException { + Transaction txn = Transaction.currentTxn(); + txn.start(); + srcVolume.setReservationId(reservationId); + srcVolume = _volumeMgr.processEvent(srcVolume, Volume.Event.CopyRequested); + Volume destVolume = _volumeMgr.allocateDuplicateVolume(srcVolume); + destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.CreateRequested); + txn.commit(); + + DataStore srcStore = _storageProviderMgr.getDataStore(srcVolume.getPoolId()); + VolumeStrategy vs = srcStore.getVolumeStrategy(); + + vs.migrateVolume(srcVolume, destVolume, destStore); + + txn.start(); + srcVolume = _volumeMgr.processEvent(srcVolume, Volume.Event.OperationSucceeded); + destVolume = _volumeMgr.processEvent(destVolume, Volume.Event.OperationSucceeded); + txn.commit(); + + srcVolume = _volumeMgr.processEvent(srcVolume, Volume.Event.DestroyRequested); + + vs.deleteVolume(srcVolume); + + _volumeMgr.processEvent(srcVolume, Volume.Event.OperationSucceeded); + + return destVolume; + } + + protected Volume createVolumeOnStorage(Volume volume, DataStore destStore, String reservationId) throws NoTransitionException { + VolumeStrategy vs = destStore.getVolumeStrategy(); + volume.setReservationId(reservationId); + volume = _volumeMgr.processEvent(volume, Volume.Event.CreateRequested); + + if (volume.getTemplateId() != null) { + DataStore ds = _secondaryStorageMgr.getImageStore(destStore); + TemplateProfile tp = ds.prepareTemplate(volume.getTemplateId(), destStore); + if (!destStore.contains(tp)) { + tp = _templateMgr.AssociateTemplateStoragePool(tp, destStore); + tp = destStore.getTemplateStrategy().install(tp); + } else { + tp = destStore.getTemplateStrategy().get(tp.getId()); + } + volume = vs.createVolumeFromBaseTemplate(volume, tp); + } else { + volume = vs.createDataVolume(volume); + } + + volume = _volumeMgr.processEvent(volume, Volume.Event.OperationSucceeded); + return volume; + } + + @DB + protected void prepareVolumes(List vols, Long destPoolId, String reservationId) throws NoTransitionException { + DataStore destStore = null; + if (destPoolId != null) { + destStore = _storageProviderMgr.getDataStore(destPoolId); + } + + for (VolumeVO volume : vols) { + if (volume.getPoolId() == null && destStore == null) { + throw new CloudRuntimeException("Volume has no pool associate and also no storage pool assigned in DeployDestination, Unable to create."); + } + if (destStore == null) { + continue; + } + + DataStore srcStore = _storageProviderMgr.getDataStore(volume.getPoolId()); + boolean needToCreateVolume = false; + boolean needToRecreateVolume = false; + boolean needToMigrateVolume = false; + boolean needToCopyFromSec = false; + + Volume.State state = volume.getState(); + if (state == Volume.State.Allocated) { + needToCreateVolume = true; + } else if (state == Volume.State.UploadOp) { + needToCopyFromSec = true; + } else if (destStore.getId() != srcStore.getId()) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Mismatch in storage pool " + destStore.getId() + " assigned by deploymentPlanner and the one associated with volume " + volume); + } + + if (volume.isRecreatable()) { + needToRecreateVolume = true; + } else { + if (Volume.Type.ROOT == volume.getVolumeType()) { + needToMigrateVolume = true; + } else { + if (destStore.getCluterId() != srcStore.getCluterId()) { + needToMigrateVolume = true; + } else if (!srcStore.isSharedStorage() && srcStore.getId() != destStore.getId()) { + needToMigrateVolume = true; + } else { + continue; + } + } + } + } else { + continue; + } + + if (needToCreateVolume) { + createVolumeOnStorage(volume, destStore, reservationId); + } else if (needToMigrateVolume) { + migrateVolume(volume, srcStore, destStore, reservationId); + } else if (needToCopyFromSec) { + copyVolumeFromBackupStorage(volume, destStore, reservationId); + } else if (needToRecreateVolume) { + recreateVolume(volume, destStore, reservationId); + } + } + } + + public void prepare(long vmId, DeploymentPlan plan, String reservationId) { VirtualMachine vm = _vmDao.findById(vmId); - List vols = _volumeDao.findUsableVolumesForInstance(vm.getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Prepare " + vols.size() + " volumes for " + vm.getInstanceName()); } - + try { - prepareVolumes(vols, plan.getPoolId(), reservationId); + prepareVolumes(vols, plan.getPoolId(), reservationId); } catch (NoTransitionException e) { - s_logger.debug("Failed to prepare volume: " + e.toString()); + s_logger.debug("Failed to prepare volume: " + e.toString()); } } + public void release(long vmId, String reservationId) { + // TODO Auto-generated method stub - public void release(long vmId, String reservationId) { - // TODO Auto-generated method stub - - } + } - public void destroy(List disks, String reservationId) { - // TODO Auto-generated method stub - - } + public void destroy(List disks, String reservationId) { + // TODO Auto-generated method stub - public void cancel(String reservationId) { - // TODO Auto-generated method stub - - } + } - public void prepareAttachDiskToVM(long diskId, long vmId, String reservationId) { - VirtualMachine vm = _vmDao.findById(vmId); - - if (vm == null || vm.getState() != VirtualMachine.State.Running) { - return; - } - - VolumeVO volume = _volumeDao.findById(diskId); - if (volume.getInstanceId() != null) { - if (volume.getInstanceId() != vmId) { - throw new InvalidParameterValueException("Volume " + volume + "already attached to " + volume.getInstanceId()); - } else { - return; - } - } - - List vols = new ArrayList(); - vols.add(volume); - - List rootDisks = _volumeDao.findByInstanceAndType(vmId, Volume.Type.ROOT); - VolumeVO rootDisk = rootDisks.get(0); - try { - prepareVolumes(vols, rootDisk.getPoolId(), reservationId); - } catch (NoTransitionException e) { - s_logger.debug("Failed to prepare volume: " + volume + ", due to" + e.toString()); - throw new CloudRuntimeException(e.toString()); - } - - volume = _volumeDao.findById(diskId); - volume.setInstanceId(vmId); - _volumeDao.update(volume.getId(), volume); - } + public void cancel(String reservationId) { + // TODO Auto-generated method stub + } + public void prepareAttachDiskToVM(long diskId, long vmId, String reservationId) { + VirtualMachine vm = _vmDao.findById(vmId); - @Override - public boolean createVolume(VolumeEntity volume, long dataStoreId, VolumeDiskType diskType) { - VolumeEntityImpl vei = ((VolumeEntityImpl)volume); - VolumeInfo vi = volumeService.createVolume(vei.getVolumeInfo(), dataStoreId, diskType); - vei.setVolumeInfo(vi); - return true; - } + if (vm == null || vm.getState() != VirtualMachine.State.Running) { + return; + } - @Override - public VolumeEntity allocateVolumeInDb(long size, VolumeType type, String volName, Long templateId) { - return volumeService.allocateVolumeInDb(size, type, volName, templateId); - } - - protected VolumeInfo getVolumeInfo(VolumeEntity volume) { - VolumeEntityImpl vei = (VolumeEntityImpl)volume; - return vei.getVolumeInfo(); - } - - @Override - public boolean createVolumeFromTemplate(VolumeEntity volume, long dataStoreId, VolumeDiskType diskType, TemplateEntity template) { - - return false; - } + VolumeVO volume = _volumeDao.findById(diskId); + if (volume.getInstanceId() != null) { + if (volume.getInstanceId() != vmId) { + throw new InvalidParameterValueException("Volume " + volume + "already attached to " + volume.getInstanceId()); + } else { + return; + } + } + + List vols = new ArrayList(); + vols.add(volume); + + List rootDisks = _volumeDao.findByInstanceAndType(vmId, Volume.Type.ROOT); + VolumeVO rootDisk = rootDisks.get(0); + try { + prepareVolumes(vols, rootDisk.getPoolId(), reservationId); + } catch (NoTransitionException e) { + s_logger.debug("Failed to prepare volume: " + volume + ", due to" + e.toString()); + throw new CloudRuntimeException(e.toString()); + } + + volume = _volumeDao.findById(diskId); + volume.setInstanceId(vmId); + _volumeDao.update(volume.getId(), volume); + } + + @Override + public boolean createVolume(VolumeEntity volume, long dataStoreId, VolumeDiskType diskType) { + VolumeEntityImpl vei = ((VolumeEntityImpl) volume); + VolumeInfo vi = volumeService.createVolume(vei.getVolumeInfo(), dataStoreId, diskType); + vei.setVolumeInfo(vi); + return true; + } + + @Override + public VolumeEntity allocateVolumeInDb(long size, VolumeType type, String volName, Long templateId) { + return volumeService.allocateVolumeInDb(size, type, volName, templateId); + } + + protected VolumeInfo getVolumeInfo(VolumeEntity volume) { + VolumeEntityImpl vei = (VolumeEntityImpl) volume; + return vei.getVolumeInfo(); + } + + @Override + public boolean createVolumeFromTemplate(VolumeEntity volume, long dataStoreId, VolumeDiskType diskType, TemplateEntity template) { + + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManager.java b/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManager.java index a49dcda06ae..4260115db37 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManager.java @@ -4,8 +4,11 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.StorageProvider; public interface StorageProviderManager { - StorageProvider getProvider(String uuid); - StorageProvider getProvider(long poolId); - StorageProvider getBackupStorageProvider(long zoneId); - DataStore getDataStore(long poolId); + StorageProvider getProvider(String uuid); + + StorageProvider getProvider(long poolId); + + StorageProvider getBackupStorageProvider(long zoneId); + + DataStore getDataStore(long poolId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManagerImpl.java index f327c406e26..bbed9f44b93 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/StorageProviderManagerImpl.java @@ -10,46 +10,45 @@ import org.apache.cloudstack.engine.subsystem.api.storage.StorageProvider; import com.cloud.utils.component.Manager; public class StorageProviderManagerImpl implements StorageProviderManager, Manager { - - public StorageProvider getProvider(String uuid) { - // TODO Auto-generated method stub - return null; - } - public boolean configure(String name, Map params) - throws ConfigurationException { - // TODO Auto-generated method stub - return false; - } + public StorageProvider getProvider(String uuid) { + // TODO Auto-generated method stub + return null; + } - public boolean start() { - // TODO Auto-generated method stub - return false; - } + public boolean configure(String name, Map params) throws ConfigurationException { + // TODO Auto-generated method stub + return false; + } - public boolean stop() { - // TODO Auto-generated method stub - return false; - } + public boolean start() { + // TODO Auto-generated method stub + return false; + } - public String getName() { - // TODO Auto-generated method stub - return null; - } + public boolean stop() { + // TODO Auto-generated method stub + return false; + } - public StorageProvider getProvider(long poolId) { - // TODO Auto-generated method stub - return null; - } + public String getName() { + // TODO Auto-generated method stub + return null; + } - public StorageProvider getBackupStorageProvider(long zoneId) { - // TODO Auto-generated method stub - return null; - } + public StorageProvider getProvider(long poolId) { + // TODO Auto-generated method stub + return null; + } - public DataStore getDataStore(long poolId) { - // TODO Auto-generated method stub - return null; - } + public StorageProvider getBackupStorageProvider(long zoneId) { + // TODO Auto-generated method stub + return null; + } + + public DataStore getDataStore(long poolId) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/VolumeBackupRef.java b/engine/storage/src/org/apache/cloudstack/storage/VolumeBackupRef.java index 645e94cd1fe..4b512ba133f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/VolumeBackupRef.java +++ b/engine/storage/src/org/apache/cloudstack/storage/VolumeBackupRef.java @@ -28,39 +28,39 @@ import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; public interface VolumeBackupRef { - public DataObjectBackupStorageOperationState getOperationState(); - - public String getInstallPath(); + public DataObjectBackupStorageOperationState getOperationState(); - public long getHostId(); + public String getInstallPath(); - public long getVolumeId(); + public long getHostId(); - public long getZoneId(); + public long getVolumeId(); - public int getDownloadPercent(); + public long getZoneId(); - public long getVolumeSize(); + public int getDownloadPercent(); - public Storage.ImageFormat getFormat(); + public long getVolumeSize(); - public String getDownloadUrl(); + public Storage.ImageFormat getFormat(); - public boolean getDestroyed(); + public String getDownloadUrl(); - public long getPhysicalSize(); + public boolean getDestroyed(); - public long getSize(); + public long getPhysicalSize(); - public String getLocalDownloadPath(); + public long getSize(); - public String getChecksum(); + public String getLocalDownloadPath(); - public Status getDownloadState(); + public String getChecksum(); - public Date getLastUpdated(); + public Status getDownloadState(); - public Date getCreated(); + public Date getLastUpdated(); - public long getId(); + public Date getCreated(); + + public long getId(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/backup/BackupMotionService.java b/engine/storage/src/org/apache/cloudstack/storage/backup/BackupMotionService.java index 5105e25983e..cb49027f3bf 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/backup/BackupMotionService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/backup/BackupMotionService.java @@ -19,5 +19,5 @@ package org.apache.cloudstack.storage.backup; public interface BackupMotionService { - boolean copySnapshot(String snapshotUri, String destSnapshotUri); + boolean copySnapshot(String snapshotUri, String destSnapshotUri); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/backup/BackupService.java b/engine/storage/src/org/apache/cloudstack/storage/backup/BackupService.java index 198247dec2a..ebb4c9f38dd 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/backup/BackupService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/backup/BackupService.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.storage.backup; public interface BackupService { - String grantAccessSnapshot(long snapshotId, long endpointId); - boolean revokeAccessSnapshot(long snapshotId, long endpointId); + String grantAccessSnapshot(long snapshotId, long endpointId); + + boolean revokeAccessSnapshot(long snapshotId, long endpointId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/command/CopyTemplateToPrimaryStorage.java b/engine/storage/src/org/apache/cloudstack/storage/command/CopyTemplateToPrimaryStorage.java index 80a280e4931..d092e9e320c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/command/CopyTemplateToPrimaryStorage.java +++ b/engine/storage/src/org/apache/cloudstack/storage/command/CopyTemplateToPrimaryStorage.java @@ -8,21 +8,21 @@ import com.cloud.agent.api.Command; public class CopyTemplateToPrimaryStorage extends Command { - private ImageOnPrimayDataStoreTO imageTO; - - protected CopyTemplateToPrimaryStorage() { - super(); - } - - public CopyTemplateToPrimaryStorage(ImageOnPrimayDataStoreTO image) { - super(); - this.imageTO = image; - } - - @Override - public boolean executeInSequence() { - // TODO Auto-generated method stub - return false; - } + private ImageOnPrimayDataStoreTO imageTO; + + protected CopyTemplateToPrimaryStorage() { + super(); + } + + public CopyTemplateToPrimaryStorage(ImageOnPrimayDataStoreTO image) { + super(); + this.imageTO = image; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeAnswer.java b/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeAnswer.java index e75307c547d..49fa93e1ede 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeAnswer.java +++ b/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeAnswer.java @@ -21,16 +21,17 @@ package org.apache.cloudstack.storage.command; import com.cloud.agent.api.Answer; public class CreateVolumeAnswer extends Answer { - private String volumeUuid; - protected CreateVolumeAnswer() { - super(); - } - - public CreateVolumeAnswer(String volumeUuid) { - this.volumeUuid = volumeUuid; - } - - public String getVolumeUuid() { - return this.volumeUuid; - } + private String volumeUuid; + + protected CreateVolumeAnswer() { + super(); + } + + public CreateVolumeAnswer(String volumeUuid) { + this.volumeUuid = volumeUuid; + } + + public String getVolumeUuid() { + return this.volumeUuid; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeCommand.java b/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeCommand.java index 70d1611687d..3d8880ff55e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeCommand.java +++ b/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeCommand.java @@ -23,20 +23,21 @@ import org.apache.cloudstack.storage.to.VolumeTO; import com.cloud.agent.api.Command; public class CreateVolumeCommand extends Command { - protected VolumeTO volumeInfo; - public CreateVolumeCommand(VolumeTO volumeInfo) { - super(); - this.volumeInfo = volumeInfo; - } - - protected CreateVolumeCommand() { - super(); - } - - @Override - public boolean executeInSequence() { - // TODO Auto-generated method stub - return false; - } + protected VolumeTO volumeInfo; + + public CreateVolumeCommand(VolumeTO volumeInfo) { + super(); + this.volumeInfo = volumeInfo; + } + + protected CreateVolumeCommand() { + super(); + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeFromBaseImageCommand.java b/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeFromBaseImageCommand.java index 0e520a9a076..0042c9504f2 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeFromBaseImageCommand.java +++ b/engine/storage/src/org/apache/cloudstack/storage/command/CreateVolumeFromBaseImageCommand.java @@ -24,16 +24,18 @@ import org.apache.cloudstack.storage.to.VolumeTO; import com.cloud.agent.api.Command; public class CreateVolumeFromBaseImageCommand extends Command { - private VolumeTO volume; - private ImageOnPrimayDataStoreTO image; - public CreateVolumeFromBaseImageCommand(VolumeTO volume, ImageOnPrimayDataStoreTO image) { - this.volume = volume; - this.image = image; - } - @Override - public boolean executeInSequence() { - // TODO Auto-generated method stub - return false; - } + private VolumeTO volume; + private ImageOnPrimayDataStoreTO image; + + public CreateVolumeFromBaseImageCommand(VolumeTO volume, ImageOnPrimayDataStoreTO image) { + this.volume = volume; + this.image = image; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreStatus.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreStatus.java index 65f46b1e156..5c61da00aa0 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreStatus.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreStatus.java @@ -19,11 +19,5 @@ package org.apache.cloudstack.storage.datastore; public enum DataStoreStatus { - Creating, - Up, - PrepareForMaintenance, - ErrorInMaintenance, - CancelMaintenance, - Maintenance, - Removed; + Creating, Up, PrepareForMaintenance, ErrorInMaintenance, CancelMaintenance, Maintenance, Removed; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultDataStore.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultDataStore.java index b95abe85dd7..206f917e00e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultDataStore.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultDataStore.java @@ -20,210 +20,209 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume; public class DefaultDataStore implements DataStore { - protected VolumeStrategy _volumeStrategy; - protected SnapshotStrategy _snapshotStrategy; - protected BackupStrategy _backupStrategy; - protected TemplateStrategy _templateStrategy; - protected String _uri; - protected String _uuid; - protected StoreType _type; - protected StoreScope _scope; - protected long _poolId; - protected DataStoreDriver _driverRef; - protected DataStoreEndPointSelector _selector; - protected FileSystem _fs; - protected VolumeStrategy _volumeSt; - protected SnapshotStrategy _snapshotSt; - protected BackupStrategy _backupSt; - protected long _id; - protected DataStoreLifeCycle _dslf; - - public DefaultDataStore( - ) { - } + protected VolumeStrategy _volumeStrategy; + protected SnapshotStrategy _snapshotStrategy; + protected BackupStrategy _backupStrategy; + protected TemplateStrategy _templateStrategy; + protected String _uri; + protected String _uuid; + protected StoreType _type; + protected StoreScope _scope; + protected long _poolId; + protected DataStoreDriver _driverRef; + protected DataStoreEndPointSelector _selector; + protected FileSystem _fs; + protected VolumeStrategy _volumeSt; + protected SnapshotStrategy _snapshotSt; + protected BackupStrategy _backupSt; + protected long _id; + protected DataStoreLifeCycle _dslf; - public String getURI() { - // TODO Auto-generated method stub - return null; - } - - public void setURI(String uri) { - this._uri = uri; - } + public DefaultDataStore() { + } - public String getUUID() { - return this._uuid; - } - - public void setUUID(String uuid) { - this._uuid = uuid; - } + public String getURI() { + // TODO Auto-generated method stub + return null; + } - public StoreType getType() { - return this._type; - } - - public void setType(StoreType type) { - this._type = type; - } + public void setURI(String uri) { + this._uri = uri; + } - public StoreScope getScope() { - return this._scope; - } - - public void setScope(StoreScope scope) { - this._scope = scope; - } + public String getUUID() { + return this._uuid; + } - public Long getId() { - return this._id; - } - - public void setId(long id) { - this._id = id; - } + public void setUUID(String uuid) { + this._uuid = uuid; + } - public DataStoreDriver getDataStoreDriver() { - return this._driverRef; - } - - public void setDataStoreDriver(DataStoreDriver drv) { - this._driverRef = drv; - } + public StoreType getType() { + return this._type; + } - public void setEndPointSelector(DataStoreEndPointSelector selector) { - this._selector = selector; - } - - public DataStoreEndPointSelector getSelector() { - return this._selector; - } + public void setType(StoreType type) { + this._type = type; + } - public FileSystem getFileSystem() { - return this._fs; - } - - public void setFileSystem(FileSystem fs) { - this._fs = fs; - } + public StoreScope getScope() { + return this._scope; + } - public VolumeStrategy getVolumeStrategy() { - return this._volumeSt; - } - - public void setVolumeStrategy(VolumeStrategy vs) { - this._volumeSt = vs; - } + public void setScope(StoreScope scope) { + this._scope = scope; + } - public SnapshotStrategy getSnapshotStrategy() { - return this._snapshotSt; - } - - public void setSnapshotStrategy(SnapshotStrategy ss) { - this._snapshotSt = ss; - } + public Long getId() { + return this._id; + } - public BackupStrategy getBackupStrategy() { - return this._backupSt; - } - - public void setBackupStrategy(BackupStrategy bs) { - this._backupSt = bs; - } - - public TemplateStrategy getTemplateStrategy() { - return this._templateStrategy; - } - - public void setTemplateStrategy(TemplateStrategy ts) { - this._templateStrategy = ts; - } + public void setId(long id) { + this._id = id; + } - public DataStoreLifeCycle getLifeCycle() { - return this._dslf; - } - - public void setLifeCycle(DataStoreLifeCycle lf) { - this._dslf = lf; - } + public DataStoreDriver getDataStoreDriver() { + return this._driverRef; + } - public long getCluterId() { - // TODO Auto-generated method stub - return 0; - } + public void setDataStoreDriver(DataStoreDriver drv) { + this._driverRef = drv; + } - public long getPodId() { - // TODO Auto-generated method stub - return 0; - } + public void setEndPointSelector(DataStoreEndPointSelector selector) { + this._selector = selector; + } - public long getZoneId() { - // TODO Auto-generated method stub - return 0; - } + public DataStoreEndPointSelector getSelector() { + return this._selector; + } - public String getPath() { - // TODO Auto-generated method stub - return null; - } + public FileSystem getFileSystem() { + return this._fs; + } - public StoragePoolType getPoolType() { - // TODO Auto-generated method stub - return null; - } + public void setFileSystem(FileSystem fs) { + this._fs = fs; + } - public boolean isSharedStorage() { - // TODO Auto-generated method stub - return false; - } + public VolumeStrategy getVolumeStrategy() { + return this._volumeSt; + } - public StorageProvider getProvider() { - // TODO Auto-generated method stub - return null; - } + public void setVolumeStrategy(VolumeStrategy vs) { + this._volumeSt = vs; + } - public DataStoreEndPointSelector getEndPointSelector() { - // TODO Auto-generated method stub - return null; - } + public SnapshotStrategy getSnapshotStrategy() { + return this._snapshotSt; + } - public VolumeProfile prepareVolume(Volume volume, DataStore destStore) { - // TODO Auto-generated method stub - return null; - } + public void setSnapshotStrategy(SnapshotStrategy ss) { + this._snapshotSt = ss; + } - public SnapshotProfile prepareSnapshot(Snapshot snapshot, DataStore destStore) { - // TODO Auto-generated method stub - return null; - } + public BackupStrategy getBackupStrategy() { + return this._backupSt; + } - public TemplateProfile prepareTemplate(long templateId, DataStore destStore) { - // TODO Auto-generated method stub - return null; - } + public void setBackupStrategy(BackupStrategy bs) { + this._backupSt = bs; + } - public boolean contains(Volume volume) { - // TODO Auto-generated method stub - return false; - } + public TemplateStrategy getTemplateStrategy() { + return this._templateStrategy; + } - public boolean contains(Snapshot snapshot) { - // TODO Auto-generated method stub - return false; - } + public void setTemplateStrategy(TemplateStrategy ts) { + this._templateStrategy = ts; + } - public boolean contains(TemplateProfile template) { - // TODO Auto-generated method stub - return false; - } + public DataStoreLifeCycle getLifeCycle() { + return this._dslf; + } - public TemplateProfile get(TemplateProfile template) { - // TODO Auto-generated method stub - return null; - } + public void setLifeCycle(DataStoreLifeCycle lf) { + this._dslf = lf; + } - public StorageFilerTO getTO() { - // TODO Auto-generated method stub - return null; - } + public long getCluterId() { + // TODO Auto-generated method stub + return 0; + } + + public long getPodId() { + // TODO Auto-generated method stub + return 0; + } + + public long getZoneId() { + // TODO Auto-generated method stub + return 0; + } + + public String getPath() { + // TODO Auto-generated method stub + return null; + } + + public StoragePoolType getPoolType() { + // TODO Auto-generated method stub + return null; + } + + public boolean isSharedStorage() { + // TODO Auto-generated method stub + return false; + } + + public StorageProvider getProvider() { + // TODO Auto-generated method stub + return null; + } + + public DataStoreEndPointSelector getEndPointSelector() { + // TODO Auto-generated method stub + return null; + } + + public VolumeProfile prepareVolume(Volume volume, DataStore destStore) { + // TODO Auto-generated method stub + return null; + } + + public SnapshotProfile prepareSnapshot(Snapshot snapshot, DataStore destStore) { + // TODO Auto-generated method stub + return null; + } + + public TemplateProfile prepareTemplate(long templateId, DataStore destStore) { + // TODO Auto-generated method stub + return null; + } + + public boolean contains(Volume volume) { + // TODO Auto-generated method stub + return false; + } + + public boolean contains(Snapshot snapshot) { + // TODO Auto-generated method stub + return false; + } + + public boolean contains(TemplateProfile template) { + // TODO Auto-generated method stub + return false; + } + + public TemplateProfile get(TemplateProfile template) { + // TODO Auto-generated method stub + return null; + } + + public StorageFilerTO getTO() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultPrimaryDataStoreImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultPrimaryDataStoreImpl.java index 780435c114c..9981d68fd40 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultPrimaryDataStoreImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DefaultPrimaryDataStoreImpl.java @@ -36,144 +36,145 @@ import com.cloud.utils.exception.CloudRuntimeException; import edu.emory.mathcs.backport.java.util.Collections; public class DefaultPrimaryDataStoreImpl implements PrimaryDataStore { - private static final Logger s_logger = Logger.getLogger(DefaultPrimaryDataStoreImpl.class); - protected PrimaryDataStoreDriver driver; - protected DataStoreVO pdsv; - protected PrimaryDataStoreInfo pdsInfo; - @Inject - private VolumeDao volumeDao; - @Inject - private HostDao hostDao; - @Inject - TemplatePrimaryDataStoreManager templatePrimaryStoreMgr; - public DefaultPrimaryDataStoreImpl(PrimaryDataStoreDriver driver, DataStoreVO pdsv, PrimaryDataStoreInfo pdsInfo) { - this.driver = driver; - this.pdsv = pdsv; - this.pdsInfo = pdsInfo; - } - - @Override - public VolumeInfo getVolume(long id) { - VolumeVO volumeVO = volumeDao.findById(id); - VolumeObject vol = new VolumeObject(this, volumeVO); - return vol; - } + private static final Logger s_logger = Logger.getLogger(DefaultPrimaryDataStoreImpl.class); + protected PrimaryDataStoreDriver driver; + protected DataStoreVO pdsv; + protected PrimaryDataStoreInfo pdsInfo; + @Inject + private VolumeDao volumeDao; + @Inject + private HostDao hostDao; + @Inject + TemplatePrimaryDataStoreManager templatePrimaryStoreMgr; - @Override - public List getVolumes() { - // TODO Auto-generated method stub - return null; - } + public DefaultPrimaryDataStoreImpl(PrimaryDataStoreDriver driver, DataStoreVO pdsv, PrimaryDataStoreInfo pdsInfo) { + this.driver = driver; + this.pdsv = pdsv; + this.pdsInfo = pdsInfo; + } - @Override - public boolean deleteVolume(long id) { - // TODO Auto-generated method stub - return false; - } + @Override + public VolumeInfo getVolume(long id) { + VolumeVO volumeVO = volumeDao.findById(id); + VolumeObject vol = new VolumeObject(this, volumeVO); + return vol; + } - @Override - public List getEndPoints() { - Long clusterId = pdsv.getClusterId(); - if (clusterId == null) { - return null; - } - List endpoints = new ArrayList(); - List hosts = hostDao.findHypervisorHostInCluster(clusterId); - for (HostVO host : hosts) { - HypervisorHostEndPoint ep = new HypervisorHostEndPoint(host.getId()); - ComponentInject.inject(ep); - endpoints.add(ep); - } - Collections.shuffle(endpoints); - return endpoints; - } + @Override + public List getVolumes() { + // TODO Auto-generated method stub + return null; + } - @Override - public PrimaryDataStoreInfo getDataStoreInfo() { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean deleteVolume(long id) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean isHypervisorSupported(HypervisorType hypervisor) { - // TODO Auto-generated method stub - return false; - } + @Override + public List getEndPoints() { + Long clusterId = pdsv.getClusterId(); + if (clusterId == null) { + return null; + } + List endpoints = new ArrayList(); + List hosts = hostDao.findHypervisorHostInCluster(clusterId); + for (HostVO host : hosts) { + HypervisorHostEndPoint ep = new HypervisorHostEndPoint(host.getId()); + ComponentInject.inject(ep); + endpoints.add(ep); + } + Collections.shuffle(endpoints); + return endpoints; + } - @Override - public boolean isLocalStorageSupported() { - // TODO Auto-generated method stub - return false; - } + @Override + public PrimaryDataStoreInfo getDataStoreInfo() { + // TODO Auto-generated method stub + return null; + } - @Override - public boolean isVolumeDiskTypeSupported(VolumeDiskType diskType) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isHypervisorSupported(HypervisorType hypervisor) { + // TODO Auto-generated method stub + return false; + } - @Override - public long getCapacity() { - // TODO Auto-generated method stub - return 0; - } + @Override + public boolean isLocalStorageSupported() { + // TODO Auto-generated method stub + return false; + } - @Override - public long getAvailableCapacity() { - // TODO Auto-generated method stub - return 0; - } + @Override + public boolean isVolumeDiskTypeSupported(VolumeDiskType diskType) { + // TODO Auto-generated method stub + return false; + } - @Override - public VolumeObject createVolume(VolumeInfo vi, VolumeDiskType diskType) { - if (!pdsInfo.isVolumeDiskTypeSupported(diskType)) { - return null; - } - VolumeObject vo = (VolumeObject)vi; - vo.setVolumeDiskType(diskType); - this.driver.createVolume(vo); - return vo; - } + @Override + public long getCapacity() { + // TODO Auto-generated method stub + return 0; + } - @Override - public boolean exists(VolumeInfo vi) { - // TODO Auto-generated method stub - return false; - } + @Override + public long getAvailableCapacity() { + // TODO Auto-generated method stub + return 0; + } - @Override - public boolean templateExists(TemplateInfo template) { - return (templatePrimaryStoreMgr.findTemplateOnPrimaryDataStore(template, this) != null) ? true : false; - } + @Override + public VolumeObject createVolume(VolumeInfo vi, VolumeDiskType diskType) { + if (!pdsInfo.isVolumeDiskTypeSupported(diskType)) { + return null; + } + VolumeObject vo = (VolumeObject) vi; + vo.setVolumeDiskType(diskType); + this.driver.createVolume(vo); + return vo; + } - @Override - public VolumeDiskType getDefaultDiskType() { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean exists(VolumeInfo vi) { + // TODO Auto-generated method stub + return false; + } - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public boolean templateExists(TemplateInfo template) { + return (templatePrimaryStoreMgr.findTemplateOnPrimaryDataStore(template, this) != null) ? true : false; + } - @Override - public TemplateOnPrimaryDataStoreInfo getTemplate(TemplateInfo template) { - return templatePrimaryStoreMgr.findTemplateOnPrimaryDataStore(template, this); - } + @Override + public VolumeDiskType getDefaultDiskType() { + // TODO Auto-generated method stub + return null; + } - @Override - public VolumeInfo createVoluemFromBaseImage(VolumeInfo volume, TemplateOnPrimaryDataStoreInfo template) { - VolumeObject vo = (VolumeObject)volume; - vo.setVolumeDiskType(template.getTemplate().getDiskType()); - this.driver.createVolumeFromBaseImage(vo, template); - return volume; - } + @Override + public long getId() { + // TODO Auto-generated method stub + return 0; + } - @Override - public boolean installTemplate(TemplateOnPrimaryDataStoreInfo template) { - // TODO Auto-generated method stub - return true; - } + @Override + public TemplateOnPrimaryDataStoreInfo getTemplate(TemplateInfo template) { + return templatePrimaryStoreMgr.findTemplateOnPrimaryDataStore(template, this); + } + + @Override + public VolumeInfo createVoluemFromBaseImage(VolumeInfo volume, TemplateOnPrimaryDataStoreInfo template) { + VolumeObject vo = (VolumeObject) volume; + vo.setVolumeDiskType(template.getTemplate().getDiskType()); + this.driver.createVolumeFromBaseImage(vo, template); + return volume; + } + + @Override + public boolean installTemplate(TemplateOnPrimaryDataStoreInfo template) { + // TODO Auto-generated method stub + return true; + } } 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 fe0ec997117..4b8dd3c1b38 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStore.java @@ -30,19 +30,29 @@ import org.apache.cloudstack.storage.image.TemplateObject; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; import org.apache.cloudstack.storage.volume.VolumeObject; - public interface PrimaryDataStore extends PrimaryDataStoreInfo { - VolumeInfo getVolume(long id); - List getVolumes(); - boolean deleteVolume(long id); - VolumeInfo createVolume(VolumeInfo vo, VolumeDiskType diskType); - VolumeInfo createVoluemFromBaseImage(VolumeInfo volume, TemplateOnPrimaryDataStoreInfo templateStore); - List getEndPoints(); - PrimaryDataStoreInfo getDataStoreInfo(); - boolean exists(VolumeInfo vi); - boolean templateExists(TemplateInfo template); - TemplateOnPrimaryDataStoreInfo getTemplate(TemplateInfo template); - boolean installTemplate(TemplateOnPrimaryDataStoreInfo template); - VolumeDiskType getDefaultDiskType(); - + VolumeInfo getVolume(long id); + + List getVolumes(); + + boolean deleteVolume(long id); + + VolumeInfo createVolume(VolumeInfo vo, VolumeDiskType diskType); + + VolumeInfo createVoluemFromBaseImage(VolumeInfo volume, TemplateOnPrimaryDataStoreInfo templateStore); + + List getEndPoints(); + + PrimaryDataStoreInfo getDataStoreInfo(); + + boolean exists(VolumeInfo vi); + + boolean templateExists(TemplateInfo template); + + TemplateOnPrimaryDataStoreInfo getTemplate(TemplateInfo template); + + boolean installTemplate(TemplateOnPrimaryDataStoreInfo template); + + VolumeDiskType getDefaultDiskType(); + } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreInfoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreInfoImpl.java index 65b1bbb6668..c5ed961fbf1 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreInfoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/PrimaryDataStoreInfoImpl.java @@ -27,55 +27,54 @@ import org.apache.cloudstack.engine.subsystem.api.storage.disktype.VolumeDiskTyp import com.cloud.hypervisor.Hypervisor.HypervisorType; public class PrimaryDataStoreInfoImpl implements PrimaryDataStoreInfo { - protected List supportedHypervs; - protected List supportedDiskTypes; - protected long caapcity; - protected long avail; - protected boolean localStorage; - - public PrimaryDataStoreInfoImpl(List hypers, List diskTypes, - long capacity, long avail, boolean localStorage) { - this.avail = avail; - this.caapcity = capacity; - this.localStorage = localStorage; - this.supportedDiskTypes = diskTypes; - this.supportedHypervs = hypers; - } - - @Override - public boolean isHypervisorSupported(HypervisorType hypervisor) { - return this.supportedHypervs.contains(hypervisor) ? true : false; - } + protected List supportedHypervs; + protected List supportedDiskTypes; + protected long caapcity; + protected long avail; + protected boolean localStorage; - @Override - public boolean isLocalStorageSupported() { - return this.localStorage; - } + public PrimaryDataStoreInfoImpl(List hypers, List diskTypes, long capacity, long avail, boolean localStorage) { + this.avail = avail; + this.caapcity = capacity; + this.localStorage = localStorage; + this.supportedDiskTypes = diskTypes; + this.supportedHypervs = hypers; + } - @Override - public boolean isVolumeDiskTypeSupported(VolumeDiskType diskType) { - return this.supportedDiskTypes.contains(diskType) ? true : false; - } + @Override + public boolean isHypervisorSupported(HypervisorType hypervisor) { + return this.supportedHypervs.contains(hypervisor) ? true : false; + } - @Override - public long getCapacity() { - return this.caapcity; - } + @Override + public boolean isLocalStorageSupported() { + return this.localStorage; + } - @Override - public long getAvailableCapacity() { - return this.avail; - } + @Override + public boolean isVolumeDiskTypeSupported(VolumeDiskType diskType) { + return this.supportedDiskTypes.contains(diskType) ? true : false; + } - @Override - public List getEndPoints() { - // TODO Auto-generated method stub - return null; - } + @Override + public long getCapacity() { + return this.caapcity; + } - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public long getAvailableCapacity() { + return this.avail; + } + + @Override + public List getEndPoints() { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getId() { + // TODO Auto-generated method stub + return 0; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/DataStoreVO.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/DataStoreVO.java index 52f3bbf1e74..dc732d95a41 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/DataStoreVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/DataStoreVO.java @@ -39,155 +39,153 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.db.GenericDao; @Entity -@Table(name="storage_pool") +@Table(name = "storage_pool") public class DataStoreVO implements Identity { @Id - @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; - - @Column(name="name", updatable=false, nullable=false, length=255) - private String name = null; + @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; - @Column(name="uuid", length=255) - private String uuid = null; - - @Column(name="pool_type", updatable=false, nullable=false, length=32) + @Column(name = "name", updatable = false, nullable = false, length = 255) + private String name = null; + + @Column(name = "uuid", length = 255) + private String uuid = null; + + @Column(name = "pool_type", updatable = false, nullable = false, length = 32) private String protocol; - - @Column(name=GenericDao.CREATED_COLUMN) + + @Column(name = GenericDao.CREATED_COLUMN) Date created; - - @Column(name=GenericDao.REMOVED_COLUMN) + + @Column(name = GenericDao.REMOVED_COLUMN) private Date removed; - - @Column(name="update_time", updatable=true) - @Temporal(value=TemporalType.TIMESTAMP) + + @Column(name = "update_time", updatable = true) + @Temporal(value = TemporalType.TIMESTAMP) private Date updateTime; - - @Column(name="data_center_id", updatable=true, nullable=false) + + @Column(name = "data_center_id", updatable = true, nullable = false) private long dataCenterId; - - @Column(name="pod_id", updatable=true) + + @Column(name = "pod_id", updatable = true) private Long podId; - - @Column(name="available_bytes", updatable=true, nullable=true) + + @Column(name = "available_bytes", updatable = true, nullable = true) private long availableBytes; - - @Column(name="capacity_bytes", updatable=true, nullable=true) + + @Column(name = "capacity_bytes", updatable = true, nullable = true) private long capacityBytes; - @Column(name="status", updatable=true, nullable=false) - @Enumerated(value=EnumType.STRING) + @Column(name = "status", updatable = true, nullable = false) + @Enumerated(value = EnumType.STRING) private DataStoreStatus status; - - @Column(name="storage_provider", updatable=true, nullable=false) + + @Column(name = "storage_provider", updatable = true, nullable = false) private Long storageProvider; - - @Column(name="storage_type", nullable=false) + + @Column(name = "storage_type", nullable = false) private String storageType; - - @Column(name="host_address") + + @Column(name = "host_address") private String hostAddress; - - @Column(name="path") + + @Column(name = "path") private String path; - - @Column(name="port") + + @Column(name = "port") private int port; - @Column(name="user_info") + @Column(name = "user_info") private String userInfo; - @Column(name="cluster_id") + @Column(name = "cluster_id") private Long clusterId; - - public long getId() { - return id; - } - - public DataStoreStatus getStatus() { - return status; - } - public DataStoreVO() { - // TODO Auto-generated constructor stub - } + public long getId() { + return id; + } + + public DataStoreStatus getStatus() { + return status; + } + + public DataStoreVO() { + // TODO Auto-generated constructor stub + } public String getName() { - return name; - } + return name; + } public String getUuid() { - return uuid; - } - + return uuid; + } public String getPoolType() { - return protocol; - } + return protocol; + } public Date getCreated() { - return created; - } + return created; + } - public Date getRemoved() { - return removed; - } + public Date getRemoved() { + return removed; + } public Date getUpdateTime() { - return updateTime; - } + return updateTime; + } public long getDataCenterId() { - return dataCenterId; - } + return dataCenterId; + } public long getAvailableBytes() { - return availableBytes; - } + return availableBytes; + } - public Long getStorageProviderId() { - return storageProvider; - } - - public void setStorageProviderId(Long provider) { - storageProvider = provider; - } - - public String getStorageType() { - return storageType; - } - - public void setStorageType(String type) { - storageType = type; - } + public Long getStorageProviderId() { + return storageProvider; + } + + public void setStorageProviderId(Long provider) { + storageProvider = provider; + } + + public String getStorageType() { + return storageType; + } + + public void setStorageType(String type) { + storageType = type; + } public long getCapacityBytes() { - return capacityBytes; - } + return capacityBytes; + } - public void setAvailableBytes(long available) { - availableBytes = available; - } - - public void setCapacityBytes(long capacity) { - capacityBytes = capacity; - } + public void setAvailableBytes(long available) { + availableBytes = available; + } + + public void setCapacityBytes(long capacity) { + capacityBytes = capacity; + } - public Long getClusterId() { return clusterId; } - + public void setClusterId(Long clusterId) { this.clusterId = clusterId; } - + public String getHostAddress() { return hostAddress; } - + public String getPath() { return path; } @@ -195,62 +193,61 @@ public class DataStoreVO implements Identity { public String getUserInfo() { return userInfo; } - - public void setStatus(DataStoreStatus status) - { - this.status = status; + + public void setStatus(DataStoreStatus status) { + this.status = status; } - + public void setId(long id) { this.id = id; } - + public void setDataCenterId(long dcId) { this.dataCenterId = dcId; } - + public void setPodId(Long podId) { this.podId = podId; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public void setPath(String path) { - this.path = path; + this.path = path; } public void setUserInfo(String userInfo) { this.userInfo = userInfo; } - + public int getPort() { return port; } public Long getPodId() { - return podId; - } - - public void setName(String name) { - this.name = name; - } - - @Override + return podId; + } + + public void setName(String name) { + this.name = name; + } + + @Override public boolean equals(Object obj) { - if (!(obj instanceof DataStoreVO) || obj == null) { - return false; - } - DataStoreVO that = (DataStoreVO)obj; - return this.id == that.id; - } - - @Override - public int hashCode() { - return new Long(id).hashCode(); - } - + if (!(obj instanceof DataStoreVO) || obj == null) { + return false; + } + DataStoreVO that = (DataStoreVO) obj; + return this.id == that.id; + } + + @Override + public int hashCode() { + return new Long(id).hashCode(); + } + @Override public String toString() { return new StringBuilder("Pool[").append(id).append("|").append(protocol).append("]").toString(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java index 8016559a6b9..f5256325d91 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java @@ -25,82 +25,92 @@ import org.apache.cloudstack.storage.datastore.DataStoreStatus; import com.cloud.utils.db.GenericDao; - 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); - - /** - * 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); + + /** + * 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); - - + DataStoreVO persist(DataStoreVO 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); - + List findPoolsByTags(long dcId, long podId, Long clusterId, String[] tags, Boolean shared); - + /** * Find pool by UUID. * - * @param uuid uuid of pool. - * @return the single StoragePoolVO + * @param uuid + * uuid of pool. + * @return the single StoragePoolVO */ DataStoreVO findPoolByUUID(String uuid); List listByStorageHost(String hostFqdnOrIp); DataStoreVO 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(DataStoreStatus status); long countPoolsByStatus(DataStoreStatus... statuses); - List listByStatusInZone(long dcId, DataStoreStatus status); - + List listByStatusInZone(long dcId, DataStoreStatus status); + List listPoolsByCluster(long clusterId); } \ No newline at end of file diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index 442949957ba..9986525f469 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -34,6 +34,7 @@ import org.springframework.stereotype.Component; import com.cloud.storage.StoragePoolDetailVO; import com.cloud.storage.dao.StoragePoolDetailsDao; import com.cloud.storage.dao.StoragePoolDetailsDaoImpl; +import com.cloud.utils.component.ComponentInject; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; @@ -46,136 +47,126 @@ import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.exception.CloudRuntimeException; @Component -public class PrimaryDataStoreDaoImpl extends GenericDaoBase implements PrimaryDataStoreDao { +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; - - - protected final StoragePoolDetailsDao _detailsDao; - + protected final PrimaryDataStoreDetailsDao _detailsDao = null; + 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.data_center_id = ? and (storage_pool.pod_id = ? or storage_pool.pod_id is null) and ("; - private final String DetailsSqlSuffix = ") 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 FindPoolTagDetails = "SELECT storage_pool_details.name FROM storage_pool_details WHERE pool_id = ? and value = ?"; + protected 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().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(); + AllFieldSearch.done(); + + DcPodSearch = createSearchBuilder(); + DcPodSearch.and("datacenterId", DcPodSearch.entity().getDataCenterId(), 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().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(); - _detailsDao = ComponentLocator.inject(StoragePoolDetailsDaoImpl.class); + // _detailsDao = ComponentInject.inject(PrimaryDataStoreDetailsDaoImpl.class); } - - @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 DataStoreVO findPoolByUUID(String uuid) { - SearchCriteria sc = AllFieldSearch.create(); + @Override + public DataStoreVO 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) { + DataStoreVO pool = createForUpdate(id); + pool.setAvailableBytes(available); + update(id, pool); + } - @Override - public void updateAvailable(long id, long available) { - DataStoreVO pool = createForUpdate(id); - pool.setAvailableBytes(available); - update(id, pool); - } + @Override + public void updateCapacity(long id, long capacity) { + DataStoreVO pool = createForUpdate(id); + pool.setCapacityBytes(capacity); + update(id, pool); + } - @Override - public void updateCapacity(long id, long capacity) { - DataStoreVO 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(DataStoreStatus status){ + public List listByStatus(DataStoreStatus 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, DataStoreStatus status){ + public List listByStatusInZone(long dcId, DataStoreStatus 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 @@ -186,192 +177,190 @@ 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) { - if (clusterId != null) { - SearchCriteria sc = DcPodSearch.create(); + @Override + public List listBy(long datacenterId, long podId, Long clusterId) { + if (clusterId != null) { + SearchCriteria sc = DcPodSearch.create(); sc.setParameters("datacenterId", datacenterId); sc.setParameters("podId", podId); - + sc.setParameters("cluster", clusterId); return listBy(sc); - } else { - SearchCriteria sc = DcPodAnyClusterSearch.create(); - sc.setParameters("datacenterId", datacenterId); - sc.setParameters("podId", podId); - return listBy(sc); - } - } + } else { + SearchCriteria sc = DcPodAnyClusterSearch.create(); + sc.setParameters("datacenterId", datacenterId); + sc.setParameters("podId", podId); + 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 DataStoreVO listById(Integer id) - { + } + + public DataStoreVO listById(Integer id) { SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("id", id); - + return findOneIncludingRemovedBy(sc); - } - - @Override @DB - public DataStoreVO persist(DataStoreVO 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) { - 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); - 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, Boolean shared) { - List storagePools = null; - if (tags == null || tags.length == 0) { - storagePools = listBy(dcId, podId, clusterId); - } else { - Map details = tagsToDetails(tags); - storagePools = findPoolsByDetails(dcId, podId, clusterId, details); - } - - if (shared == null) { - return storagePools; - } else { - List filteredStoragePools = new ArrayList(storagePools); - for (DataStoreVO pool : storagePools) { - /* - if (shared != pool.isShared()) { - filteredStoragePools.remove(pool); - }*/ - } - - return filteredStoragePools; - } - } - - @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( DataStoreStatus... statuses) { + @DB + public DataStoreVO persist(DataStoreVO pool, Map details) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + pool = super.persist(pool); + if (details != null) { + for (Map.Entry detail : details.entrySet()) { + PrimaryDataStoreDetailVO vo = new PrimaryDataStoreDetailVO(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) { + 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); + 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, Boolean shared) { + List storagePools = null; + if (tags == null || tags.length == 0) { + storagePools = listBy(dcId, podId, clusterId); + } else { + Map details = tagsToDetails(tags); + storagePools = findPoolsByDetails(dcId, podId, clusterId, details); + } + + if (shared == null) { + return storagePools; + } else { + List filteredStoragePools = new ArrayList(storagePools); + for (DataStoreVO pool : storagePools) { + /* + * if (shared != pool.isShared()) { + * filteredStoragePools.remove(pool); } + */ + } + + return filteredStoragePools; + } + } + + @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(DataStoreStatus... 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/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java new file mode 100644 index 00000000000..d1f802de949 --- /dev/null +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailVO.java @@ -0,0 +1,79 @@ +// 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.datastore.db; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="storage_pool_details") +public class PrimaryDataStoreDetailVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; + + @Column(name="pool_id") + long poolId; + + @Column(name="name") + String name; + + @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; + } + + public long getPoolId() { + return poolId; + } + + public void setPoolId(long poolId) { + this.poolId = poolId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + protected PrimaryDataStoreDetailVO() { + } +} diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java new file mode 100644 index 00000000000..906742bb3f0 --- /dev/null +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDao.java @@ -0,0 +1,28 @@ +// 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.datastore.db; + +import java.util.Map; + +import com.cloud.storage.StoragePoolDetailVO; +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/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDaoImpl.java new file mode 100644 index 00000000000..59c488cf6d4 --- /dev/null +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDetailsDaoImpl.java @@ -0,0 +1,71 @@ +// 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.datastore.db; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.springframework.stereotype.Component; + +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 +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(); + */ + } + + @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()) { + PrimaryDataStoreDetailVO detail = new PrimaryDataStoreDetailVO(poolId, entry.getKey(), entry.getValue()); + persist(detail); + } + txn.commit(); + } + + @Override + public Map 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; + } +} diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDao.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDao.java index cebcacf3bdc..2fb556eb81d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDao.java @@ -21,5 +21,5 @@ package org.apache.cloudstack.storage.datastore.db; import com.cloud.utils.db.GenericDao; public interface PrimaryDataStoreProviderDao extends GenericDao { - + } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDaoImpl.java index bd0571d6be0..c65ca4c1f92 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderDaoImpl.java @@ -24,5 +24,5 @@ import com.cloud.utils.db.GenericDaoBase; @Component class PrimaryDataStoreProviderDaoImpl extends GenericDaoBase implements PrimaryDataStoreProviderDao { - + } \ No newline at end of file diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderVO.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderVO.java index 0d155802464..4047819ec71 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreProviderVO.java @@ -25,14 +25,14 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; @Entity -@Table(name="data_store_provider") +@Table(name = "data_store_provider") public class PrimaryDataStoreProviderVO { @Id - @TableGenerator(name="data_store_provider_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="data_store_provider_seq", allocationSize=1) - @Column(name="id", updatable=false, nullable = false) - private long id; - + @TableGenerator(name = "data_store_provider_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "data_store_provider_seq", allocationSize = 1) + @Column(name = "id", updatable = false, nullable = false) + private long id; + public long getId() { - return id; + return id; } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/DefaultPrimaryDataStoreDriverImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/DefaultPrimaryDataStoreDriverImpl.java index 630b3a76379..7a1e3354d72 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/DefaultPrimaryDataStoreDriverImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/DefaultPrimaryDataStoreDriverImpl.java @@ -20,92 +20,93 @@ import com.cloud.agent.api.Command; import com.cloud.utils.exception.CloudRuntimeException; @Component -public class DefaultPrimaryDataStoreDriverImpl implements - PrimaryDataStoreDriver { - private static final Logger s_logger = Logger.getLogger(DefaultPrimaryDataStoreDriverImpl.class); - @Override - public boolean createVolume(VolumeObject vol) { - //The default driver will send createvolume command to one of hosts which can access its datastore - List endPoints = vol.getDataStore().getEndPoints(); - int retries = 3; - VolumeInfo volInfo = vol; - CreateVolumeCommand createCmd = new CreateVolumeCommand(new VolumeTO(volInfo)); - Answer answer = null; - int i = 0; - boolean result = false; - - for (EndPoint ep : endPoints) { - answer = ep.sendMessage(createCmd); - if (answer == null) { - if (i < retries) { - s_logger.debug("create volume failed, retrying: " + i); - } - i++; - } else { - CreateVolumeAnswer volAnswer = (CreateVolumeAnswer)answer; - vol.setPath(volAnswer.getVolumeUuid()); - result = true; - } - } - - return result; - } +public class DefaultPrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver { + private static final Logger s_logger = Logger.getLogger(DefaultPrimaryDataStoreDriverImpl.class); - @Override - public boolean deleteVolume(VolumeObject vo) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean createVolume(VolumeObject vol) { + // The default driver will send createvolume command to one of hosts + // which can access its datastore + List endPoints = vol.getDataStore().getEndPoints(); + int retries = 3; + VolumeInfo volInfo = vol; + CreateVolumeCommand createCmd = new CreateVolumeCommand(new VolumeTO(volInfo)); + Answer answer = null; + int i = 0; + boolean result = false; - @Override - public String grantAccess(VolumeObject vol, EndPoint ep) { - // TODO Auto-generated method stub - return null; - } + for (EndPoint ep : endPoints) { + answer = ep.sendMessage(createCmd); + if (answer == null) { + if (i < retries) { + s_logger.debug("create volume failed, retrying: " + i); + } + i++; + } else { + CreateVolumeAnswer volAnswer = (CreateVolumeAnswer) answer; + vol.setPath(volAnswer.getVolumeUuid()); + result = true; + } + } - @Override - public boolean revokeAccess(VolumeObject vol, EndPoint ep) { - // TODO Auto-generated method stub - return false; - } - - protected Answer sendOutCommand(Command cmd, List endPoints) { - Answer answer = null; - int retries = 3; - int i = 0; - for (EndPoint ep : endPoints) { - answer = ep.sendMessage(cmd); - if (answer == null || answer.getDetails() != null) { - if (i < retries) { - s_logger.debug("create volume failed, retrying: " + i); - } - i++; - } else { - break; - } - } - return answer; - } + return result; + } - @Override - public boolean createVolumeFromBaseImage(VolumeObject volume, TemplateOnPrimaryDataStoreInfo template) { - VolumeTO vol = new VolumeTO(volume); - ImageOnPrimayDataStoreTO image = new ImageOnPrimayDataStoreTO(template); - CreateVolumeFromBaseImageCommand cmd = new CreateVolumeFromBaseImageCommand(vol, image); - List endPoints = volume.getDataStore().getEndPoints(); - - Answer answer = sendOutCommand(cmd, endPoints); - - if (answer == null || answer.getDetails() != null) { - if (answer == null) { - throw new CloudRuntimeException("Failed to created volume"); - } else { - throw new CloudRuntimeException(answer.getDetails()); - } - } else { - CreateVolumeAnswer volAnswer = (CreateVolumeAnswer)answer; - volume.setPath(volAnswer.getVolumeUuid()); - return true; - } - } + @Override + public boolean deleteVolume(VolumeObject vo) { + // TODO Auto-generated method stub + return false; + } + + @Override + public String grantAccess(VolumeObject vol, EndPoint ep) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean revokeAccess(VolumeObject vol, EndPoint ep) { + // TODO Auto-generated method stub + return false; + } + + protected Answer sendOutCommand(Command cmd, List endPoints) { + Answer answer = null; + int retries = 3; + int i = 0; + for (EndPoint ep : endPoints) { + answer = ep.sendMessage(cmd); + if (answer == null || answer.getDetails() != null) { + if (i < retries) { + s_logger.debug("create volume failed, retrying: " + i); + } + i++; + } else { + break; + } + } + return answer; + } + + @Override + public boolean createVolumeFromBaseImage(VolumeObject volume, TemplateOnPrimaryDataStoreInfo template) { + VolumeTO vol = new VolumeTO(volume); + ImageOnPrimayDataStoreTO image = new ImageOnPrimayDataStoreTO(template); + CreateVolumeFromBaseImageCommand cmd = new CreateVolumeFromBaseImageCommand(vol, image); + List endPoints = volume.getDataStore().getEndPoints(); + + Answer answer = sendOutCommand(cmd, endPoints); + + if (answer == null || answer.getDetails() != null) { + if (answer == null) { + throw new CloudRuntimeException("Failed to created volume"); + } else { + throw new CloudRuntimeException(answer.getDetails()); + } + } else { + CreateVolumeAnswer volAnswer = (CreateVolumeAnswer) answer; + volume.setPath(volAnswer.getVolumeUuid()); + return true; + } + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/PrimaryDataStoreDriver.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/PrimaryDataStoreDriver.java index 30f6c545e47..e3ff0b7226b 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/PrimaryDataStoreDriver.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/driver/PrimaryDataStoreDriver.java @@ -4,11 +4,14 @@ import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; import org.apache.cloudstack.storage.volume.VolumeObject; - public interface PrimaryDataStoreDriver { - boolean createVolume(VolumeObject vol); - boolean createVolumeFromBaseImage(VolumeObject volume, TemplateOnPrimaryDataStoreInfo template); - boolean deleteVolume(VolumeObject vo); - String grantAccess(VolumeObject vol, EndPoint ep); - boolean revokeAccess(VolumeObject vol, EndPoint ep); + boolean createVolume(VolumeObject vol); + + boolean createVolumeFromBaseImage(VolumeObject volume, TemplateOnPrimaryDataStoreInfo template); + + boolean deleteVolume(VolumeObject vo); + + String grantAccess(VolumeObject vol, EndPoint ep); + + boolean revokeAccess(VolumeObject vol, EndPoint ep); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/DefaultPrimaryDataStoreLifeCycleImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/DefaultPrimaryDataStoreLifeCycleImpl.java index fe4562c9102..a50ebdc5e2d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/DefaultPrimaryDataStoreLifeCycleImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/DefaultPrimaryDataStoreLifeCycleImpl.java @@ -25,46 +25,46 @@ import org.springframework.stereotype.Component; @Component public class DefaultPrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { - @Override - public boolean registerDataStore(Map dsInfos) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean registerDataStore(Map dsInfos) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean attach(long scope) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean attach(long scope) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean dettach(long dataStoreId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean dettach(long dataStoreId) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean unmanaged(long dataStoreId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean unmanaged(long dataStoreId) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean maintain(long dataStoreId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean maintain(long dataStoreId) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean cancelMaintain(long dataStoreId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean cancelMaintain(long dataStoreId) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean deleteDataStore(long dataStoreId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean deleteDataStore(long dataStoreId) { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/PrimaryDataStoreLifeCycle.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/PrimaryDataStoreLifeCycle.java index 2e41a62ee4a..99bb995cb7e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/PrimaryDataStoreLifeCycle.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/lifecycle/PrimaryDataStoreLifeCycle.java @@ -21,11 +21,17 @@ package org.apache.cloudstack.storage.datastore.lifecycle; import java.util.Map; public interface PrimaryDataStoreLifeCycle { - public boolean registerDataStore(Map dsInfos); - public boolean attach(long scope); - public boolean dettach(long dataStoreId); - public boolean unmanaged(long dataStoreId); - public boolean maintain(long dataStoreId); - public boolean cancelMaintain(long dataStoreId); - public boolean deleteDataStore(long dataStoreId); + public boolean registerDataStore(Map dsInfos); + + public boolean attach(long scope); + + public boolean dettach(long dataStoreId); + + public boolean unmanaged(long dataStoreId); + + public boolean maintain(long dataStoreId); + + public boolean cancelMaintain(long dataStoreId); + + public boolean deleteDataStore(long dataStoreId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/DefaultPrimaryDataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/DefaultPrimaryDataStoreManagerImpl.java index 4949b2faf67..e55b126e0f5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/DefaultPrimaryDataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/DefaultPrimaryDataStoreManagerImpl.java @@ -31,25 +31,26 @@ import org.springframework.stereotype.Component; @Component public class DefaultPrimaryDataStoreManagerImpl implements PrimaryDataStoreManager { - @Inject - PrimaryDataStoreProviderDao dataStoreProviderDao; - @Inject - PrimaryDataStoreProviderManager providerManager; - @Inject - PrimaryDataStoreDao dataStoreDao; - @Override - public PrimaryDataStore getPrimaryDataStore(long dataStoreId) { - DataStoreVO dataStoreVO = dataStoreDao.findById(dataStoreId); - Long providerId = dataStoreVO.getStorageProviderId(); - PrimaryDataStoreProvider provider = providerManager.getDataStoreProvider(providerId); - PrimaryDataStore dataStore = provider.getDataStore(dataStoreId); - return dataStore; - } + @Inject + PrimaryDataStoreProviderDao dataStoreProviderDao; + @Inject + PrimaryDataStoreProviderManager providerManager; + @Inject + PrimaryDataStoreDao dataStoreDao; - @Override - public PrimaryDataStoreLifeCycle getPrimaryDataStoreLifeCycle(long dataStoreId) { - // TODO Auto-generated method stub - return null; - } + @Override + public PrimaryDataStore getPrimaryDataStore(long dataStoreId) { + DataStoreVO dataStoreVO = dataStoreDao.findById(dataStoreId); + Long providerId = dataStoreVO.getStorageProviderId(); + PrimaryDataStoreProvider provider = providerManager.getDataStoreProvider(providerId); + PrimaryDataStore dataStore = provider.getDataStore(dataStoreId); + return dataStore; + } + + @Override + public PrimaryDataStoreLifeCycle getPrimaryDataStoreLifeCycle(long dataStoreId) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreManager.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreManager.java index b6ac34d3d76..7dd0276463e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/manager/PrimaryDataStoreManager.java @@ -22,6 +22,7 @@ import org.apache.cloudstack.storage.datastore.PrimaryDataStore; import org.apache.cloudstack.storage.datastore.lifecycle.PrimaryDataStoreLifeCycle; public interface PrimaryDataStoreManager { - public PrimaryDataStore getPrimaryDataStore(long dataStoreId); - public PrimaryDataStoreLifeCycle getPrimaryDataStoreLifeCycle(long dataStoreId); + public PrimaryDataStore getPrimaryDataStore(long dataStoreId); + + public PrimaryDataStoreLifeCycle getPrimaryDataStoreLifeCycle(long dataStoreId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DefaultPrimaryDatastoreProviderImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DefaultPrimaryDatastoreProviderImpl.java index 0d46c13876f..6126a8a388f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DefaultPrimaryDatastoreProviderImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/DefaultPrimaryDatastoreProviderImpl.java @@ -14,31 +14,31 @@ import org.springframework.stereotype.Component; import com.cloud.utils.component.ComponentInject; @Component -public class DefaultPrimaryDatastoreProviderImpl implements - PrimaryDataStoreProvider { - protected PrimaryDataStoreDriver driver; - @Inject - public PrimaryDataStoreDao dataStoreDao; +public class DefaultPrimaryDatastoreProviderImpl implements PrimaryDataStoreProvider { + protected PrimaryDataStoreDriver driver; + @Inject + public PrimaryDataStoreDao dataStoreDao; + + public DefaultPrimaryDatastoreProviderImpl() { + this.driver = new DefaultPrimaryDataStoreDriverImpl(); + } + + @Override + public PrimaryDataStore getDataStore(long dataStoreId) { + DataStoreVO dsv = dataStoreDao.findById(dataStoreId); + if (dsv == null) { + return null; + } + + PrimaryDataStore pds = new DefaultPrimaryDataStoreImpl(driver, dsv, null); + pds = ComponentInject.inject(pds); + return pds; + } + + @Override + public PrimaryDataStoreInfo getDataStoreInfo(long dataStoreId) { + // TODO Auto-generated method stub + return null; + } - public DefaultPrimaryDatastoreProviderImpl() { - this.driver = new DefaultPrimaryDataStoreDriverImpl(); - } - @Override - public PrimaryDataStore getDataStore(long dataStoreId) { - DataStoreVO dsv = dataStoreDao.findById(dataStoreId); - if (dsv == null) { - return null; - } - - PrimaryDataStore pds = new DefaultPrimaryDataStoreImpl(driver, dsv, null); - pds = ComponentInject.inject(pds); - return pds; - } - - @Override - public PrimaryDataStoreInfo getDataStoreInfo(long dataStoreId) { - // TODO Auto-generated method stub - return null; - } - } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProvider.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProvider.java index 7b076373193..dcc80931eac 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProvider.java @@ -3,9 +3,8 @@ package org.apache.cloudstack.storage.datastore.provider; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.storage.datastore.PrimaryDataStore; - - public interface PrimaryDataStoreProvider { - public PrimaryDataStore getDataStore(long dataStoreId); - public PrimaryDataStoreInfo getDataStoreInfo(long dataStoreId); + public PrimaryDataStore getDataStore(long dataStoreId); + + public PrimaryDataStoreInfo getDataStoreInfo(long dataStoreId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManager.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManager.java index 28f92509bc7..85a132f7591 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManager.java @@ -1,6 +1,5 @@ package org.apache.cloudstack.storage.datastore.provider; - public interface PrimaryDataStoreProviderManager { - public PrimaryDataStoreProvider getDataStoreProvider(Long providerId); + public PrimaryDataStoreProvider getDataStoreProvider(Long providerId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManagerImpl.java index 08755530c11..809a7e5783c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/provider/PrimaryDataStoreProviderManagerImpl.java @@ -23,10 +23,10 @@ import org.springframework.stereotype.Component; @Component public class PrimaryDataStoreProviderManagerImpl implements PrimaryDataStoreProviderManager { - @Override - public PrimaryDataStoreProvider getDataStoreProvider(Long providerId) { - // TODO Auto-generated method stub - return null; - } + @Override + public PrimaryDataStoreProvider getDataStoreProvider(Long providerId) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/type/ISCSI.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/type/ISCSI.java index 26d36def426..9b80bccd834 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/type/ISCSI.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/type/ISCSI.java @@ -23,9 +23,10 @@ import org.springframework.stereotype.Component; @Component public class ISCSI extends BaseType implements DataStoreType { - private final String type = "iscsi"; - @Override - public String toString() { - return type; - } + private final String type = "iscsi"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/type/NetworkFileSystem.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/type/NetworkFileSystem.java index 9340975f87c..f8801545ce5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/type/NetworkFileSystem.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/type/NetworkFileSystem.java @@ -23,9 +23,10 @@ import org.springframework.stereotype.Component; @Component public class NetworkFileSystem extends BaseType implements DataStoreType { - private final String type = "nfs"; - @Override - public String toString() { - return type; - } + private final String type = "nfs"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/type/SharedMount.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/type/SharedMount.java index c97a8939833..addf9019332 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/type/SharedMount.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/type/SharedMount.java @@ -21,9 +21,10 @@ package org.apache.cloudstack.storage.datastore.type; import org.apache.cloudstack.storage.BaseType; public class SharedMount extends BaseType implements DataStoreType { - private final String type = "SharedMountPoint"; - @Override - public String toString() { - return type; - } + private final String type = "SharedMountPoint"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/driver/AbstractStorageDriver.java b/engine/storage/src/org/apache/cloudstack/storage/driver/AbstractStorageDriver.java index 933a322078e..8b7837810a2 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/driver/AbstractStorageDriver.java +++ b/engine/storage/src/org/apache/cloudstack/storage/driver/AbstractStorageDriver.java @@ -31,46 +31,43 @@ import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; public abstract class AbstractStorageDriver implements DataStoreDriver { - protected DataStore _ds; - protected TemplateStrategy _ts; - - public AbstractStorageDriver(DataStore ds) { - _ds = ds; - _ts = ds.getTemplateStrategy(); - } - - public TemplateProfile install(TemplateProfile tp, DataStoreEndPoint ep) { - PrimaryStorageDownloadCommand dcmd = new PrimaryStorageDownloadCommand(tp.getName(), tp.getUrl(), tp.getFormat(), - 0, _ds.getId(), _ds.getUUID(), _ts.getDownloadWait()); - dcmd.setSecondaryStorageUrl(tp.getImageStorageUri()); - dcmd.setPrimaryStorageUrl(_ds.getURI()); - PrimaryStorageDownloadAnswer asw = (PrimaryStorageDownloadAnswer)ep.sendCommand(dcmd); + protected DataStore _ds; + protected TemplateStrategy _ts; - tp.setLocalPath(asw.getInstallPath()); - return tp; - } - - public TemplateProfile register(TemplateProfile tp, DataStoreEndPoint ep, boolean freshDownload) { - - DownloadCommand dcmd = - new DownloadCommand(_ds.getURI(), tp.getTemplate(), _ts.getMaxTemplateSizeInBytes()); - dcmd.setProxy(_ts.getHttpProxy()); - if (!freshDownload) { - dcmd = new DownloadProgressCommand(dcmd, tp.getJobId(), RequestType.GET_OR_RESTART); - } - - ep.sendCommand(dcmd); - return tp; - } - /* - public VolumeProfile createVolumeFromTemplate(VolumeProfile volProfile, TemplateProfile tp, DataStoreEndPoint ep) { - CreateCommand cmd = new CreateCommand(volProfile, tp.getLocalPath(), _ds.getTO()); - CreateAnswer ans = (CreateAnswer)ep.sendCommand(cmd); - VolumeTO created = ans.getVolume(); - DiskProfile diskProfile = new VolumeProfile(volProfile); - diskProfile.setPath(created.getPath()); - diskProfile.setSize(created.getSize()); - return diskProfile; - return null; - }*/ + public AbstractStorageDriver(DataStore ds) { + _ds = ds; + _ts = ds.getTemplateStrategy(); + } + + public TemplateProfile install(TemplateProfile tp, DataStoreEndPoint ep) { + PrimaryStorageDownloadCommand dcmd = new PrimaryStorageDownloadCommand(tp.getName(), tp.getUrl(), tp.getFormat(), 0, _ds.getId(), _ds.getUUID(), _ts.getDownloadWait()); + dcmd.setSecondaryStorageUrl(tp.getImageStorageUri()); + dcmd.setPrimaryStorageUrl(_ds.getURI()); + PrimaryStorageDownloadAnswer asw = (PrimaryStorageDownloadAnswer) ep.sendCommand(dcmd); + + tp.setLocalPath(asw.getInstallPath()); + return tp; + } + + public TemplateProfile register(TemplateProfile tp, DataStoreEndPoint ep, boolean freshDownload) { + + DownloadCommand dcmd = new DownloadCommand(_ds.getURI(), tp.getTemplate(), _ts.getMaxTemplateSizeInBytes()); + dcmd.setProxy(_ts.getHttpProxy()); + if (!freshDownload) { + dcmd = new DownloadProgressCommand(dcmd, tp.getJobId(), RequestType.GET_OR_RESTART); + } + + ep.sendCommand(dcmd); + return tp; + } + /* + * public VolumeProfile createVolumeFromTemplate(VolumeProfile volProfile, + * TemplateProfile tp, DataStoreEndPoint ep) { CreateCommand cmd = new + * CreateCommand(volProfile, tp.getLocalPath(), _ds.getTO()); CreateAnswer + * ans = (CreateAnswer)ep.sendCommand(cmd); VolumeTO created = + * ans.getVolume(); DiskProfile diskProfile = new VolumeProfile(volProfile); + * diskProfile.setPath(created.getPath()); + * diskProfile.setSize(created.getSize()); return diskProfile; return null; + * } + */ } diff --git a/engine/storage/src/org/apache/cloudstack/storage/driver/DefaultNfsSecondaryDriver.java b/engine/storage/src/org/apache/cloudstack/storage/driver/DefaultNfsSecondaryDriver.java index ec845145ab7..df1e0b3b05a 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/driver/DefaultNfsSecondaryDriver.java +++ b/engine/storage/src/org/apache/cloudstack/storage/driver/DefaultNfsSecondaryDriver.java @@ -29,62 +29,62 @@ import com.cloud.storage.TemplateProfile; public class DefaultNfsSecondaryDriver extends AbstractStorageDriver { - /** - * @param ds - */ - public DefaultNfsSecondaryDriver(DataStore ds) { - super(ds); - // TODO Auto-generated constructor stub - } + /** + * @param ds + */ + public DefaultNfsSecondaryDriver(DataStore ds) { + super(ds); + // TODO Auto-generated constructor stub + } - public String getDriverType() { - // TODO Auto-generated method stub - return null; - } + public String getDriverType() { + // TODO Auto-generated method stub + return null; + } - public TemplateProfile register(TemplateProfile tp, DataStoreEndPoint ep) { - // TODO Auto-generated method stub - return null; - } + public TemplateProfile register(TemplateProfile tp, DataStoreEndPoint ep) { + // TODO Auto-generated method stub + return null; + } - public DataObject create(DataObject obj) { - // TODO Auto-generated method stub - return null; - } + public DataObject create(DataObject obj) { + // TODO Auto-generated method stub + return null; + } - public DataObject copy(DataObject src, DataStore dest) { - // TODO Auto-generated method stub - return null; - } + public DataObject copy(DataObject src, DataStore dest) { + // TODO Auto-generated method stub + return null; + } - public DataObject copy(DataObject src, DataObject dest) { - // TODO Auto-generated method stub - return null; - } + public DataObject copy(DataObject src, DataObject dest) { + // TODO Auto-generated method stub + return null; + } - public DataObject move(DataObject src, DataObject dest) { - // TODO Auto-generated method stub - return null; - } + public DataObject move(DataObject src, DataObject dest) { + // TODO Auto-generated method stub + return null; + } - public Answer sendMessage(DataStoreEndPoint dsep, Command cmd) { - // TODO Auto-generated method stub - return null; - } + public Answer sendMessage(DataStoreEndPoint dsep, Command cmd) { + // TODO Auto-generated method stub + return null; + } - public boolean delete(DataObject obj) { - // TODO Auto-generated method stub - return false; - } + public boolean delete(DataObject obj) { + // TODO Auto-generated method stub + return false; + } - public org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile register(org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint ep) { - // TODO Auto-generated method stub - return null; - } + public org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile register(org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint ep) { + // TODO Auto-generated method stub + return null; + } - public VolumeProfile createVolumeFromTemplate(VolumeProfile vol, org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint dp) { - // TODO Auto-generated method stub - return null; - } + public VolumeProfile createVolumeFromTemplate(VolumeProfile vol, org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint dp) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/driver/XenServerStorageDriver.java b/engine/storage/src/org/apache/cloudstack/storage/driver/XenServerStorageDriver.java index b3de7210309..4b3bbe5c3b3 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/driver/XenServerStorageDriver.java +++ b/engine/storage/src/org/apache/cloudstack/storage/driver/XenServerStorageDriver.java @@ -26,56 +26,56 @@ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeProfile; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; - public class XenServerStorageDriver extends AbstractStorageDriver { - protected DataStore _ds; - public XenServerStorageDriver(DataStore ds) { - super(ds); - _ds = ds; - } - - public String getDriverType() { - // TODO Auto-generated method stub - return null; - } + protected DataStore _ds; - public DataObject create(DataObject obj) { - // TODO Auto-generated method stub - return null; - } + public XenServerStorageDriver(DataStore ds) { + super(ds); + _ds = ds; + } - public DataObject copy(DataObject src, DataStore dest) { - // TODO Auto-generated method stub - return null; - } + public String getDriverType() { + // TODO Auto-generated method stub + return null; + } - public DataObject copy(DataObject src, DataObject dest) { - // TODO Auto-generated method stub - return null; - } + public DataObject create(DataObject obj) { + // TODO Auto-generated method stub + return null; + } - public DataObject move(DataObject src, DataObject dest) { - // TODO Auto-generated method stub - return null; - } + public DataObject copy(DataObject src, DataStore dest) { + // TODO Auto-generated method stub + return null; + } - public Answer sendMessage(DataStoreEndPoint dsep, Command cmd) { - // TODO Auto-generated method stub - return null; - } + public DataObject copy(DataObject src, DataObject dest) { + // TODO Auto-generated method stub + return null; + } - public boolean delete(DataObject obj) { - // TODO Auto-generated method stub - return false; - } + public DataObject move(DataObject src, DataObject dest) { + // TODO Auto-generated method stub + return null; + } - public org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile register(org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint ep) { - // TODO Auto-generated method stub - return null; - } + public Answer sendMessage(DataStoreEndPoint dsep, Command cmd) { + // TODO Auto-generated method stub + return null; + } - public VolumeProfile createVolumeFromTemplate(VolumeProfile vol, org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint dp) { - // TODO Auto-generated method stub - return null; - } + public boolean delete(DataObject obj) { + // TODO Auto-generated method stub + return false; + } + + public org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile register(org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint ep) { + // TODO Auto-generated method stub + return null; + } + + public VolumeProfile createVolumeFromTemplate(VolumeProfile vol, org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile tp, DataStoreEndPoint dp) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/ImageManager.java b/engine/storage/src/org/apache/cloudstack/storage/image/ImageManager.java index e029fe23a36..a5b449779dd 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/ImageManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/ImageManager.java @@ -21,12 +21,12 @@ package org.apache.cloudstack.storage.image; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateProfile; - import com.cloud.api.commands.RegisterTemplateCmd; - public interface ImageManager { - TemplateProfile AssociateTemplateStoragePool(TemplateProfile tp, DataStore ds); - TemplateProfile getProfile(long templateId); - TemplateProfile allocateTemplateInDB(RegisterTemplateCmd cmd); + TemplateProfile AssociateTemplateStoragePool(TemplateProfile tp, DataStore ds); + + TemplateProfile getProfile(long templateId); + + TemplateProfile allocateTemplateInDB(RegisterTemplateCmd cmd); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/ImageManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/ImageManagerImpl.java index d1832960030..bcf42ce6cf3 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/ImageManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/ImageManagerImpl.java @@ -41,127 +41,125 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; public class ImageManagerImpl implements ImageManager { - private static final Logger s_logger = Logger.getLogger(ImageManagerImpl.class); - @Inject - VMTemplateDao _templateDao; - @Inject - VMTemplatePoolDao _templatePoolDao; - @Inject - DataCenterDao _dcDao; - - public boolean contains(VirtualMachineTemplate template, DataStore ds) { - long templateId = template.getId(); - long poolId = ds.getId(); - VMTemplateStoragePoolVO templateStoragePoolRef = null; - templateStoragePoolRef = _templatePoolDao.findByPoolTemplate(poolId, templateId); - return templateStoragePoolRef == null ? false : true; - } - - public TemplateProfile AssociateTemplateStoragePool(TemplateProfile tp, DataStore ds) { - long templateId = tp.getTemplateId(); - long poolId = ds.getId(); - VMTemplateStoragePoolVO templateStoragePoolRef = null; - long templateStoragePoolRefId; - - templateStoragePoolRef = _templatePoolDao.findByPoolTemplate(poolId, templateId); - if (templateStoragePoolRef != null) { - templateStoragePoolRef.setMarkedForGC(false); - _templatePoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef); + private static final Logger s_logger = Logger.getLogger(ImageManagerImpl.class); + @Inject + VMTemplateDao _templateDao; + @Inject + VMTemplatePoolDao _templatePoolDao; + @Inject + DataCenterDao _dcDao; - if (templateStoragePoolRef.getDownloadState() == Status.DOWNLOADED) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Template " + templateId + " has already been downloaded to pool " + poolId); - } + public boolean contains(VirtualMachineTemplate template, DataStore ds) { + long templateId = template.getId(); + long poolId = ds.getId(); + VMTemplateStoragePoolVO templateStoragePoolRef = null; + templateStoragePoolRef = _templatePoolDao.findByPoolTemplate(poolId, templateId); + return templateStoragePoolRef == null ? false : true; + } - tp.setLocalPath(templateStoragePoolRef.getInstallPath()); - tp.setTemplatePoolRefId(templateStoragePoolRef.getId()); - return tp; - } - } - - if (templateStoragePoolRef == null) { - templateStoragePoolRef = new VMTemplateStoragePoolVO(poolId, templateId); - try { - templateStoragePoolRef = _templatePoolDao.persist(templateStoragePoolRef); - templateStoragePoolRefId = templateStoragePoolRef.getId(); - } catch (Exception e) { - s_logger.debug("Assuming we're in a race condition: " + e.getMessage()); - templateStoragePoolRef = _templatePoolDao.findByPoolTemplate(poolId, templateId); - if (templateStoragePoolRef == null) { - throw new CloudRuntimeException("Unable to persist a reference for pool " + poolId + " and template " + templateId); - } - templateStoragePoolRefId = templateStoragePoolRef.getId(); - } - } else { - templateStoragePoolRefId = templateStoragePoolRef.getId(); - } - tp.setTemplatePoolRefId(templateStoragePoolRefId); - return tp; - } + public TemplateProfile AssociateTemplateStoragePool(TemplateProfile tp, DataStore ds) { + long templateId = tp.getTemplateId(); + long poolId = ds.getId(); + VMTemplateStoragePoolVO templateStoragePoolRef = null; + long templateStoragePoolRefId; - public TemplateProfile getProfile(long templateId) { - // TODO Auto-generated method stub - return null; - } - - protected TemplateProfile persistTemplate(TemplateProfile profile) { - Long zoneId = profile.getZoneId(); - VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(), - profile.getFeatured(), profile.getIsExtractable(), TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(), - profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(), - profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), - profile.getDetails(), profile.getSshKeyEnabled()); - - if (zoneId == null || zoneId.longValue() == -1) { + templateStoragePoolRef = _templatePoolDao.findByPoolTemplate(poolId, templateId); + if (templateStoragePoolRef != null) { + templateStoragePoolRef.setMarkedForGC(false); + _templatePoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef); + + if (templateStoragePoolRef.getDownloadState() == Status.DOWNLOADED) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Template " + templateId + " has already been downloaded to pool " + poolId); + } + + tp.setLocalPath(templateStoragePoolRef.getInstallPath()); + tp.setTemplatePoolRefId(templateStoragePoolRef.getId()); + return tp; + } + } + + if (templateStoragePoolRef == null) { + templateStoragePoolRef = new VMTemplateStoragePoolVO(poolId, templateId); + try { + templateStoragePoolRef = _templatePoolDao.persist(templateStoragePoolRef); + templateStoragePoolRefId = templateStoragePoolRef.getId(); + } catch (Exception e) { + s_logger.debug("Assuming we're in a race condition: " + e.getMessage()); + templateStoragePoolRef = _templatePoolDao.findByPoolTemplate(poolId, templateId); + if (templateStoragePoolRef == null) { + throw new CloudRuntimeException("Unable to persist a reference for pool " + poolId + " and template " + templateId); + } + templateStoragePoolRefId = templateStoragePoolRef.getId(); + } + } else { + templateStoragePoolRefId = templateStoragePoolRef.getId(); + } + tp.setTemplatePoolRefId(templateStoragePoolRefId); + return tp; + } + + public TemplateProfile getProfile(long templateId) { + // TODO Auto-generated method stub + return null; + } + + protected TemplateProfile persistTemplate(TemplateProfile profile) { + Long zoneId = profile.getZoneId(); + VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(), profile.getFeatured(), profile.getIsExtractable(), + TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(), profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(), + profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), profile.getDetails(), profile.getSshKeyEnabled()); + + if (zoneId == null || zoneId.longValue() == -1) { List dcs = _dcDao.listAll(); - + if (dcs.isEmpty()) { - throw new CloudRuntimeException("No zones are present in the system, can't add template"); + throw new CloudRuntimeException("No zones are present in the system, can't add template"); } template.setCrossZones(true); - for (DataCenterVO dc: dcs) { - _templateDao.addTemplateToZone(template, dc.getId()); - } + for (DataCenterVO dc : dcs) { + _templateDao.addTemplateToZone(template, dc.getId()); + } } else { - _templateDao.addTemplateToZone(template, zoneId); + _templateDao.addTemplateToZone(template, zoneId); } - return getProfile(template.getId()); - } - - protected boolean parameterCheck(RegisterTemplateCmd cmd) { - Long zoneId = cmd.getZoneId(); - if (zoneId == -1) { - zoneId = null; - } + return getProfile(template.getId()); + } + + protected boolean parameterCheck(RegisterTemplateCmd cmd) { + Long zoneId = cmd.getZoneId(); + if (zoneId == -1) { + zoneId = null; + } + + ImageFormat imgfmt = ImageFormat.valueOf(cmd.getFormat().toUpperCase()); + if (imgfmt == null) { + throw new IllegalArgumentException("Image format is incorrect " + cmd.getFormat() + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + } - ImageFormat imgfmt = ImageFormat.valueOf(cmd.getFormat().toUpperCase()); - if (imgfmt == null) { - throw new IllegalArgumentException("Image format is incorrect " + cmd.getFormat() + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); - } - // If a zoneId is specified, make sure it is valid if (zoneId != null) { - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new IllegalArgumentException("Please specify a valid zone."); - } + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new IllegalArgumentException("Please specify a valid zone."); + } } - + List systemvmTmplts = _templateDao.listAllSystemVMTemplates(); for (VMTemplateVO template : systemvmTmplts) { if (template.getName().equalsIgnoreCase(cmd.getTemplateName()) || template.getDisplayText().equalsIgnoreCase(cmd.getDisplayText())) { throw new IllegalArgumentException("Cannot use reserved names for templates"); } } - - return true; - } - public TemplateProfile allocateTemplateInDB(RegisterTemplateCmd cmd) { - parameterCheck(cmd); - //TemplateProfile tp = new TemplateProfile(cmd); - return persistTemplate(null); - } + return true; + } + + public TemplateProfile allocateTemplateInDB(RegisterTemplateCmd cmd) { + parameterCheck(cmd); + // TemplateProfile tp = new TemplateProfile(cmd); + return persistTemplate(null); + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestrator.java b/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestrator.java index f759d6b130f..e4141f3fa00 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestrator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestrator.java @@ -19,8 +19,11 @@ package org.apache.cloudstack.storage.image; public interface ImageOrchestrator { - void registerTemplate(long templateId); - void registerSnapshot(long snapshotId); - void registerVolume(long volumeId); - void registerIso(long isoId); + void registerTemplate(long templateId); + + void registerSnapshot(long snapshotId); + + void registerVolume(long volumeId); + + void registerIso(long isoId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestratorImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestratorImpl.java index 39564f3332e..8da27b5a1d5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestratorImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/ImageOrchestratorImpl.java @@ -32,47 +32,47 @@ import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.utils.component.Inject; public class ImageOrchestratorImpl implements ImageOrchestrator { - @Inject - SecondaryStorageManager _secStorageMgr; - @Inject - VMTemplateZoneDao _templateZoneDao; - public void registerTemplate(long templateId) { - List tpZones = _templateZoneDao.listByTemplateId(templateId); - - for (VMTemplateZoneVO tpZone : tpZones) { - DataStore imageStore = null; - List imageStores = _secStorageMgr.getImageStores(tpZone.getZoneId()); - for (DataStore imgStore : imageStores) { - TemplateStrategy ts = imgStore.getTemplateStrategy(); - if (ts.canRegister(templateId)) { - imageStore = imgStore; - break; - } - } - - if (imageStore == null) { - continue; - } - - TemplateStrategy ts = imageStore.getTemplateStrategy(); - ts.register(ts.get(templateId)); - } - } + @Inject + SecondaryStorageManager _secStorageMgr; + @Inject + VMTemplateZoneDao _templateZoneDao; - public void registerSnapshot(long snapshotId) { - // TODO Auto-generated method stub - - } + public void registerTemplate(long templateId) { + List tpZones = _templateZoneDao.listByTemplateId(templateId); - public void registerVolume(long volumeId) { - // TODO Auto-generated method stub - - } + for (VMTemplateZoneVO tpZone : tpZones) { + DataStore imageStore = null; + List imageStores = _secStorageMgr.getImageStores(tpZone.getZoneId()); + for (DataStore imgStore : imageStores) { + TemplateStrategy ts = imgStore.getTemplateStrategy(); + if (ts.canRegister(templateId)) { + imageStore = imgStore; + break; + } + } - public void registerIso(long isoId) { - // TODO Auto-generated method stub - - } + if (imageStore == null) { + continue; + } + TemplateStrategy ts = imageStore.getTemplateStrategy(); + ts.register(ts.get(templateId)); + } + } + + public void registerSnapshot(long snapshotId) { + // TODO Auto-generated method stub + + } + + public void registerVolume(long volumeId) { + // TODO Auto-generated method stub + + } + + public void registerIso(long isoId) { + // TODO Auto-generated method stub + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/ImageService.java b/engine/storage/src/org/apache/cloudstack/storage/image/ImageService.java index 8863a6a9f96..d657715eab5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/ImageService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/ImageService.java @@ -21,15 +21,22 @@ package org.apache.cloudstack.storage.image; import org.apache.cloudstack.engine.cloud.entity.api.TemplateEntity; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; - public interface ImageService { - boolean registerTemplate(long templateId, long imageStoreId); - boolean deleteTemplate(long templateId); - long registerIso(String isoUrl, long accountId); - boolean deleteIso(long isoId); - TemplateInfo grantTemplateAccess(TemplateInfo template, EndPoint endpointId); - boolean revokeTemplateAccess(long templateId, long endpointId); - String grantIsoAccess(long isoId, long endpointId); - boolean revokeIsoAccess(long isoId, long endpointId); - TemplateEntity getTemplateEntity(long templateId); + TemplateEntity registerTemplate(long templateId, long imageStoreId); + + boolean deleteTemplate(long templateId); + + long registerIso(String isoUrl, long accountId); + + boolean deleteIso(long isoId); + + boolean grantTemplateAccess(TemplateInfo template, EndPoint endpointId); + + boolean revokeTemplateAccess(long templateId, long endpointId); + + String grantIsoAccess(long isoId, long endpointId); + + boolean revokeIsoAccess(long isoId, long endpointId); + + TemplateEntity getTemplateEntity(long templateId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java index 18561e6d3a7..38f669b051f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java @@ -26,69 +26,66 @@ import org.apache.cloudstack.storage.image.downloader.ImageDownloader; import org.apache.cloudstack.storage.image.manager.ImageDataStoreManager; import org.apache.cloudstack.storage.image.provider.ImageDataStoreProviderManager; import org.apache.cloudstack.storage.image.store.ImageDataStore; +import org.springframework.stereotype.Component; +@Component public class ImageServiceImpl implements ImageService { + @Inject + ImageDataStoreProviderManager imageStoreProviderMgr; - @Inject - ImageDataStoreProviderManager imageStoreProviderMgr; - @Inject - - @Override - public boolean registerTemplate(long templateId, long imageStoreId) { - ImageDataStore ids = imageStoreProviderMgr.getDataStore(imageStoreId); - TemplateInfo template = ids.registerTemplate(templateId); - if (ids.needDownloadToCacheStorage()) { - ImageDownloader imageDl = ids.getImageDownloader(); - imageDl.downloadImage(template); - } - return true; - } + @Override + public TemplateEntity registerTemplate(long templateId, long imageStoreId) { + ImageDataStore ids = imageStoreProviderMgr.getDataStore(imageStoreId); + TemplateObject to = ids.registerTemplate(templateId); + return new TemplateEntityImpl(to); + } - @Override - public boolean deleteTemplate(long templateId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean deleteTemplate(long templateId) { + // TODO Auto-generated method stub + return false; + } - @Override - public long registerIso(String isoUrl, long accountId) { - // TODO Auto-generated method stub - return 0; - } + @Override + public long registerIso(String isoUrl, long accountId) { + // TODO Auto-generated method stub + return 0; + } - @Override - public boolean deleteIso(long isoId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean deleteIso(long isoId) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean revokeTemplateAccess(long templateId, long endpointId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean revokeTemplateAccess(long templateId, long endpointId) { + // TODO Auto-generated method stub + return false; + } - @Override - public String grantIsoAccess(long isoId, long endpointId) { - // TODO Auto-generated method stub - return null; - } + @Override + public String grantIsoAccess(long isoId, long endpointId) { + // TODO Auto-generated method stub + return null; + } - @Override - public boolean revokeIsoAccess(long isoId, long endpointId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean revokeIsoAccess(long isoId, long endpointId) { + // TODO Auto-generated method stub + return false; + } - @Override - public TemplateEntity getTemplateEntity(long templateId) { - TemplateObject to = imageStoreProviderMgr.getTemplate(templateId); - return new TemplateEntityImpl(to); - } + @Override + public TemplateEntity getTemplateEntity(long templateId) { + ImageDataStore dataStore = imageStoreProviderMgr.getDataStoreFromTemplateId(templateId); + TemplateObject to = dataStore.getTemplate(templateId); + return new TemplateEntityImpl(to); + } - @Override - public TemplateInfo grantTemplateAccess(TemplateInfo template, EndPoint endpointId) { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean grantTemplateAccess(TemplateInfo template, EndPoint endpointId) { + // TODO Auto-generated method stub + return true; + } } 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 384ca0d7b2c..e775d25f119 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateEntityImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateEntityImpl.java @@ -32,6 +32,7 @@ import com.cloud.storage.Storage.TemplateType; public class TemplateEntityImpl implements TemplateEntity { protected TemplateInfo templateInfo; + public TemplateEntityImpl(TemplateInfo templateInfo) { this.templateInfo = templateInfo; } @@ -40,7 +41,6 @@ public class TemplateEntityImpl implements TemplateEntity { return templateInfo.getImageDataStore(); } - public long getImageDataStoreId() { return getImageDataStore().getImageDataStoreId(); } @@ -51,14 +51,18 @@ public class TemplateEntityImpl implements TemplateEntity { @Override public String getUuid() { - // TODO Auto-generated method stub - return null; + return this.templateInfo.getUuid(); } @Override public long getId() { + return this.templateInfo.getId(); + } + + @Override + public String getExternalId() { // TODO Auto-generated method stub - return 0; + return null; } @Override diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateInfo.java b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateInfo.java index fedbafbb692..0e11f3eb358 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateInfo.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateInfo.java @@ -22,7 +22,13 @@ import org.apache.cloudstack.engine.subsystem.api.storage.disktype.VolumeDiskTyp import org.apache.cloudstack.storage.image.store.ImageDataStoreInfo; public interface TemplateInfo { - ImageDataStoreInfo getImageDataStore(); - long getId(); - VolumeDiskType getDiskType(); + ImageDataStoreInfo getImageDataStore(); + + long getId(); + + VolumeDiskType getDiskType(); + + String getPath(); + + String getUuid(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateObject.java b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateObject.java index 24c656ad2ee..5d65a3a13f7 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/TemplateObject.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/TemplateObject.java @@ -24,24 +24,38 @@ import org.apache.cloudstack.storage.image.db.ImageDataVO; import org.apache.cloudstack.storage.image.store.ImageDataStoreInfo; public class TemplateObject implements TemplateInfo { - private ImageDataVO imageVO; - public TemplateObject(ImageDataVO template) { - this.imageVO = template; - } - @Override - public ImageDataStoreInfo getImageDataStore() { - // TODO Auto-generated method stub - return null; - } + private ImageDataVO imageVO; + private ImageDataStoreInfo dataStore; - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } + public TemplateObject(ImageDataVO template, ImageDataStoreInfo dataStore) { + this.imageVO = template; + this.dataStore = dataStore; + } - @Override - public VolumeDiskType getDiskType() { - return VolumeDiskTypeHelper.getDiskType(imageVO.getFormat()); - } + @Override + public ImageDataStoreInfo getImageDataStore() { + return this.dataStore; + } + + @Override + public long getId() { + return this.imageVO.getId(); + } + + @Override + public VolumeDiskType getDiskType() { + return VolumeDiskTypeHelper.getDiskType(imageVO.getFormat()); + } + + @Override + public String getPath() { + //TODO: add installation path if it's downloaded to cache storage already + return this.imageVO.getUrl(); + } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDaoStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDaoStoreDaoImpl.java index 4f1a510095c..995aa5e8b88 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDaoStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDaoStoreDaoImpl.java @@ -21,6 +21,7 @@ package org.apache.cloudstack.storage.image.db; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; + @Component public class ImageDaoStoreDaoImpl extends GenericDaoBase implements ImageDataStoreDao { diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDao.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDao.java index b336ffa2db5..5f79e966f35 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDao.java @@ -31,41 +31,51 @@ import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; public interface ImageDataDao extends GenericDao { - public List listByPublic(); - public ImageDataVO findByName(String templateName); - public ImageDataVO findByTemplateName(String templateName); + public List listByPublic(); - //public void update(ImageDataVO template); + public ImageDataVO findByName(String templateName); + public ImageDataVO findByTemplateName(String templateName); - public List listAllSystemVMTemplates(); + // public void update(ImageDataVO template); - public List listDefaultBuiltinTemplates(); - public String getRoutingTemplateUniqueName(); - public List findIsosByIdAndPath(Long domainId, Long accountId, String path); - public List listReadyTemplates(); - public List listByAccountId(long accountId); - public 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); - - 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); + public List listAllSystemVMTemplates(); + + public List listDefaultBuiltinTemplates(); + + public String getRoutingTemplateUniqueName(); + + public List findIsosByIdAndPath(Long domainId, Long accountId, String path); + + public List listReadyTemplates(); + + public List listByAccountId(long accountId); + + public Set> searchTemplates(String name, String keyword, TemplateFilter templateFilter, boolean isIso, List hypers, Boolean bootable, DomainVO domain, + Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr, List permittedAccounts, Account caller, + ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags); + + 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); + + public long addTemplateToZone(ImageDataVO tmplt, long zoneId); + + public List listAllInZone(long dataCenterId); - public long addTemplateToZone(ImageDataVO tmplt, long zoneId); - public List listAllInZone(long dataCenterId); - 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); + ImageDataVO findSystemVMTemplate(long zoneId); + ImageDataVO findSystemVMTemplate(long zoneId, HypervisorType hType); ImageDataVO findRoutingTemplate(HypervisorType type); - List listPrivateTemplatesByHost(Long hostId); - public Long countTemplatesForAccount(long accountId); - -} + List listPrivateTemplatesByHost(Long hostId); + + public Long countTemplatesForAccount(long accountId); + +} diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java index 27b12fb8b40..5444a28096d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataDaoImpl.java @@ -59,6 +59,7 @@ import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.utils.Pair; +import com.cloud.utils.component.ComponentInject; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -74,26 +75,26 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class ImageDataDaoImpl extends GenericDaoBase implements ImageDataDao { private static final Logger s_logger = Logger.getLogger(VMTemplateDaoImpl.class); - - @Inject - VMTemplateZoneDao _templateZoneDao; - @Inject - VMTemplateDetailsDao _templateDetailsDao; - - @Inject - ConfigurationDao _configDao; - @Inject - HostDao _hostDao; - @Inject - DomainDao _domainDao; - @Inject - DataCenterDao _dcDao; - 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) "; - + + + VMTemplateZoneDao _templateZoneDao = null; + + VMTemplateDetailsDao _templateDetailsDao = null; + + + ConfigurationDao _configDao = null; + + HostDao _hostDao = null; + + DomainDao _domainDao = null; + + DataCenterDao _dcDao = null; + 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"; protected SearchBuilder TemplateNameSearch; @@ -111,39 +112,38 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen private SearchBuilder UserIsoSearch; private GenericSearchBuilder CountTemplatesByAccount; - ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); - - + //ResourceTagsDaoImpl _tagsDao = ComponentInject.inject(ResourceTagsDaoImpl.class); + ResourceTagsDaoImpl _tagsDao = null; private String routerTmpltName; private String consoleProxyTmpltName; - + protected ImageDataDaoImpl() { } - + @Override public List listByPublic() { - SearchCriteria sc = PublicSearch.create(); - sc.setParameters("public", 1); - return listBy(sc); - } - - @Override - public ImageDataVO findByName(String templateName) { - SearchCriteria sc = UniqueNameSearch.create(); - sc.setParameters("uniqueName", templateName); - return findOneIncludingRemovedBy(sc); - } - - @Override - public ImageDataVO 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 ImageDataVO findByName(String templateName) { + SearchCriteria sc = UniqueNameSearch.create(); + sc.setParameters("uniqueName", templateName); + return findOneIncludingRemovedBy(sc); + } + + @Override + public ImageDataVO 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()) { sb = PublicIsoSearch; @@ -154,9 +154,9 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen sb.and("type", sb.entity().getTemplateType(), SearchCriteria.Op.EQ); sb.and("bootable", sb.entity().isBootable(), SearchCriteria.Op.EQ); 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(); @@ -165,21 +165,21 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen sb.groupBy(sb.entity().getId()); 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); - } - - if (!listRemoved) { - sc.setParameters("removed", (Object)null); - } - - if (tags != null && !tags.isEmpty()) { + + 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 (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.ISO.toString()); for (String key : tags.keySet()) { @@ -188,12 +188,12 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen count++; } } - + return listBy(sc); } - + @Override - public List userIsoSearch(boolean listRemoved){ + public List userIsoSearch(boolean listRemoved) { SearchBuilder sb = null; sb = UserIsoSearch; @@ -203,25 +203,26 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen 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(ImageDataVO.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(ImageDataVO.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"; + 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"; List l = new ArrayList(); @@ -240,140 +241,139 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen } return l; } - - @Override - public List listReadyTemplates() { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("ready", SearchCriteria.Op.EQ, true); - sc.addAnd("format", SearchCriteria.Op.NEQ, Storage.ImageFormat.ISO); - return listIncludingRemovedBy(sc); - } - - @Override - public List findIsosByIdAndPath(Long domainId, Long accountId, String path) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("iso", SearchCriteria.Op.EQ, true); - if (domainId != null) { + + @Override + public List listReadyTemplates() { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("ready", SearchCriteria.Op.EQ, true); + sc.addAnd("format", SearchCriteria.Op.NEQ, Storage.ImageFormat.ISO); + return listIncludingRemovedBy(sc); + } + + @Override + public List findIsosByIdAndPath(Long domainId, Long accountId, String path) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("iso", SearchCriteria.Op.EQ, true); + if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } - if (accountId != null) { + 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); - - PublicSearch = createSearchBuilder(); - PublicSearch.and("public", PublicSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + boolean result = super.configure(name, params); - routerTmpltName = (String)params.get("routing.uniquename"); - - s_logger.debug("Found parameter routing unique name " + routerTmpltName); - if (routerTmpltName==null) { - routerTmpltName="routing"; - } - - consoleProxyTmpltName = (String)params.get("consoleproxy.uniquename"); - if(consoleProxyTmpltName == null) { + PublicSearch = createSearchBuilder(); + PublicSearch.and("public", PublicSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ); + + routerTmpltName = (String) params.get("routing.uniquename"); + + s_logger.debug("Found parameter routing unique name " + routerTmpltName); + if (routerTmpltName == null) { + routerTmpltName = "routing"; + } + + consoleProxyTmpltName = (String) params.get("consoleproxy.uniquename"); + if (consoleProxyTmpltName == null) { consoleProxyTmpltName = "routing"; } - if(s_logger.isDebugEnabled()) { + 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.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); + 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()); - - tmpltTypeSearch = createSearchBuilder(); + 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); + + 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(); - - 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(); + AccountIdSearch.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(); + SearchBuilder tmpltZoneSearch = _templateZoneDao.createSearchBuilder(); + tmpltZoneSearch.and("removed", tmpltZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + tmpltZoneSearch.and("zoneId", tmpltZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ); - return result; - } + 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(); - @Override - public String getRoutingTemplateUniqueName() { - return routerTmpltName; - } + 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(); + + 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, @@ -493,29 +493,27 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen 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) { + @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) { 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); + // chop the "," off + permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length() - 1); } - - Transaction txn = Transaction.currentTxn(); + + Transaction txn = Transaction.currentTxn(); txn.start(); - + /* Use LinkedHashSet here to guarantee iteration order */ Set> templateZonePairList = new LinkedHashSet>(); PreparedStatement pstmt = null; @@ -523,57 +521,57 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen 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 = ""; + 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; + 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 (templateFilter == TemplateFilter.sharedexecutable){ - 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 ((templateFilter == TemplateFilter.featured) || (templateFilter == TemplateFilter.community)) { + dataCenterJoin = " INNER JOIN data_center dc on (h.data_center_id = dc.id)"; + } + + if (templateFilter == TemplateFilter.sharedexecutable) { + 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()); + // 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 @@ -589,148 +587,154 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen } // get all child domain ID's - if (isAdmin(account.getType()) ) { + 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); + 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) && !isAdmin(caller.getType()) ) { - whereClause += attr + "t.account_id IN (" + permittedAccountsStr + ")"; + attr += " WHERE "; } - 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)"; - } + 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) + && !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) { - whereClause += " AND " + - " (t.account_id IN (" + permittedAccountsStr + ") OR" + - " lp.account_id IN (" + permittedAccountsStr + "))"; + 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 + "))"; + 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)"; - } + 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; + 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 (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 "; + whereClause += " WHERE "; } else if (!whereClause.equals(" WHERE ")) { - whereClause += " AND "; + whereClause += " AND "; } - - sql += whereClause + getExtrasWhere(templateFilter, name, keyword, isIso, bootable, hyperType, zoneId, - onlyReady, showDomr) + groupByClause + getOrderByLimit(pageSize, startIndex); + + sql += whereClause + getExtrasWhere(templateFilter, name, keyword, isIso, bootable, hyperType, zoneId, onlyReady, showDomr) + 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); + 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 + // 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); + 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 + // 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; + int i = 0; - if (startIndex > userIsos.size()) { - i=(int) (startIndex - userIsos.size()); - } + if (startIndex > userIsos.size()) { + i = (int) (startIndex - userIsos.size()); + } - for (; i < publicIsos.size(); i++) { - if(templateZonePairList.size() >= pageSize){ + for (; i < publicIsos.size(); i++) { + if (templateZonePairList.size() >= pageSize) { break; - } else { + } else { if (keyword != null && publicIsos.get(i).getName().contains(keyword)) { - templateZonePairList.add(new Pair(publicIsos.get(i).getId(), null)); + 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)); + 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)); + } 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); - } + 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 sql = ""; + return templateZonePairList; + } + + private String getExtrasWhere(TemplateFilter templateFilter, String name, String keyword, boolean isIso, Boolean bootable, HypervisorType hyperType, Long zoneId, boolean onlyReady, + boolean showDomr) { + String sql = ""; if (keyword != null) { sql += " t.name LIKE \"%" + keyword + "%\" AND"; } else if (name != null) { @@ -740,159 +744,161 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen if (isIso) { sql += " t.format = 'ISO'"; if (!hyperType.equals(HypervisorType.None)) { - sql += " AND goh.hypervisor_type = '" + hyperType.toString() + "'"; + sql += " AND goh.hypervisor_type = '" + hyperType.toString() + "'"; } } else { sql += " t.format <> 'ISO'"; if (!hyperType.equals(HypervisorType.None)) { - sql += " AND t.hypervisor_type = '" + hyperType.toString() + "'"; + 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 (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 (!showDomr) { + sql += " AND t.type != '" + Storage.TemplateType.SYSTEM.toString() + "'"; } - 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"; + } - 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(ImageDataVO tmplt, long zoneId) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - ImageDataVO 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 long addTemplateToZone(ImageDataVO tmplt, long zoneId) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + ImageDataVO 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(); - @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); - } + return tmplt.getId(); + } - @Override - public List listDefaultBuiltinTemplates() { - SearchCriteria sc = tmpltTypeSearch.create(); - sc.setParameters("templateType", Storage.TemplateType.BUILTIN); - return listBy(sc); - } - - @Override - public ImageDataVO 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); + @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); + } - //order by descending order of id and select the first (this is going to be the latest) - List tmplts = listBy(sc, new Filter(ImageDataVO.class, "id", false, null, 1l)); - - if (tmplts.size() > 0) { - return tmplts.get(0); - } else { - return null; - } - } - - public ImageDataVO 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); + @Override + public List listDefaultBuiltinTemplates() { + SearchCriteria sc = tmpltTypeSearch.create(); + sc.setParameters("templateType", Storage.TemplateType.BUILTIN); + return listBy(sc); + } - //order by descending order of id - List tmplts = listBy(sc, new Filter(ImageDataVO.class, "id", false, null, null)); - - for (ImageDataVO tmplt: tmplts) { - if (tmplt.getHypervisorType() == hType) { - return tmplt; - } - } - if (tmplts.size() > 0 && hType == HypervisorType.Any) { - return tmplts.get(0); - } - return null; - } - - @Override - public ImageDataVO findRoutingTemplate(HypervisorType hType) { - SearchCriteria sc = tmpltTypeHyperSearch2.create(); + @Override + public ImageDataVO findSystemVMTemplate(long zoneId) { + SearchCriteria sc = tmpltTypeHyperSearch.create(); sc.setParameters("templateType", Storage.TemplateType.SYSTEM); - sc.setParameters("hypervisorType", hType); + 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(ImageDataVO.class, "id", false, null, 1l)); - + if (tmplts.size() > 0) { return tmplts.get(0); } else { return null; } - } + } + + public ImageDataVO 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(ImageDataVO.class, "id", false, null, null)); + + for (ImageDataVO tmplt : tmplts) { + if (tmplt.getHypervisorType() == hType) { + return tmplt; + } + } + if (tmplts.size() > 0 && hType == HypervisorType.Any) { + return tmplts.get(0); + } + return null; + } + + @Override + public ImageDataVO findRoutingTemplate(HypervisorType hType) { + SearchCriteria sc = tmpltTypeHyperSearch2.create(); + sc.setParameters("templateType", Storage.TemplateType.SYSTEM); + sc.setParameters("hypervisorType", hType); + + // order by descending order of id and select the first (this is going + // to be the latest) + List tmplts = listBy(sc, new Filter(ImageDataVO.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); } - + @Override @DB public boolean remove(Long id) { @@ -900,7 +906,7 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen txn.start(); ImageDataVO template = createForUpdate(); template.setRemoved(new Date()); - + ImageDataVO vo = findById(id); if (vo != null) { if (vo.getFormat().equalsIgnoreCase(new ISO().toString())) { @@ -914,12 +920,9 @@ public class ImageDataDaoImpl extends GenericDaoBase implemen txn.commit(); return result; } - + private boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } - + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + } + } \ No newline at end of file diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderDao.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderDao.java index 466afa296f4..37a2fe97d6c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderDao.java @@ -21,5 +21,4 @@ package org.apache.cloudstack.storage.image.db; import com.cloud.utils.db.GenericDao; public interface ImageDataStoreProviderDao extends GenericDao { - } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderVO.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderVO.java index 799a4596318..5cc5b8ddcef 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreProviderVO.java @@ -25,25 +25,25 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; @Entity -@Table(name="image_data_store_provider") +@Table(name = "image_data_store_provider") public class ImageDataStoreProviderVO { @Id - @TableGenerator(name="image_data_store_provider_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="image_data_store_provider_seq", allocationSize=1) - @Column(name="id", nullable = false) + @TableGenerator(name = "image_data_store_provider_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "image_data_store_provider_seq", allocationSize = 1) + @Column(name = "id", nullable = false) private long id; - - @Column(name="name", nullable = false) + + @Column(name = "name", nullable = false) private String name; - + public long getId() { - return this.id; + return this.id; } - + public String getName() { - return this.name; + return this.name; } - + public void setName(String name) { - this.name = name; + this.name = name; } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreVO.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreVO.java index 7177203aa75..509441885da 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataStoreVO.java @@ -25,36 +25,36 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; @Entity -@Table(name="image_data_store") +@Table(name = "image_data_store") public class ImageDataStoreVO { @Id - @TableGenerator(name="image_data_store_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="image_data_store_seq", allocationSize=1) - @Column(name="id", nullable = false) + @TableGenerator(name = "image_data_store_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "image_data_store_seq", allocationSize = 1) + @Column(name = "id", nullable = false) private long id; - - @Column(name="name", nullable = false) + + @Column(name = "name", nullable = false) private String name; - - @Column(name="image_provider", nullable = false) + + @Column(name = "image_provider", nullable = false) private long provider; - + public long getId() { - return this.id; + return this.id; } - + public String getName() { - return this.name; + return this.name; } - + public long getProvider() { - return this.provider; + return this.provider; } - + public void setName(String name) { - this.name = name; + this.name = name; } - + public void setProvider(long provider) { - this.provider = provider; + this.provider = provider; } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java index eff2dbcc652..efce33cb1ba 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageDataVO.java @@ -41,101 +41,100 @@ import com.cloud.storage.Storage.TemplateType; import com.cloud.utils.db.GenericDao; @Entity -@Table(name="vm_template") +@Table(name = "vm_template") public class ImageDataVO implements Identity { @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 String 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") - private String 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="image_data_store_id") + + @Column(name = "image_data_store_id") private long imageDataStoreId; - + @Transient Map details; - public String getUniqueName() { return uniqueName; } @@ -145,7 +144,7 @@ public class ImageDataVO implements Identity { } protected ImageDataVO() { - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } public boolean getEnablePassword() { @@ -306,44 +305,44 @@ public class ImageDataVO implements Identity { public String getTemplateTag() { return templateTag; - } + } public void setTemplateTag(String templateTag) { this.templateTag = templateTag; - } + } public long getDomainId() { return -1; } - + @Override public String getUuid() { - return this.uuid; + return this.uuid; } - + public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } - + public Map getDetails() { - return this.details; + return this.details; } - + public void setDetails(Map details) { - this.details = details; + this.details = details; } @Override public boolean equals(Object that) { - if (this == that ) { + if (this == that) { return true; } - if (!(that instanceof VMTemplateVO)){ + if (!(that instanceof VMTemplateVO)) { return false; } - VMTemplateVO other = (VMTemplateVO)that; + VMTemplateVO other = (VMTemplateVO) that; - return ((this.getUniqueName().equals(other.getUniqueName()))); + return ((this.getUniqueName().equals(other.getUniqueName()))); } @Override @@ -353,6 +352,7 @@ public class ImageDataVO implements Identity { @Transient String toString; + @Override public String toString() { if (toString == null) { @@ -364,29 +364,29 @@ public class ImageDataVO implements Identity { public void setRemoved(Date removed) { this.removed = removed; } - + public void setSortKey(int key) { - sortKey = key; - } - - public int getSortKey() { - return sortKey; + sortKey = key; } - public boolean getEnableSshKey() { - return enableSshKey; - } - - public void setEnableSshKey(boolean enable) { - enableSshKey = enable; - } - - public long getImageDataStoreId() { - return this.imageDataStoreId; - } - - public void setImageDataStoreId(long dataStoreId) { - this.imageDataStoreId = dataStoreId; - } + public int getSortKey() { + return sortKey; + } + + public boolean getEnableSshKey() { + return enableSshKey; + } + + public void setEnableSshKey(boolean enable) { + enableSshKey = enable; + } + + public Long getImageDataStoreId() { + return this.imageDataStoreId; + } + + public void setImageDataStoreId(long dataStoreId) { + this.imageDataStoreId = dataStoreId; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/downloader/ImageDownloader.java b/engine/storage/src/org/apache/cloudstack/storage/image/downloader/ImageDownloader.java index ef9bc3f1465..adb247afd0f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/downloader/ImageDownloader.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/downloader/ImageDownloader.java @@ -21,5 +21,5 @@ package org.apache.cloudstack.storage.image.downloader; import org.apache.cloudstack.storage.image.TemplateInfo; public interface ImageDownloader { - public void downloadImage(TemplateInfo template); + public void downloadImage(TemplateInfo template); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriver.java b/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriver.java index 07f45154eb4..42e52e5eff4 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriver.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriver.java @@ -21,8 +21,11 @@ package org.apache.cloudstack.storage.image.driver; import org.apache.cloudstack.storage.image.TemplateInfo; public interface ImageDataStoreDriver { - boolean registerTemplate(TemplateInfo template); - String grantAccess(long templateId, long endPointId); - boolean revokeAccess(long templateId, long endPointId); - boolean deleteTemplate(TemplateInfo template); + boolean registerTemplate(TemplateInfo template); + + String grantAccess(long templateId, long endPointId); + + boolean revokeAccess(long templateId, long endPointId); + + boolean deleteTemplate(TemplateInfo template); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriverImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriverImpl.java index 714bee19eae..e395cf13c2f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriverImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/driver/ImageDataStoreDriverImpl.java @@ -21,33 +21,32 @@ package org.apache.cloudstack.storage.image.driver; import org.apache.cloudstack.storage.image.TemplateInfo; public class ImageDataStoreDriverImpl implements ImageDataStoreDriver { - - public ImageDataStoreDriverImpl() { - } - @Override - public boolean registerTemplate(TemplateInfo template) { - //TODO: check the availability of template - return true; - } - @Override - public String grantAccess(long templateId, long endPointId) { - // TODO Auto-generated method stub - return null; - } + public ImageDataStoreDriverImpl() { + } - @Override - public boolean revokeAccess(long templateId, long endPointId) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean registerTemplate(TemplateInfo template) { + // TODO: check the availability of template + return true; + } - @Override - public boolean deleteTemplate(TemplateInfo template) { - // TODO Auto-generated method stub - return false; - } + @Override + public String grantAccess(long templateId, long endPointId) { + // TODO Auto-generated method stub + return null; + } - + @Override + public boolean revokeAccess(long templateId, long endPointId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deleteTemplate(TemplateInfo template) { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/BAREMETAL.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/BAREMETAL.java index c3de2f1a31d..72e683be132 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/BAREMETAL.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/BAREMETAL.java @@ -23,9 +23,10 @@ import org.springframework.stereotype.Component; @Component public class BAREMETAL extends BaseType implements ImageFormat { - private final String type = "BAREMETAL"; - @Override - public String toString() { - return type; - } + private final String type = "BAREMETAL"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/ISO.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/ISO.java index f27d16b178a..2f01a276187 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/ISO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/ISO.java @@ -23,9 +23,10 @@ import org.springframework.stereotype.Component; @Component public class ISO extends BaseType implements ImageFormat { - private final String type = "ISO"; - @Override - public String toString() { - return type; - } + private final String type = "ISO"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/ImageFormatHelper.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/ImageFormatHelper.java index 6ecb9b05d43..9523d24c14e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/ImageFormatHelper.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/ImageFormatHelper.java @@ -26,19 +26,20 @@ import org.springframework.stereotype.Component; @Component public class ImageFormatHelper { - private static List formats; - private static final ImageFormat defaultFormat = new Unknown(); - @Inject - public void setFormats(List formats) { - ImageFormatHelper.formats = formats; - } - - public static ImageFormat getFormat(String format) { - for(ImageFormat fm : formats) { - if (fm.equals(format)) { - return fm; - } - } - return ImageFormatHelper.defaultFormat; - } + private static List formats; + private static final ImageFormat defaultFormat = new Unknown(); + + @Inject + public void setFormats(List formats) { + ImageFormatHelper.formats = formats; + } + + public static ImageFormat getFormat(String format) { + for (ImageFormat fm : formats) { + if (fm.equals(format)) { + return fm; + } + } + return ImageFormatHelper.defaultFormat; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/OVA.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/OVA.java index 46f77a00be2..77a355a0c86 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/OVA.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/OVA.java @@ -23,9 +23,10 @@ import org.springframework.stereotype.Component; @Component public class OVA extends BaseType implements ImageFormat { - private final String type = "OVA"; - @Override - public String toString() { - return type; - } + private final String type = "OVA"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/QCOW2.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/QCOW2.java index 9e13ebb62c8..d51052b8998 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/QCOW2.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/QCOW2.java @@ -23,9 +23,10 @@ import org.springframework.stereotype.Component; @Component("imageformat_qcow2") public class QCOW2 extends BaseType implements ImageFormat { - private final String type = "QCOW2"; - @Override - public String toString() { - return type; - } + private final String type = "QCOW2"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/Unknown.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/Unknown.java index 341be646b6b..992654e085b 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/Unknown.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/Unknown.java @@ -23,10 +23,10 @@ import org.springframework.stereotype.Component; @Component public class Unknown extends BaseType implements ImageFormat { - private final String type = "Unknown"; - - @Override - public String toString() { - return type; - } + private final String type = "Unknown"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/format/VHD.java b/engine/storage/src/org/apache/cloudstack/storage/image/format/VHD.java index 4a02e5fe893..f979ac35355 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/format/VHD.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/format/VHD.java @@ -19,11 +19,14 @@ package org.apache.cloudstack.storage.image.format; import org.apache.cloudstack.storage.BaseType; +import org.springframework.stereotype.Component; +@Component public class VHD extends BaseType implements ImageFormat { - private final String type = "VHD"; - @Override - public String toString() { - return type; - } + private final String type = "VHD"; + + @Override + public String toString() { + return type; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManager.java b/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManager.java index 878e394c9f9..e1dce500361 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManager.java @@ -21,5 +21,5 @@ package org.apache.cloudstack.storage.image.manager; import org.apache.cloudstack.storage.image.store.ImageDataStore; public interface ImageDataStoreManager { - ImageDataStore getImageDataStore(long dataStoreId); + ImageDataStore getImageDataStore(long dataStoreId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManagerImpl.java index ce9e78cec79..ebd60f14621 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/manager/ImageDataStoreManagerImpl.java @@ -27,15 +27,16 @@ import org.apache.cloudstack.storage.image.db.ImageDataStoreVO; import org.apache.cloudstack.storage.image.store.ImageDataStore; public class ImageDataStoreManagerImpl implements ImageDataStoreManager { - @Inject - ImageDataStoreDao dataStoreDao; - @Inject - ImageDataDao imageDataDao; - @Override - public ImageDataStore getImageDataStore(long dataStoreId) { - ImageDataStoreVO dataStore = dataStoreDao.findById(dataStoreId); - // TODO Auto-generated method stub - return null; - } + @Inject + ImageDataStoreDao dataStoreDao; + @Inject + ImageDataDao imageDataDao; + + @Override + public ImageDataStore getImageDataStore(long dataStoreId) { + ImageDataStoreVO dataStore = dataStoreDao.findById(dataStoreId); + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/motion/DefaultImageMotionStrategy.java b/engine/storage/src/org/apache/cloudstack/storage/image/motion/DefaultImageMotionStrategy.java index 14fe4664c77..7ec63e0160f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/motion/DefaultImageMotionStrategy.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/motion/DefaultImageMotionStrategy.java @@ -29,27 +29,29 @@ import org.apache.cloudstack.storage.to.ImageOnPrimayDataStoreTO; import org.apache.cloudstack.storage.to.TemplateTO; import org.apache.cloudstack.storage.to.VolumeTO; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; +import org.springframework.stereotype.Component; +@Component public class DefaultImageMotionStrategy implements ImageMotionStrategy { - @Override - public boolean canHandle(TemplateOnPrimaryDataStoreInfo templateStore) { - // TODO Auto-generated method stub - return true; - } + @Override + public boolean canHandle(TemplateOnPrimaryDataStoreInfo templateStore) { + // TODO Auto-generated method stub + return true; + } - @Override - public EndPoint getEndPoint(TemplateOnPrimaryDataStoreInfo templateStore) { - PrimaryDataStoreInfo pdi = templateStore.getPrimaryDataStore(); - return pdi.getEndPoints().get(0); - } + @Override + public EndPoint getEndPoint(TemplateOnPrimaryDataStoreInfo templateStore) { + PrimaryDataStoreInfo pdi = templateStore.getPrimaryDataStore(); + return pdi.getEndPoints().get(0); + } - @Override - public boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore, EndPoint ep) { - ImageOnPrimayDataStoreTO imageTo = new ImageOnPrimayDataStoreTO(templateStore); - CopyTemplateToPrimaryStorage copyCommand = new CopyTemplateToPrimaryStorage(imageTo); - ep.sendMessage(copyCommand); - return true; - } + @Override + public boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore, EndPoint ep) { + ImageOnPrimayDataStoreTO imageTo = new ImageOnPrimayDataStoreTO(templateStore); + CopyTemplateToPrimaryStorage copyCommand = new CopyTemplateToPrimaryStorage(imageTo); + ep.sendMessage(copyCommand); + return true; + } } 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 8351d398e21..9f481155418 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,6 +21,7 @@ package org.apache.cloudstack.storage.image.motion; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; public interface ImageMotionService { - boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore); - boolean copyIso(String isoUri, String destIsoUri); + boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore); + + boolean copyIso(String isoUri, String destIsoUri); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionServiceImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionServiceImpl.java index a4e6e400b77..3cf5efc6f69 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionServiceImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionServiceImpl.java @@ -31,41 +31,44 @@ import org.apache.cloudstack.storage.image.ImageService; import org.apache.cloudstack.storage.image.TemplateInfo; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; import org.apache.cloudstack.storage.volume.VolumeService; +import org.springframework.stereotype.Component; import com.cloud.utils.exception.CloudRuntimeException; +@Component public class ImageMotionServiceImpl implements ImageMotionService { - @Inject - List motionStrategies; - @Inject - VolumeService volumeService; - @Inject - ImageService imageService; - @Override - public boolean copyIso(String isoUri, String destIsoUri) { - // TODO Auto-generated method stub - return false; - } + @Inject + List motionStrategies; + @Inject + VolumeService volumeService; + @Inject + ImageService imageService; - @Override - public boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore) { - ImageMotionStrategy ims = null; - for (ImageMotionStrategy strategy : motionStrategies) { - if (strategy.canHandle(templateStore)) { - ims = strategy; - break; - } - } - - if (ims == null) { - throw new CloudRuntimeException("Can't find proper image motion strategy"); - } - - EndPoint ep = ims.getEndPoint(templateStore); - - volumeService.grantAccess(templateStore, ep); - TemplateInfo template = templateStore.getTemplate(); - imageService.grantTemplateAccess(template, ep); - return ims.copyTemplate(templateStore, ep); - } + @Override + public boolean copyIso(String isoUri, String destIsoUri) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore) { + ImageMotionStrategy ims = null; + for (ImageMotionStrategy strategy : motionStrategies) { + if (strategy.canHandle(templateStore)) { + ims = strategy; + break; + } + } + + if (ims == null) { + throw new CloudRuntimeException("Can't find proper image motion strategy"); + } + + EndPoint ep = ims.getEndPoint(templateStore); + + volumeService.grantAccess(templateStore, ep); + TemplateInfo template = templateStore.getTemplate(); + imageService.grantTemplateAccess(template, ep); + return ims.copyTemplate(templateStore, ep); + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionStrategy.java b/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionStrategy.java index 7e5de7d71d9..e1df9e29293 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionStrategy.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/motion/ImageMotionStrategy.java @@ -22,7 +22,9 @@ import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; public interface ImageMotionStrategy { - public boolean canHandle(TemplateOnPrimaryDataStoreInfo templateStore); - public EndPoint getEndPoint(TemplateOnPrimaryDataStoreInfo templateStore); - public boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore, EndPoint ep); + public boolean canHandle(TemplateOnPrimaryDataStoreInfo templateStore); + + public EndPoint getEndPoint(TemplateOnPrimaryDataStoreInfo templateStore); + + public boolean copyTemplate(TemplateOnPrimaryDataStoreInfo templateStore, EndPoint ep); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/provider/DefaultImageDataStoreProvider.java b/engine/storage/src/org/apache/cloudstack/storage/image/provider/DefaultImageDataStoreProvider.java index 2953f0b0383..bfb915feb5c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/provider/DefaultImageDataStoreProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/provider/DefaultImageDataStoreProvider.java @@ -31,23 +31,29 @@ import org.springframework.stereotype.Component; @Component public class DefaultImageDataStoreProvider implements ImageDataStoreProvider { - private final String providerName = "DefaultProvider"; - @Inject - ImageDataStoreProviderDao providerDao; - @Inject - ImageDataStoreDao imageStoreDao; - - @Override - public ImageDataStore getImageDataStore(long imageStoreId) { - ImageDataStoreVO idsv = imageStoreDao.findById(imageStoreId); - ImageDataStoreDriver driver = new ImageDataStoreDriverImpl(); - ImageDataStore ids = new ImageDataStoreImpl(idsv, driver, false, null); - return ids; - } + private final String providerName = "DefaultProvider"; + @Inject + ImageDataStoreProviderDao providerDao; + @Inject + ImageDataStoreDao imageStoreDao; - @Override - public String getName() { - return providerName; - } + @Override + public ImageDataStore getImageDataStore(long imageStoreId) { + ImageDataStoreVO idsv = imageStoreDao.findById(imageStoreId); + ImageDataStoreDriver driver = new ImageDataStoreDriverImpl(); + ImageDataStore ids = new ImageDataStoreImpl(idsv, driver, false, null); + return ids; + } + + @Override + public String getName() { + return providerName; + } + + @Override + public boolean register(long providerId) { + // TODO Auto-generated method stub + return true; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProvider.java b/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProvider.java index 495c652824d..8776827baa5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProvider.java @@ -21,6 +21,7 @@ package org.apache.cloudstack.storage.image.provider; import org.apache.cloudstack.storage.image.store.ImageDataStore; public interface ImageDataStoreProvider { - ImageDataStore getImageDataStore(long imageStoreId); - public String getName(); + ImageDataStore getImageDataStore(long imageStoreId); + boolean register(long providerId); + public String getName(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManager.java b/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManager.java index 407a64455f1..2359a2737e0 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManager.java @@ -21,9 +21,12 @@ package org.apache.cloudstack.storage.image.provider; import org.apache.cloudstack.storage.image.TemplateObject; import org.apache.cloudstack.storage.image.store.ImageDataStore; -public interface ImageDataStoreProviderManager { - public ImageDataStoreProvider getProvider(long providerId); - public ImageDataStore getDataStore(long dataStoreId); - public ImageDataStore getDataStoreFromTemplateId(long templateId); - public TemplateObject getTemplate(long templateId); +import com.cloud.utils.component.Manager; + +public interface ImageDataStoreProviderManager extends Manager { + public ImageDataStoreProvider getProvider(long providerId); + + public ImageDataStore getDataStore(Long dataStoreId); + + public ImageDataStore getDataStoreFromTemplateId(long templateId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManagerImpl.java index 62ef8e1bcd9..602973a8ab8 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/provider/ImageDataStoreProviderManagerImpl.java @@ -19,8 +19,10 @@ package org.apache.cloudstack.storage.image.provider; import java.util.List; +import java.util.Map; import javax.inject.Inject; +import javax.naming.ConfigurationException; import org.apache.cloudstack.storage.image.TemplateObject; import org.apache.cloudstack.storage.image.db.ImageDataDao; @@ -34,47 +36,94 @@ import org.springframework.stereotype.Component; @Component public class ImageDataStoreProviderManagerImpl implements ImageDataStoreProviderManager { - @Inject - ImageDataStoreProviderDao providerDao; - @Inject - ImageDataStoreDao dataStoreDao; - @Inject - ImageDataDao imageDataDao; - @Inject - List providers; - @Override - public ImageDataStoreProvider getProvider(long providerId) { - - return null; - } - - protected ImageDataStoreProvider getProvider(String name) { - for (ImageDataStoreProvider provider : providers) { - if (provider.getName().equalsIgnoreCase(name)) { - return provider; - } - } - return null; - } - - @Override - public ImageDataStore getDataStore(long dataStoreId) { - ImageDataStoreVO idsv = dataStoreDao.findById(dataStoreId); - long providerId = idsv.getProvider(); - ImageDataStoreProviderVO idspv = providerDao.findById(providerId); - ImageDataStoreProvider provider = getProvider(idspv.getName()); - return provider.getImageDataStore(dataStoreId); - } + @Inject + ImageDataStoreProviderDao providerDao; + @Inject + ImageDataStoreDao dataStoreDao; + @Inject + ImageDataDao imageDataDao; + @Inject + List providers; - @Override - public ImageDataStore getDataStoreFromTemplateId(long templateId) { - ImageDataVO iddv = imageDataDao.findById(templateId); - return getDataStore(iddv.getId()); - } + @Override + public ImageDataStoreProvider getProvider(long providerId) { - @Override - public TemplateObject getTemplate(long templateId) { - // TODO Auto-generated method stub - return null; - } + return null; + } + + protected ImageDataStoreProvider getProvider(String name) { + for (ImageDataStoreProvider provider : providers) { + if (provider.getName().equalsIgnoreCase(name)) { + return provider; + } + } + return null; + } + + @Override + public ImageDataStore getDataStore(Long dataStoreId) { + if (dataStoreId == null) { + return null; + } + + ImageDataStoreVO idsv = dataStoreDao.findById(dataStoreId); + if (idsv == null) { + return null; + } + + long providerId = idsv.getProvider(); + ImageDataStoreProviderVO idspv = providerDao.findById(providerId); + ImageDataStoreProvider provider = getProvider(idspv.getName()); + return provider.getImageDataStore(dataStoreId); + } + + @Override + public ImageDataStore getDataStoreFromTemplateId(long templateId) { + ImageDataVO iddv = imageDataDao.findById(templateId); + return getDataStore(iddv.getImageDataStoreId()); + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + List existingProviders = providerDao.listAll(); + //TODO: hold global lock + boolean foundExistingProvider = false; + for (ImageDataStoreProvider provider : providers) { + foundExistingProvider = false; + for (ImageDataStoreProviderVO existingProvider : existingProviders) { + if (provider.getName().equalsIgnoreCase(existingProvider.getName())) { + foundExistingProvider = true; + break; + } + } + + if (!foundExistingProvider) { + //add a new provider into db + ImageDataStoreProviderVO nProvider = new ImageDataStoreProviderVO(); + nProvider.setName(provider.getName()); + nProvider = providerDao.persist(nProvider); + provider.register(nProvider.getId()); + } + } + + return true; + } + + @Override + public boolean start() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean stop() { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStore.java b/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStore.java index 5422bad5a61..6e97c83ab48 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStore.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStore.java @@ -19,14 +19,21 @@ package org.apache.cloudstack.storage.image.store; import org.apache.cloudstack.storage.image.TemplateInfo; +import org.apache.cloudstack.storage.image.TemplateObject; import org.apache.cloudstack.storage.image.downloader.ImageDownloader; public interface ImageDataStore extends ImageDataStoreInfo { - TemplateInfo registerTemplate(long templateId); - String grantAccess(long templateId, long endPointId); - boolean revokeAccess(long templateId, long endPointId); - boolean deleteTemplate(long templateId); - boolean needDownloadToCacheStorage(); - - ImageDownloader getImageDownloader(); + TemplateObject registerTemplate(long templateId); + + String grantAccess(long templateId, long endPointId); + + boolean revokeAccess(long templateId, long endPointId); + + boolean deleteTemplate(long templateId); + + boolean needDownloadToCacheStorage(); + + ImageDownloader getImageDownloader(); + + TemplateObject getTemplate(long templateId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreImpl.java index dbe37d585d7..8f1b3735123 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreImpl.java @@ -21,6 +21,7 @@ package org.apache.cloudstack.storage.image.store; import javax.inject.Inject; import org.apache.cloudstack.storage.image.TemplateInfo; +import org.apache.cloudstack.storage.image.TemplateObject; import org.apache.cloudstack.storage.image.db.ImageDataDao; import org.apache.cloudstack.storage.image.db.ImageDataStoreDao; import org.apache.cloudstack.storage.image.db.ImageDataStoreVO; @@ -29,72 +30,76 @@ import org.apache.cloudstack.storage.image.downloader.ImageDownloader; import org.apache.cloudstack.storage.image.driver.ImageDataStoreDriver; public class ImageDataStoreImpl implements ImageDataStore { - @Inject - ImageDataDao imageDao; - ImageDataStoreDriver driver; - ImageDownloader downloader; - ImageDataStoreVO imageDataStoreVO; - boolean needDownloadToCacheStorage = false; - - - public ImageDataStoreImpl(ImageDataStoreVO dataStoreVO, ImageDataStoreDriver driver, boolean needDownloadToCacheStorage, ImageDownloader downloader) { - this.driver = driver; - this.needDownloadToCacheStorage = needDownloadToCacheStorage; - this.downloader = downloader; - this.imageDataStoreVO = dataStoreVO; - } - /* - @Override - public TemplateInfo registerTemplate(long templateId) { - ImageDataVO idv = imageDao.findById(templateId); - TemplateInfo template = new TemplateInfo(this, idv); - if (driver.registerTemplate(template)) { - template.setImageDataStoreId(imageDataStoreVO.getId()); - return template; - } else { - return null; - } - }*/ + @Inject + ImageDataDao imageDao; + ImageDataStoreDriver driver; + ImageDownloader downloader; + ImageDataStoreVO imageDataStoreVO; + boolean needDownloadToCacheStorage = false; - @Override - public String grantAccess(long templateId, long endPointId) { - ImageDataVO idv = imageDao.findById(templateId); - return idv.getUrl(); - } + public ImageDataStoreImpl(ImageDataStoreVO dataStoreVO, ImageDataStoreDriver driver, boolean needDownloadToCacheStorage, ImageDownloader downloader) { + this.driver = driver; + this.needDownloadToCacheStorage = needDownloadToCacheStorage; + this.downloader = downloader; + this.imageDataStoreVO = dataStoreVO; + } - @Override - public boolean revokeAccess(long templateId, long endPointId) { - // TODO Auto-generated method stub - return false; - } + /* + * @Override public TemplateInfo registerTemplate(long templateId) { + * ImageDataVO idv = imageDao.findById(templateId); TemplateInfo template = + * new TemplateInfo(this, idv); if (driver.registerTemplate(template)) { + * template.setImageDataStoreId(imageDataStoreVO.getId()); return template; + * } else { return null; } } + */ - @Override - public boolean deleteTemplate(long templateId) { - // TODO Auto-generated method stub - return false; - } + @Override + public String grantAccess(long templateId, long endPointId) { + ImageDataVO idv = imageDao.findById(templateId); + return idv.getUrl(); + } - @Override - public boolean needDownloadToCacheStorage() { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean revokeAccess(long templateId, long endPointId) { + // TODO Auto-generated method stub + return false; + } - @Override - public ImageDownloader getImageDownloader() { - return this.downloader; - } + @Override + public boolean deleteTemplate(long templateId) { + // TODO Auto-generated method stub + return false; + } - @Override - public long getImageDataStoreId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public boolean needDownloadToCacheStorage() { + // TODO Auto-generated method stub + return false; + } - @Override - public TemplateInfo registerTemplate(long templateId) { - // TODO Auto-generated method stub - return null; - } + @Override + public ImageDownloader getImageDownloader() { + return this.downloader; + } + + @Override + public long getImageDataStoreId() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public TemplateObject registerTemplate(long templateId) { + ImageDataVO image = imageDao.findById(templateId); + image.setImageDataStoreId(this.getImageDataStoreId()); + imageDao.update(templateId, image); + return getTemplate(templateId); + } + + @Override + public TemplateObject getTemplate(long templateId) { + ImageDataVO image = imageDao.findById(templateId); + TemplateObject to = new TemplateObject(image, this); + return to; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreInfo.java b/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreInfo.java index 7be4da0f784..a5d3d0f7eba 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreInfo.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/store/ImageDataStoreInfo.java @@ -19,5 +19,5 @@ package org.apache.cloudstack.storage.image.store; public interface ImageDataStoreInfo { - public long getImageDataStoreId(); + public long getImageDataStoreId(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultNfsSecondaryLifeCycle.java b/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultNfsSecondaryLifeCycle.java index 2786a99f0b5..4c71e436a9b 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultNfsSecondaryLifeCycle.java +++ b/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultNfsSecondaryLifeCycle.java @@ -22,33 +22,35 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; public class DefaultNfsSecondaryLifeCycle implements DataStoreLifeCycle { - protected DataStore _ds; - public DefaultNfsSecondaryLifeCycle(DataStore ds) { - _ds = ds; - } - public void add() { - // TODO Auto-generated method stub + protected DataStore _ds; - } + public DefaultNfsSecondaryLifeCycle(DataStore ds) { + _ds = ds; + } - public void delete() { - // TODO Auto-generated method stub + public void add() { + // TODO Auto-generated method stub - } + } - public void enable() { - // TODO Auto-generated method stub + public void delete() { + // TODO Auto-generated method stub - } + } - public void disable() { - // TODO Auto-generated method stub + public void enable() { + // TODO Auto-generated method stub - } + } - public void processEvent(DataStoreEvent event, Object... objs) { - // TODO Auto-generated method stub + public void disable() { + // TODO Auto-generated method stub - } + } + + public void processEvent(DataStoreEvent event, Object... objs) { + // TODO Auto-generated method stub + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultPrimaryDataStoreLifeCycle.java b/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultPrimaryDataStoreLifeCycle.java index f837bcc35b6..098c56a8020 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultPrimaryDataStoreLifeCycle.java +++ b/engine/storage/src/org/apache/cloudstack/storage/lifecycle/DefaultPrimaryDataStoreLifeCycle.java @@ -26,98 +26,98 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; public class DefaultPrimaryDataStoreLifeCycle implements DataStoreLifeCycle { - private static final Logger s_logger = Logger.getLogger(DataStoreLifeCycle.class); - private DataStore _ds; - @Inject - StoragePoolDao _storagePoolDao; - @Inject - StoragePoolHostDao _poolHostDao; - public DefaultPrimaryDataStoreLifeCycle(DataStore ds) { - this._ds = ds; - } - + private static final Logger s_logger = Logger.getLogger(DataStoreLifeCycle.class); + private DataStore _ds; + @Inject + StoragePoolDao _storagePoolDao; + @Inject + StoragePoolHostDao _poolHostDao; - protected boolean createStoragePool(DataStoreEndPoint ep, StoragePoolVO pool) { - DataStoreDriver dsDriver = _ds.getDataStoreDriver(); - CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, pool); - final Answer answer = dsDriver.sendMessage(ep, cmd); - if (answer != null && answer.getResult()) { - return true; - } else { - throw new CloudRuntimeException(answer.getDetails()); - } - } - - protected void connectHostToSharedPool(DataStoreEndPoint ep, StoragePoolVO pool) throws StorageUnavailableException { - DataStoreDriver dsDriver = _ds.getDataStoreDriver(); - long hostId = ep.getHostId(); - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool); - final Answer answer = dsDriver.sendMessage(ep, cmd); + public DefaultPrimaryDataStoreLifeCycle(DataStore ds) { + this._ds = ds; + } - if (answer == null) { - throw new StorageUnavailableException("Unable to get an answer to the modify storage pool command", pool.getId()); - } + protected boolean createStoragePool(DataStoreEndPoint ep, StoragePoolVO pool) { + DataStoreDriver dsDriver = _ds.getDataStoreDriver(); + CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, pool); + final Answer answer = dsDriver.sendMessage(ep, cmd); + if (answer != null && answer.getResult()) { + return true; + } else { + throw new CloudRuntimeException(answer.getDetails()); + } + } - if (!answer.getResult()) { - throw new StorageUnavailableException("Unable establish connection from storage head to storage pool " + pool.getId() + " due to " + answer.getDetails(), pool.getId()); - } + protected void connectHostToSharedPool(DataStoreEndPoint ep, StoragePoolVO pool) throws StorageUnavailableException { + DataStoreDriver dsDriver = _ds.getDataStoreDriver(); + long hostId = ep.getHostId(); + ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool); + final Answer answer = dsDriver.sendMessage(ep, cmd); - assert (answer instanceof ModifyStoragePoolAnswer) : "Well, now why won't you actually return the ModifyStoragePoolAnswer when it's ModifyStoragePoolCommand? Pool=" + pool.getId(); - ModifyStoragePoolAnswer mspAnswer = (ModifyStoragePoolAnswer) answer; + if (answer == null) { + throw new StorageUnavailableException("Unable to get an answer to the modify storage pool command", pool.getId()); + } - StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(pool.getId(), hostId); - if (poolHost == null) { - poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); - _poolHostDao.persist(poolHost); - } else { - poolHost.setLocalPath(mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); - } - pool.setAvailableBytes(mspAnswer.getPoolInfo().getAvailableBytes()); - pool.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes()); - _storagePoolDao.update(pool.getId(), pool); - } + if (!answer.getResult()) { + throw new StorageUnavailableException("Unable establish connection from storage head to storage pool " + pool.getId() + " due to " + answer.getDetails(), pool.getId()); + } - public void add() { - DataStoreEndPointSelector dseps = _ds.getEndPointSelector(); - List dsep = dseps.getEndPoints(null); - boolean success = false; - StoragePoolVO spool = _storagePoolDao.findById(_ds.getId()); - for (DataStoreEndPoint ep : dsep) { - success = createStoragePool(ep, spool); - if (success) { - break; - } - } + assert (answer instanceof ModifyStoragePoolAnswer) : "Well, now why won't you actually return the ModifyStoragePoolAnswer when it's ModifyStoragePoolCommand? Pool=" + pool.getId(); + ModifyStoragePoolAnswer mspAnswer = (ModifyStoragePoolAnswer) answer; - List poolHosts = new ArrayList(); - for (DataStoreEndPoint ep : dsep) { - try { - connectHostToSharedPool(ep, spool); - poolHosts.add(ep); - } catch (Exception e) { - s_logger.debug("Failed to add storage on this ep: " + ep.getHostId()); - } - } - } + StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(pool.getId(), hostId); + if (poolHost == null) { + poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); + _poolHostDao.persist(poolHost); + } else { + poolHost.setLocalPath(mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); + } + pool.setAvailableBytes(mspAnswer.getPoolInfo().getAvailableBytes()); + pool.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes()); + _storagePoolDao.update(pool.getId(), pool); + } - public void delete() { - // TODO Auto-generated method stub + public void add() { + DataStoreEndPointSelector dseps = _ds.getEndPointSelector(); + List dsep = dseps.getEndPoints(null); + boolean success = false; + StoragePoolVO spool = _storagePoolDao.findById(_ds.getId()); + for (DataStoreEndPoint ep : dsep) { + success = createStoragePool(ep, spool); + if (success) { + break; + } + } - } + List poolHosts = new ArrayList(); + for (DataStoreEndPoint ep : dsep) { + try { + connectHostToSharedPool(ep, spool); + poolHosts.add(ep); + } catch (Exception e) { + s_logger.debug("Failed to add storage on this ep: " + ep.getHostId()); + } + } + } - public void enable() { - // TODO Auto-generated method stub + public void delete() { + // TODO Auto-generated method stub - } + } - public void disable() { - // TODO Auto-generated method stub + public void enable() { + // TODO Auto-generated method stub - } + } - public void processEvent(DataStoreEvent event, Object... objs) { - // TODO Auto-generated method stub + public void disable() { + // TODO Auto-generated method stub - } + } + + public void processEvent(DataStoreEvent event, Object... objs) { + // TODO Auto-generated method stub + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManager.java b/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManager.java index 77375ab6fab..fe28ce9e14e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManager.java @@ -27,13 +27,17 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.utils.fsm.NoTransitionException; public interface BackupStorageManager { - boolean contains(Volume vol); - boolean contains(Snapshot snapshot); - boolean contains(VirtualMachineTemplate template); - - DataStore getBackupDataStore(Volume vol); - DataStore getBackupDataStore(Snapshot snapshot); - DataStore getBackupDataStore(VirtualMachineTemplate template); - - boolean updateOperationState(Volume vol, DataObjectBackupStorageOperationState.Event event) throws NoTransitionException; + boolean contains(Volume vol); + + boolean contains(Snapshot snapshot); + + boolean contains(VirtualMachineTemplate template); + + DataStore getBackupDataStore(Volume vol); + + DataStore getBackupDataStore(Snapshot snapshot); + + DataStore getBackupDataStore(VirtualMachineTemplate template); + + boolean updateOperationState(Volume vol, DataObjectBackupStorageOperationState.Event event) throws NoTransitionException; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManagerImpl.java index 9a6b629f67c..49bc673c002 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/manager/BackupStorageManagerImpl.java @@ -28,39 +28,39 @@ import com.cloud.utils.fsm.NoTransitionException; public class BackupStorageManagerImpl implements BackupStorageManager { - public boolean contains(Volume vol) { - // TODO Auto-generated method stub - return false; - } + public boolean contains(Volume vol) { + // TODO Auto-generated method stub + return false; + } - public boolean contains(Snapshot snapshot) { - // TODO Auto-generated method stub - return false; - } + public boolean contains(Snapshot snapshot) { + // TODO Auto-generated method stub + return false; + } - public boolean contains(VirtualMachineTemplate template) { - // TODO Auto-generated method stub - return false; - } + public boolean contains(VirtualMachineTemplate template) { + // TODO Auto-generated method stub + return false; + } - public DataStore getBackupDataStore(Volume vol) { - // TODO Auto-generated method stub - return null; - } + public DataStore getBackupDataStore(Volume vol) { + // TODO Auto-generated method stub + return null; + } - public DataStore getBackupDataStore(Snapshot snapshot) { - // TODO Auto-generated method stub - return null; - } + public DataStore getBackupDataStore(Snapshot snapshot) { + // TODO Auto-generated method stub + return null; + } - public DataStore getBackupDataStore(VirtualMachineTemplate template) { - // TODO Auto-generated method stub - return null; - } + public DataStore getBackupDataStore(VirtualMachineTemplate template) { + // TODO Auto-generated method stub + return null; + } - public boolean updateOperationState(Volume vol, Event event) throws NoTransitionException { - // TODO Auto-generated method stub - return false; - } + public boolean updateOperationState(Volume vol, Event event) throws NoTransitionException { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManager.java b/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManager.java index 6292ab8b553..3745e6777f9 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManager.java @@ -27,16 +27,17 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.StoragePool; public interface PrimaryDataStoreManager { - PrimaryDataStore addDataStore(long zoneId, long podId, long clusterId, long hostId, - String URI, - String storageType, - String poolName, - String storageProviderName, - Map params); - void deleteStoragePool(long poolId); - void enableStoragePool(long poolId); - void disableStoragePool(long poolId); - Map> getSupportedPrimaryStorages(long zoneId, HypervisorType hypervisor); - Map> getSupportedSecondaryStorages(long zoneId); - PrimaryDataStore getDataStore(String id); + PrimaryDataStore addDataStore(long zoneId, long podId, long clusterId, long hostId, String URI, String storageType, String poolName, String storageProviderName, Map params); + + void deleteStoragePool(long poolId); + + void enableStoragePool(long poolId); + + void disableStoragePool(long poolId); + + Map> getSupportedPrimaryStorages(long zoneId, HypervisorType hypervisor); + + Map> getSupportedSecondaryStorages(long zoneId); + + PrimaryDataStore getDataStore(String id); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManagerImpl.java index 2af2ef0324f..6c3ce746c71 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/manager/PrimaryDataStoreManagerImpl.java @@ -43,61 +43,61 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; public class PrimaryDataStoreManagerImpl implements PrimaryDataStoreManager { - @Inject(adapter = StorageProvider.class) - protected Adapters _storageProviders; - @Inject - protected DataCenterDao _dcDao; - @Inject - protected HostPodDao _podDao; - @Inject - protected ClusterDao _clusterDao; - @Inject - protected StoragePoolDao _storagePoolDao; + @Inject(adapter = StorageProvider.class) + protected Adapters _storageProviders; + @Inject + protected DataCenterDao _dcDao; + @Inject + protected HostPodDao _podDao; + @Inject + protected ClusterDao _clusterDao; + @Inject + protected StoragePoolDao _storagePoolDao; - public void deleteStoragePool(long poolId) { - StoragePool spool = _storagePoolDao.findById(poolId); - StorageProvider sp = findStorageProvider(spool.getStorageProvider()); - DataStore ds = sp.getDataStore(spool); - DataStoreLifeCycle dslc = ds.getLifeCycle(); - dslc.delete(); - } + public void deleteStoragePool(long poolId) { + StoragePool spool = _storagePoolDao.findById(poolId); + StorageProvider sp = findStorageProvider(spool.getStorageProvider()); + DataStore ds = sp.getDataStore(spool); + DataStoreLifeCycle dslc = ds.getLifeCycle(); + dslc.delete(); + } - public void enableStoragePool(long poolId) { - // TODO Auto-generated method stub - - } + public void enableStoragePool(long poolId) { + // TODO Auto-generated method stub - public void disableStoragePool(long poolId) { - // TODO Auto-generated method stub - - } + } - public Map> getSupportedPrimaryStorages(long zoneId, HypervisorType hypervisor) { - // TODO Auto-generated method stub - return null; - } + public void disableStoragePool(long poolId) { + // TODO Auto-generated method stub - public Map> getSupportedSecondaryStorages(long zoneId) { - // TODO Auto-generated method stub - return null; - } - - protected StorageProvider findStorageProvider(String name) { - Iterator spIter = _storageProviders.iterator(); - StorageProvider sp = null; - while (spIter.hasNext()) { - sp = spIter.next(); - if (sp.getProviderName().equalsIgnoreCase(name)) { - break; - } - } - - return sp; - } - - public StoragePool addStoragePool(long zoneId, long podId, long clusterId, long hostId, String URI, String storageType, String poolName, String storageProviderName, Map params) { - StoragePoolVO spool = new StoragePoolVO(); - long poolId = _storagePoolDao.getNextInSequence(Long.class, "id"); + } + + public Map> getSupportedPrimaryStorages(long zoneId, HypervisorType hypervisor) { + // TODO Auto-generated method stub + return null; + } + + public Map> getSupportedSecondaryStorages(long zoneId) { + // TODO Auto-generated method stub + return null; + } + + protected StorageProvider findStorageProvider(String name) { + Iterator spIter = _storageProviders.iterator(); + StorageProvider sp = null; + while (spIter.hasNext()) { + sp = spIter.next(); + if (sp.getProviderName().equalsIgnoreCase(name)) { + break; + } + } + + return sp; + } + + public StoragePool addStoragePool(long zoneId, long podId, long clusterId, long hostId, String URI, String storageType, String poolName, String storageProviderName, Map params) { + StoragePoolVO spool = new StoragePoolVO(); + long poolId = _storagePoolDao.getNextInSequence(Long.class, "id"); spool.setId(poolId); spool.setDataCenterId(zoneId); spool.setPodId(podId); @@ -107,36 +107,36 @@ public class PrimaryDataStoreManagerImpl implements PrimaryDataStoreManager { spool.setStorageType(storageType); spool.setStatus(StoragePoolStatus.Creating); spool = _storagePoolDao.persist(spool); - + StorageProvider sp = findStorageProvider(storageProviderName); - DataStore ds = sp.addDataStore((StoragePool)spool, URI, params); - + DataStore ds = sp.addDataStore((StoragePool) spool, URI, params); + DataStoreLifeCycle dslc = ds.getLifeCycle(); try { - dslc.add(); + dslc.add(); } catch (CloudRuntimeException e) { - _storagePoolDao.remove(spool.getId()); - throw e; + _storagePoolDao.remove(spool.getId()); + throw e; } - + spool.setPath(ds.getURI()); spool.setUuid(ds.getUUID()); spool.setStatus(StoragePoolStatus.Up); _storagePoolDao.update(spool.getId(), spool); spool = _storagePoolDao.findById(spool.getId()); return spool; - } + } - @Override - public PrimaryDataStore addDataStore(long zoneId, long podId, long clusterId, long hostId, String URI, String storageType, String poolName, String storageProviderName, Map params) { - // TODO Auto-generated method stub - return null; - } + @Override + public PrimaryDataStore addDataStore(long zoneId, long podId, long clusterId, long hostId, String URI, String storageType, String poolName, String storageProviderName, Map params) { + // TODO Auto-generated method stub + return null; + } - @Override - public PrimaryDataStore getDataStore(String id) { - // TODO Auto-generated method stub - return null; - } + @Override + public PrimaryDataStore getDataStore(String id) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManager.java b/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManager.java index 3eda0cb2b4a..fb6baf67a36 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManager.java @@ -27,8 +27,11 @@ import com.cloud.storage.Volume; import com.cloud.template.VirtualMachineTemplate; public interface SecondaryStorageManager { - DataStore getStore(Volume volume); - DataStore getImageStore(DataStore destStore); - List getImageStores(long zoneId); - DataStore getStore(Snapshot snapshot); + DataStore getStore(Volume volume); + + DataStore getImageStore(DataStore destStore); + + List getImageStores(long zoneId); + + DataStore getStore(Snapshot snapshot); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManagerImpl.java index 7b4e29c4e50..5c58bd770e6 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/manager/SecondaryStorageManagerImpl.java @@ -27,29 +27,29 @@ import com.cloud.storage.Volume; import com.cloud.storage.dao.VMTemplateZoneDao; public class SecondaryStorageManagerImpl implements SecondaryStorageManager { - public DataStore getStore(Volume volume) { - // TODO Auto-generated method stub - return null; - } + public DataStore getStore(Volume volume) { + // TODO Auto-generated method stub + return null; + } - public DataStore getImageStore(DataStore destStore) { - // TODO Auto-generated method stub - return null; - } + public DataStore getImageStore(DataStore destStore) { + // TODO Auto-generated method stub + return null; + } - public List getImageStores() { - - return null; - } + public List getImageStores() { - public DataStore getStore(Snapshot snapshot) { - // TODO Auto-generated method stub - return null; - } + return null; + } - public List getImageStores(long zoneId) { - // TODO Auto-generated method stub - return null; - } + public DataStore getStore(Snapshot snapshot) { + // TODO Auto-generated method stub + return null; + } + + public List getImageStores(long zoneId) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultNfsSecondaryStorageProvider.java b/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultNfsSecondaryStorageProvider.java index 19ffae8de3f..0d375fa4f0d 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultNfsSecondaryStorageProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultNfsSecondaryStorageProvider.java @@ -39,91 +39,92 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.StoragePool; public class DefaultNfsSecondaryStorageProvider implements StorageProvider { - private String _name = DefaultPrimaryStorageProvider.class.toString(); - protected Map> _supportedProtocols; - public boolean configure(String name, Map params) throws ConfigurationException { - Map dscs = new HashMap(); - DataStoreConfigurator nfsdc = null; - dscs.put(nfsdc.getProtocol(), nfsdc); - - _supportedProtocols.put(HypervisorType.XenServer, dscs); - _supportedProtocols.put(HypervisorType.KVM, dscs); - _supportedProtocols.put(HypervisorType.VMware, dscs); - _supportedProtocols.put(HypervisorType.Ovm, dscs); - return true; - } + private String _name = DefaultPrimaryStorageProvider.class.toString(); + protected Map> _supportedProtocols; - public String getName() { - // TODO Auto-generated method stub - return null; - } + public boolean configure(String name, Map params) throws ConfigurationException { + Map dscs = new HashMap(); + DataStoreConfigurator nfsdc = null; + dscs.put(nfsdc.getProtocol(), nfsdc); - public boolean start() { - // TODO Auto-generated method stub - return false; - } + _supportedProtocols.put(HypervisorType.XenServer, dscs); + _supportedProtocols.put(HypervisorType.KVM, dscs); + _supportedProtocols.put(HypervisorType.VMware, dscs); + _supportedProtocols.put(HypervisorType.Ovm, dscs); + return true; + } - public boolean stop() { - // TODO Auto-generated method stub - return false; - } + public String getName() { + // TODO Auto-generated method stub + return null; + } - public List supportedHypervisors() { - List hypervisors = new ArrayList(); - Set hyps = _supportedProtocols.keySet(); - - for (HypervisorType hy : hyps) { - hypervisors.add(hy); - } - - return hypervisors; - } + public boolean start() { + // TODO Auto-generated method stub + return false; + } - public String getProviderName() { - // TODO Auto-generated method stub - return null; - } + public boolean stop() { + // TODO Auto-generated method stub + return false; + } - public void configure(Map storeProviderInfo) { - // TODO Auto-generated method stub + public List supportedHypervisors() { + List hypervisors = new ArrayList(); + Set hyps = _supportedProtocols.keySet(); - } + for (HypervisorType hy : hyps) { + hypervisors.add(hy); + } - public DataStore addDataStore(StoragePool sp, String url, Map params) { - URI uri; - try { - uri = new URI(url); - } catch (URISyntaxException e) { - throw new InvalidParameterValueException("invalide url" + url); - } - - String protocol = uri.getScheme(); - if (protocol == null) { - throw new InvalidParameterValueException("the protocol can't be null"); - } - - DataStoreConfigurator dscf = _supportedProtocols.get(HypervisorType.XenServer).get(protocol); - Map configs = dscf.getConfigs(uri, params); - dscf.validate(configs); - DataStore ds = dscf.getDataStore(sp); - return ds; - } + return hypervisors; + } - public DataStore getDataStore(StoragePool pool) { - // TODO Auto-generated method stub - return null; - } + public String getProviderName() { + // TODO Auto-generated method stub + return null; + } - public Map> getDataStoreConfigs() { - // TODO Auto-generated method stub - return null; - } + public void configure(Map storeProviderInfo) { + // TODO Auto-generated method stub - public List supportedStoreTypes() { - List types = new ArrayList(); - types.add(StoreType.Image); - types.add(StoreType.Backup); - return types; - } + } + + public DataStore addDataStore(StoragePool sp, String url, Map params) { + URI uri; + try { + uri = new URI(url); + } catch (URISyntaxException e) { + throw new InvalidParameterValueException("invalide url" + url); + } + + String protocol = uri.getScheme(); + if (protocol == null) { + throw new InvalidParameterValueException("the protocol can't be null"); + } + + DataStoreConfigurator dscf = _supportedProtocols.get(HypervisorType.XenServer).get(protocol); + Map configs = dscf.getConfigs(uri, params); + dscf.validate(configs); + DataStore ds = dscf.getDataStore(sp); + return ds; + } + + public DataStore getDataStore(StoragePool pool) { + // TODO Auto-generated method stub + return null; + } + + public Map> getDataStoreConfigs() { + // TODO Auto-generated method stub + return null; + } + + public List supportedStoreTypes() { + List types = new ArrayList(); + types.add(StoreType.Image); + types.add(StoreType.Backup); + return types; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultPrimaryStorageProvider.java b/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultPrimaryStorageProvider.java index fc88a1fe9ed..a5f73174cd9 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultPrimaryStorageProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/provider/DefaultPrimaryStorageProvider.java @@ -30,113 +30,112 @@ import com.cloud.storage.StoragePoolVO; import com.cloud.storage.dao.StoragePoolDao; public class DefaultPrimaryStorageProvider implements StorageProvider { - private String _name = DefaultPrimaryStorageProvider.class.toString(); - static Map> _supportedProtocols; - @Inject - protected ClusterDao _clusterDao; - - public List supportedHypervisors() { - List hypervisors = new ArrayList(); - hypervisors.add(Hypervisor.HypervisorType.XenServer); - return hypervisors; - } - - public DefaultPrimaryStorageProvider() { - Map dscs = new HashMap(); - DataStoreConfigurator nfsdc = null; - dscs.put(nfsdc.getProtocol(), nfsdc); - - _supportedProtocols.put(HypervisorType.XenServer, dscs); - } + private String _name = DefaultPrimaryStorageProvider.class.toString(); + static Map> _supportedProtocols; + @Inject + protected ClusterDao _clusterDao; - public List supportedStoreType() { - List type = new ArrayList(); - type.add(StoreType.Primary); - return type; - } + public List supportedHypervisors() { + List hypervisors = new ArrayList(); + hypervisors.add(Hypervisor.HypervisorType.XenServer); + return hypervisors; + } - public void configure(Map storeProviderInfo) { - // TODO Auto-generated method stub + public DefaultPrimaryStorageProvider() { + Map dscs = new HashMap(); + DataStoreConfigurator nfsdc = null; + dscs.put(nfsdc.getProtocol(), nfsdc); - } + _supportedProtocols.put(HypervisorType.XenServer, dscs); + } - public Map> getDataStoreConfigs() { - return _supportedProtocols; - } + public List supportedStoreType() { + List type = new ArrayList(); + type.add(StoreType.Primary); + return type; + } - public String getProviderName() { - return _name; - } + public void configure(Map storeProviderInfo) { + // TODO Auto-generated method stub - public DataStore createDataStore(HypervisorType hypervisor, - DataStoreConfigurator dsc) { - // TODO Auto-generated method stub - return null; - } - - public DataStore getDataStore(StoragePool pool) { - ClusterVO clu = _clusterDao.findById(pool.getClusterId()); - HypervisorType hy = clu.getHypervisorType(); - Map dscs = _supportedProtocols.get(hy); - DataStoreConfigurator dsc = dscs.get(pool.getPoolType().toString()); - return dsc.getDataStore(pool); - } + } - public boolean configure(String name, Map params) throws ConfigurationException { - // TODO Auto-generated method stub - return false; - } + public Map> getDataStoreConfigs() { + return _supportedProtocols; + } - public String getName() { - // TODO Auto-generated method stub - return null; - } + public String getProviderName() { + return _name; + } - public boolean start() { - // TODO Auto-generated method stub - return false; - } + public DataStore createDataStore(HypervisorType hypervisor, DataStoreConfigurator dsc) { + // TODO Auto-generated method stub + return null; + } - public boolean stop() { - // TODO Auto-generated method stub - return false; - } + public DataStore getDataStore(StoragePool pool) { + ClusterVO clu = _clusterDao.findById(pool.getClusterId()); + HypervisorType hy = clu.getHypervisorType(); + Map dscs = _supportedProtocols.get(hy); + DataStoreConfigurator dsc = dscs.get(pool.getPoolType().toString()); + return dsc.getDataStore(pool); + } - public DataStore addDataStore(StoragePool spool, String url, Map params) { - URI uri; - try { - uri = new URI(url); - } catch (URISyntaxException e) { - throw new InvalidParameterValueException("invalide url" + url); - } + public boolean configure(String name, Map params) throws ConfigurationException { + // TODO Auto-generated method stub + return false; + } - String protocol = uri.getScheme(); - if (protocol == null) { - throw new InvalidParameterValueException("the protocol can't be null"); - } - - ClusterVO cluster = _clusterDao.findById(spool.getClusterId()); + public String getName() { + // TODO Auto-generated method stub + return null; + } - Map dscs = _supportedProtocols.get(cluster.getHypervisorType()); - if (dscs.isEmpty()) { - throw new InvalidParameterValueException("Doesn't support this hypervisor"); - } + public boolean start() { + // TODO Auto-generated method stub + return false; + } - DataStoreConfigurator dsc = dscs.get(protocol); - if (dsc == null) { - throw new InvalidParameterValueException("Doesn't support this protocol"); - } - - Map configs = dsc.getConfigs(uri, params); - dsc.validate(configs); - DataStore ds = dsc.getDataStore(spool); - - return ds; - } + public boolean stop() { + // TODO Auto-generated method stub + return false; + } - public List supportedStoreTypes() { - // TODO Auto-generated method stub - return null; - } + public DataStore addDataStore(StoragePool spool, String url, Map params) { + URI uri; + try { + uri = new URI(url); + } catch (URISyntaxException e) { + throw new InvalidParameterValueException("invalide url" + url); + } + + String protocol = uri.getScheme(); + if (protocol == null) { + throw new InvalidParameterValueException("the protocol can't be null"); + } + + ClusterVO cluster = _clusterDao.findById(spool.getClusterId()); + + Map dscs = _supportedProtocols.get(cluster.getHypervisorType()); + if (dscs.isEmpty()) { + throw new InvalidParameterValueException("Doesn't support this hypervisor"); + } + + DataStoreConfigurator dsc = dscs.get(protocol); + if (dsc == null) { + throw new InvalidParameterValueException("Doesn't support this protocol"); + } + + Map configs = dsc.getConfigs(uri, params); + dsc.validate(configs); + DataStore ds = dsc.getDataStore(spool); + + return ds; + } + + public List supportedStoreTypes() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/provider/HttpImageStoreProvider.java b/engine/storage/src/org/apache/cloudstack/storage/provider/HttpImageStoreProvider.java index 96e1219622b..846ff7a6bdc 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/provider/HttpImageStoreProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/provider/HttpImageStoreProvider.java @@ -33,59 +33,59 @@ import com.cloud.storage.StoragePool; public class HttpImageStoreProvider implements StorageProvider { - public boolean configure(String name, Map params) throws ConfigurationException { - // TODO Auto-generated method stub - return false; - } + public boolean configure(String name, Map params) throws ConfigurationException { + // TODO Auto-generated method stub + return false; + } - public String getName() { - // TODO Auto-generated method stub - return null; - } + public String getName() { + // TODO Auto-generated method stub + return null; + } - public boolean start() { - // TODO Auto-generated method stub - return false; - } + public boolean start() { + // TODO Auto-generated method stub + return false; + } - public boolean stop() { - // TODO Auto-generated method stub - return false; - } + public boolean stop() { + // TODO Auto-generated method stub + return false; + } - public List supportedHypervisors() { - // TODO Auto-generated method stub - return null; - } + public List supportedHypervisors() { + // TODO Auto-generated method stub + return null; + } - public String getProviderName() { - // TODO Auto-generated method stub - return null; - } + public String getProviderName() { + // TODO Auto-generated method stub + return null; + } - public List supportedStoreTypes() { - // TODO Auto-generated method stub - return null; - } + public List supportedStoreTypes() { + // TODO Auto-generated method stub + return null; + } - public void configure(Map storeProviderInfo) { - // TODO Auto-generated method stub + public void configure(Map storeProviderInfo) { + // TODO Auto-generated method stub - } + } - public DataStore addDataStore(StoragePool sp, String uri, Map params) { - // TODO Auto-generated method stub - return null; - } + public DataStore addDataStore(StoragePool sp, String uri, Map params) { + // TODO Auto-generated method stub + return null; + } - public DataStore getDataStore(StoragePool pool) { - // TODO Auto-generated method stub - return null; - } + public DataStore getDataStore(StoragePool pool) { + // TODO Auto-generated method stub + return null; + } - public Map> getDataStoreConfigs() { - // TODO Auto-generated method stub - return null; - } + public Map> getDataStoreConfigs() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/provider/S3SecondaryStorageProvider.java b/engine/storage/src/org/apache/cloudstack/storage/provider/S3SecondaryStorageProvider.java index 83f8a1f143e..d21e5e03d94 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/provider/S3SecondaryStorageProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/provider/S3SecondaryStorageProvider.java @@ -33,59 +33,59 @@ import com.cloud.storage.StoragePool; public class S3SecondaryStorageProvider implements StorageProvider { - public boolean configure(String name, Map params) throws ConfigurationException { - // TODO Auto-generated method stub - return false; - } + public boolean configure(String name, Map params) throws ConfigurationException { + // TODO Auto-generated method stub + return false; + } - public String getName() { - // TODO Auto-generated method stub - return null; - } + public String getName() { + // TODO Auto-generated method stub + return null; + } - public boolean start() { - // TODO Auto-generated method stub - return false; - } + public boolean start() { + // TODO Auto-generated method stub + return false; + } - public boolean stop() { - // TODO Auto-generated method stub - return false; - } + public boolean stop() { + // TODO Auto-generated method stub + return false; + } - public List supportedHypervisors() { - // TODO Auto-generated method stub - return null; - } + public List supportedHypervisors() { + // TODO Auto-generated method stub + return null; + } - public String getProviderName() { - // TODO Auto-generated method stub - return null; - } + public String getProviderName() { + // TODO Auto-generated method stub + return null; + } - public List supportedStoreTypes() { - // TODO Auto-generated method stub - return null; - } + public List supportedStoreTypes() { + // TODO Auto-generated method stub + return null; + } - public void configure(Map storeProviderInfo) { - // TODO Auto-generated method stub + public void configure(Map storeProviderInfo) { + // TODO Auto-generated method stub - } + } - public DataStore addDataStore(StoragePool sp, String uri, Map params) { - // TODO Auto-generated method stub - return null; - } + public DataStore addDataStore(StoragePool sp, String uri, Map params) { + // TODO Auto-generated method stub + return null; + } - public DataStore getDataStore(StoragePool pool) { - // TODO Auto-generated method stub - return null; - } + public DataStore getDataStore(StoragePool pool) { + // TODO Auto-generated method stub + return null; + } - public Map> getDataStoreConfigs() { - // TODO Auto-generated method stub - return null; - } + public Map> getDataStoreConfigs() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/provider/SwiftSecondaryStorageProvider.java b/engine/storage/src/org/apache/cloudstack/storage/provider/SwiftSecondaryStorageProvider.java index cfe0e48aa3f..c62b8b1d050 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/provider/SwiftSecondaryStorageProvider.java +++ b/engine/storage/src/org/apache/cloudstack/storage/provider/SwiftSecondaryStorageProvider.java @@ -33,59 +33,59 @@ import com.cloud.storage.StoragePool; public class SwiftSecondaryStorageProvider implements StorageProvider { - public boolean configure(String name, Map params) throws ConfigurationException { - // TODO Auto-generated method stub - return false; - } + public boolean configure(String name, Map params) throws ConfigurationException { + // TODO Auto-generated method stub + return false; + } - public String getName() { - // TODO Auto-generated method stub - return null; - } + public String getName() { + // TODO Auto-generated method stub + return null; + } - public boolean start() { - // TODO Auto-generated method stub - return false; - } + public boolean start() { + // TODO Auto-generated method stub + return false; + } - public boolean stop() { - // TODO Auto-generated method stub - return false; - } + public boolean stop() { + // TODO Auto-generated method stub + return false; + } - public List supportedHypervisors() { - // TODO Auto-generated method stub - return null; - } + public List supportedHypervisors() { + // TODO Auto-generated method stub + return null; + } - public String getProviderName() { - // TODO Auto-generated method stub - return null; - } + public String getProviderName() { + // TODO Auto-generated method stub + return null; + } - public List supportedStoreTypes() { - // TODO Auto-generated method stub - return null; - } + public List supportedStoreTypes() { + // TODO Auto-generated method stub + return null; + } - public void configure(Map storeProviderInfo) { - // TODO Auto-generated method stub + public void configure(Map storeProviderInfo) { + // TODO Auto-generated method stub - } + } - public DataStore addDataStore(StoragePool sp, String uri, Map params) { - // TODO Auto-generated method stub - return null; - } + public DataStore addDataStore(StoragePool sp, String uri, Map params) { + // TODO Auto-generated method stub + return null; + } - public DataStore getDataStore(StoragePool pool) { - // TODO Auto-generated method stub - return null; - } + public DataStore getDataStore(StoragePool pool) { + // TODO Auto-generated method stub + return null; + } - public Map> getDataStoreConfigs() { - // TODO Auto-generated method stub - return null; - } + public Map> getDataStoreConfigs() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotService.java b/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotService.java index 6adab006a6e..d13582ce045 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/snapshot/SnapshotService.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.storage.snapshot; public interface SnapshotService { - long takeSnapshot(long volumeId); - boolean deleteSnapshot(long snapshotId); + long takeSnapshot(long volumeId); + + boolean deleteSnapshot(long snapshotId); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultTemplateStratey.java b/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultTemplateStratey.java index 17ef4b95894..8c2339f36fc 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultTemplateStratey.java +++ b/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultTemplateStratey.java @@ -47,11 +47,11 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; public class DefaultTemplateStratey implements TemplateStrategy { - private static final Logger s_logger = Logger.getLogger(DefaultTemplateStratey.class); - protected DataStore _ds; - protected DataStoreDriver _driver; - protected int _primaryStorageDownloadWait; - protected int _installTries = 3; + private static final Logger s_logger = Logger.getLogger(DefaultTemplateStratey.class); + protected DataStore _ds; + protected DataStoreDriver _driver; + protected int _primaryStorageDownloadWait; + protected int _installTries = 3; protected int _storagePoolMaxWaitSeconds = 3600; @Inject VMTemplatePoolDao _templatePoolDao; @@ -59,133 +59,133 @@ public class DefaultTemplateStratey implements TemplateStrategy { VMTemplateHostDao _templateImageStoreDao; @Inject ImageManager _templateMgr; - + public DefaultTemplateStratey(DataStore ds) { - _ds = ds; + _ds = ds; } - + public TemplateProfile get(long templateId) { - return _templateMgr.getProfile(templateId); + return _templateMgr.getProfile(templateId); } - - public TemplateProfile install(TemplateProfile tp) { - DataStoreEndPointSelector dseps = _ds.getEndPointSelector(); - List eps = dseps.getEndPoints(StorageEvent.DownloadTemplateToPrimary); - int tries = Math.min(eps.size(), _installTries); - VMTemplateStoragePoolVO templateStoragePoolRef = _templatePoolDao.acquireInLockTable(tp.getTemplatePoolRefId(), _storagePoolMaxWaitSeconds); - if (templateStoragePoolRef == null) { - throw new CloudRuntimeException("Unable to acquire lock on VMTemplateStoragePool: " + tp.getTemplatePoolRefId()); - } + public TemplateProfile install(TemplateProfile tp) { + DataStoreEndPointSelector dseps = _ds.getEndPointSelector(); + List eps = dseps.getEndPoints(StorageEvent.DownloadTemplateToPrimary); + int tries = Math.min(eps.size(), _installTries); - try { - for (int retry = 0; retry < tries; retry++) { - Collections.shuffle(eps); - DataStoreEndPoint ep = eps.get(0); - try { - tp = _driver.install(tp, ep); - templateStoragePoolRef.setDownloadPercent(100); - templateStoragePoolRef.setDownloadState(Status.DOWNLOADED); - templateStoragePoolRef.setLocalDownloadPath(tp.getLocalPath()); - templateStoragePoolRef.setInstallPath(tp.getLocalPath()); - templateStoragePoolRef.setTemplateSize(tp.getSize()); - _templatePoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Template " + tp.getTemplateId() + " is installed via " + ep.getHostId()); - } - return get(tp.getTemplateId()); - } catch (CloudRuntimeException e) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Template " + tp.getTemplateId() + " download to pool " + _ds.getId() + " failed due to " + e.toString()); - } - } - } - } finally { - _templatePoolDao.releaseFromLockTable(tp.getTemplatePoolRefId()); - } + VMTemplateStoragePoolVO templateStoragePoolRef = _templatePoolDao.acquireInLockTable(tp.getTemplatePoolRefId(), _storagePoolMaxWaitSeconds); + if (templateStoragePoolRef == null) { + throw new CloudRuntimeException("Unable to acquire lock on VMTemplateStoragePool: " + tp.getTemplatePoolRefId()); + } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Template " + tp.getTemplateId() + " is not found on and can not be downloaded to pool " + _ds.getId()); - } - return null; - } + try { + for (int retry = 0; retry < tries; retry++) { + Collections.shuffle(eps); + DataStoreEndPoint ep = eps.get(0); + try { + tp = _driver.install(tp, ep); + templateStoragePoolRef.setDownloadPercent(100); + templateStoragePoolRef.setDownloadState(Status.DOWNLOADED); + templateStoragePoolRef.setLocalDownloadPath(tp.getLocalPath()); + templateStoragePoolRef.setInstallPath(tp.getLocalPath()); + templateStoragePoolRef.setTemplateSize(tp.getSize()); + _templatePoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Template " + tp.getTemplateId() + " is installed via " + ep.getHostId()); + } + return get(tp.getTemplateId()); + } catch (CloudRuntimeException e) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Template " + tp.getTemplateId() + " download to pool " + _ds.getId() + " failed due to " + e.toString()); + } + } + } + } finally { + _templatePoolDao.releaseFromLockTable(tp.getTemplatePoolRefId()); + } - public TemplateProfile register(TemplateProfile tp) { - - VMTemplateHostVO vmTemplateHost = _templateImageStoreDao.findByHostTemplate(_ds.getId(), tp.getTemplateId()); - if (vmTemplateHost == null) { - vmTemplateHost = new VMTemplateHostVO(_ds.getId(), tp.getTemplateId(), new Date(), 0, VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, "jobid0000", null, tp.getUrl()); - _templateImageStoreDao.persist(vmTemplateHost); - } - - DataStoreEndPointSelector dseps = _ds.getEndPointSelector(); - List eps = dseps.getEndPoints(StorageEvent.RegisterTemplate); - - Collections.shuffle(eps); - DataStoreEndPoint ep = eps.get(0); - _driver.register(tp, ep); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Template " + tp.getTemplateId() + " is not found on and can not be downloaded to pool " + _ds.getId()); + } + return null; + } - return null; - } - - protected boolean checkHypervisor(HypervisorType hypervisor) { - StorageProvider sp = _ds.getProvider(); - List spHys = sp.supportedHypervisors(); - boolean checkHypervisor = false; - for (HypervisorType hy : spHys) { - if (hy == hypervisor) { - checkHypervisor = true; - } - } - return checkHypervisor; - } - - protected boolean checkFormat(String url, String format) { - if ((!url.toLowerCase().endsWith("vhd")) && (!url.toLowerCase().endsWith("vhd.zip")) && (!url.toLowerCase().endsWith("vhd.bz2")) && (!url.toLowerCase().endsWith("vhd.gz")) - && (!url.toLowerCase().endsWith("qcow2")) && (!url.toLowerCase().endsWith("qcow2.zip")) && (!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) - && (!url.toLowerCase().endsWith("ova")) && (!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) - && (!url.toLowerCase().endsWith("img")) && (!url.toLowerCase().endsWith("raw"))) { - throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase()); - } + public TemplateProfile register(TemplateProfile tp) { - if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith("vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith( - "vhd.gz"))) - || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith("qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url - .toLowerCase().endsWith("qcow2.gz"))) - || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith("ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase() - .endsWith("ova.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith("img") && !url.toLowerCase().endsWith("raw")))) { - throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase()); - } - return true; - } + VMTemplateHostVO vmTemplateHost = _templateImageStoreDao.findByHostTemplate(_ds.getId(), tp.getTemplateId()); + if (vmTemplateHost == null) { + vmTemplateHost = new VMTemplateHostVO(_ds.getId(), tp.getTemplateId(), new Date(), 0, VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, "jobid0000", null, tp.getUrl()); + _templateImageStoreDao.persist(vmTemplateHost); + } - public boolean canRegister(long templateId) { - TemplateProfile tp = get(templateId); - - if (!checkHypervisor(tp.getHypervisorType())) { - return false; - } - - if (!checkFormat(tp.getUrl(), tp.getFormat().toString())) { - return false; - } - - return true; - } + DataStoreEndPointSelector dseps = _ds.getEndPointSelector(); + List eps = dseps.getEndPoints(StorageEvent.RegisterTemplate); - public int getDownloadWait() { - // TODO Auto-generated method stub - return 0; - } + Collections.shuffle(eps); + DataStoreEndPoint ep = eps.get(0); + _driver.register(tp, ep); - public long getMaxTemplateSizeInBytes() { - // TODO Auto-generated method stub - return 0; - } + return null; + } - public Proxy getHttpProxy() { - // TODO Auto-generated method stub - return null; - } + protected boolean checkHypervisor(HypervisorType hypervisor) { + StorageProvider sp = _ds.getProvider(); + List spHys = sp.supportedHypervisors(); + boolean checkHypervisor = false; + for (HypervisorType hy : spHys) { + if (hy == hypervisor) { + checkHypervisor = true; + } + } + return checkHypervisor; + } + + protected boolean checkFormat(String url, String format) { + if ((!url.toLowerCase().endsWith("vhd")) && (!url.toLowerCase().endsWith("vhd.zip")) && (!url.toLowerCase().endsWith("vhd.bz2")) && (!url.toLowerCase().endsWith("vhd.gz")) + && (!url.toLowerCase().endsWith("qcow2")) && (!url.toLowerCase().endsWith("qcow2.zip")) && (!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) + && (!url.toLowerCase().endsWith("ova")) && (!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) + && (!url.toLowerCase().endsWith("img")) && (!url.toLowerCase().endsWith("raw"))) { + throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase()); + } + + if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith("vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith( + "vhd.gz"))) + || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith("qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url + .toLowerCase().endsWith("qcow2.gz"))) + || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith("ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase() + .endsWith("ova.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith("img") && !url.toLowerCase().endsWith("raw")))) { + throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase()); + } + return true; + } + + public boolean canRegister(long templateId) { + TemplateProfile tp = get(templateId); + + if (!checkHypervisor(tp.getHypervisorType())) { + return false; + } + + if (!checkFormat(tp.getUrl(), tp.getFormat().toString())) { + return false; + } + + return true; + } + + public int getDownloadWait() { + // TODO Auto-generated method stub + return 0; + } + + public long getMaxTemplateSizeInBytes() { + // TODO Auto-generated method stub + return 0; + } + + public Proxy getHttpProxy() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultVolumeStrategy.java b/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultVolumeStrategy.java index d926d9a216b..8d1ab797130 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultVolumeStrategy.java +++ b/engine/storage/src/org/apache/cloudstack/storage/strategy/DefaultVolumeStrategy.java @@ -16,75 +16,77 @@ import org.apache.cloudstack.storage.volume.VolumeManager; import org.apache.log4j.Logger; - import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; import com.cloud.utils.component.Inject; - public class DefaultVolumeStrategy implements VolumeStrategy { - private static final Logger s_logger = Logger.getLogger(DefaultVolumeStrategy.class); - protected DataStore _ds; - protected DataStoreDriver _driver; - @Inject - VolumeManager _volumeMgr; - - public VolumeProfile get(long volumeId) { - return _volumeMgr.getProfile(volumeId); - } + private static final Logger s_logger = Logger.getLogger(DefaultVolumeStrategy.class); + protected DataStore _ds; + protected DataStoreDriver _driver; + @Inject + VolumeManager _volumeMgr; - public DefaultVolumeStrategy(DataStore ds) { - _ds = ds; - } - public Volume createVolume(Volume vol) { - // TODO Auto-generated method stub - return null; - } - public Volume createDataVolume(Volume vol) { - // TODO Auto-generated method stub - return null; - } - public Volume copyVolumeFromBackup(VolumeProfile srcVol, Volume destVol) { - // TODO Auto-generated method stub - return null; - } - public Volume createVolumeFromSnapshot(SnapshotProfile snapshot, Volume vol) { - // TODO Auto-generated method stub - return null; - } - public Volume createVolumeFromTemplate(TemplateProfile template, Volume vol) { - // TODO Auto-generated method stub - return null; - } - public Volume migrateVolume(Volume srcVol, Volume destVol, DataStore destStore) { - // TODO Auto-generated method stub - return null; - } - - public Volume createVolumeFromBaseTemplate(Volume volume, TemplateProfile tp) { - DataStoreEndPointSelector dsep = _ds.getEndPointSelector(); - List dseps = dsep.getEndPoints(StorageEvent.CreateVolumeFromTemplate); - DataStoreEndPoint dp = dseps.get(0); - - VolumeProfile vp = _driver.createVolumeFromTemplate(get(volume.getId()), tp, dp); - - VolumeVO vlvo = _volumeMgr.getVolume(volume.getId()); - - vlvo.setFolder(_ds.getPath()); - vlvo.setPath(vp.getPath()); - vlvo.setSize(vp.getSize()); - vlvo.setPoolType(_ds.getPoolType()); - vlvo.setPoolId(_ds.getId()); - vlvo.setPodId(_ds.getPodId()); - - return _volumeMgr.updateVolume(vlvo); - } - public boolean deleteVolume(Volume vol) { - // TODO Auto-generated method stub - return false; - } - - + public VolumeProfile get(long volumeId) { + return _volumeMgr.getProfile(volumeId); + } + public DefaultVolumeStrategy(DataStore ds) { + _ds = ds; + } + + public Volume createVolume(Volume vol) { + // TODO Auto-generated method stub + return null; + } + + public Volume createDataVolume(Volume vol) { + // TODO Auto-generated method stub + return null; + } + + public Volume copyVolumeFromBackup(VolumeProfile srcVol, Volume destVol) { + // TODO Auto-generated method stub + return null; + } + + public Volume createVolumeFromSnapshot(SnapshotProfile snapshot, Volume vol) { + // TODO Auto-generated method stub + return null; + } + + public Volume createVolumeFromTemplate(TemplateProfile template, Volume vol) { + // TODO Auto-generated method stub + return null; + } + + public Volume migrateVolume(Volume srcVol, Volume destVol, DataStore destStore) { + // TODO Auto-generated method stub + return null; + } + + public Volume createVolumeFromBaseTemplate(Volume volume, TemplateProfile tp) { + DataStoreEndPointSelector dsep = _ds.getEndPointSelector(); + List dseps = dsep.getEndPoints(StorageEvent.CreateVolumeFromTemplate); + DataStoreEndPoint dp = dseps.get(0); + + VolumeProfile vp = _driver.createVolumeFromTemplate(get(volume.getId()), tp, dp); + + VolumeVO vlvo = _volumeMgr.getVolume(volume.getId()); + + vlvo.setFolder(_ds.getPath()); + vlvo.setPath(vp.getPath()); + vlvo.setSize(vp.getSize()); + vlvo.setPoolType(_ds.getPoolType()); + vlvo.setPoolId(_ds.getId()); + vlvo.setPodId(_ds.getPodId()); + + return _volumeMgr.updateVolume(vlvo); + } + + public boolean deleteVolume(Volume vol) { + // TODO Auto-generated method stub + return false; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/strategy/XenBackupStrategy.java b/engine/storage/src/org/apache/cloudstack/storage/strategy/XenBackupStrategy.java index 09abc9fbe9a..86953f476f6 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/strategy/XenBackupStrategy.java +++ b/engine/storage/src/org/apache/cloudstack/storage/strategy/XenBackupStrategy.java @@ -4,8 +4,9 @@ import org.apache.cloudstack.engine.subsystem.api.storage.BackupStrategy; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; public class XenBackupStrategy implements BackupStrategy { - protected DataStore _ds; - public XenBackupStrategy(DataStore ds) { - _ds = ds; - } + protected DataStore _ds; + + public XenBackupStrategy(DataStore ds) { + _ds = ds; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/strategy/XenSnapshotStrategy.java b/engine/storage/src/org/apache/cloudstack/storage/strategy/XenSnapshotStrategy.java index 70b3b6837b4..32581dde721 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/strategy/XenSnapshotStrategy.java +++ b/engine/storage/src/org/apache/cloudstack/storage/strategy/XenSnapshotStrategy.java @@ -4,8 +4,9 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy; public class XenSnapshotStrategy implements SnapshotStrategy { - protected DataStore _ds; - public XenSnapshotStrategy(DataStore ds) { - _ds = ds; - } + protected DataStore _ds; + + public XenSnapshotStrategy(DataStore ds) { + _ds = ds; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/to/ImageDataStoreTO.java b/engine/storage/src/org/apache/cloudstack/storage/to/ImageDataStoreTO.java index 1b4c083f802..ca1e9b7426c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/to/ImageDataStoreTO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/to/ImageDataStoreTO.java @@ -3,7 +3,7 @@ package org.apache.cloudstack.storage.to; import org.apache.cloudstack.storage.image.store.ImageDataStoreInfo; public class ImageDataStoreTO { - public ImageDataStoreTO(ImageDataStoreInfo dataStore) { - - } + public ImageDataStoreTO(ImageDataStoreInfo dataStore) { + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/to/ImageOnPrimayDataStoreTO.java b/engine/storage/src/org/apache/cloudstack/storage/to/ImageOnPrimayDataStoreTO.java index 203ab057e7d..cc31bc7dcf5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/to/ImageOnPrimayDataStoreTO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/to/ImageOnPrimayDataStoreTO.java @@ -21,7 +21,7 @@ package org.apache.cloudstack.storage.to; import org.apache.cloudstack.storage.volume.TemplateOnPrimaryDataStoreInfo; public class ImageOnPrimayDataStoreTO { - public ImageOnPrimayDataStoreTO(TemplateOnPrimaryDataStoreInfo template) { - - } + public ImageOnPrimayDataStoreTO(TemplateOnPrimaryDataStoreInfo template) { + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java b/engine/storage/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java index bb264df5b2d..bd97dda9651 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java @@ -3,7 +3,7 @@ package org.apache.cloudstack.storage.to; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; public class PrimaryDataStoreTO { - public PrimaryDataStoreTO(PrimaryDataStoreInfo dataStore) { - - } + public PrimaryDataStoreTO(PrimaryDataStoreInfo dataStore) { + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/to/TemplateTO.java b/engine/storage/src/org/apache/cloudstack/storage/to/TemplateTO.java index 0c9d53f6203..d5f9d09c9f3 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/to/TemplateTO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/to/TemplateTO.java @@ -3,7 +3,7 @@ package org.apache.cloudstack.storage.to; import org.apache.cloudstack.storage.image.TemplateInfo; public class TemplateTO { - public TemplateTO(TemplateInfo template) { - - } + public TemplateTO(TemplateInfo template) { + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/to/VolumeTO.java b/engine/storage/src/org/apache/cloudstack/storage/to/VolumeTO.java index 28150f143c2..eff22f0191a 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/to/VolumeTO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/to/VolumeTO.java @@ -3,7 +3,7 @@ package org.apache.cloudstack.storage.to; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; public class VolumeTO { - public VolumeTO(VolumeInfo volume) { - - } + public VolumeTO(VolumeInfo volume) { + + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java index 33a350e39b1..b1bf403c4e3 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreInfo.java @@ -22,8 +22,11 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.storage.image.TemplateInfo; public interface TemplateOnPrimaryDataStoreInfo { - public String getPath(); - public void setPath(String path); - public PrimaryDataStoreInfo getPrimaryDataStore(); - public TemplateInfo getTemplate(); + public String getPath(); + + public void setPath(String path); + + public PrimaryDataStoreInfo getPrimaryDataStore(); + + public TemplateInfo getTemplate(); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreObject.java b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreObject.java index d68b497d10d..25ae38d2cb0 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreObject.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplateOnPrimaryDataStoreObject.java @@ -28,41 +28,41 @@ import org.apache.cloudstack.storage.volume.db.TemplatePrimaryDataStoreVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; public class TemplateOnPrimaryDataStoreObject implements TemplateOnPrimaryDataStoreInfo { - protected PrimaryDataStoreInfo dataStore; - protected TemplateInfo template; - protected TemplatePrimaryDataStoreVO vo; - @Inject - TemplatePrimaryDataStoreDao templateStoreDao; - - public TemplateOnPrimaryDataStoreObject(PrimaryDataStoreInfo primaryDataStore, TemplateInfo template, TemplatePrimaryDataStoreVO vo) { - this.dataStore = primaryDataStore; - this.template = template; - this.vo = vo; - } - - @Override - public String getPath() { - return vo.getInstallPath(); - } + protected PrimaryDataStoreInfo dataStore; + protected TemplateInfo template; + protected TemplatePrimaryDataStoreVO vo; + @Inject + TemplatePrimaryDataStoreDao templateStoreDao; - @Override - public void setPath(String path) { - this.vo.setInstallPath(path); - } + public TemplateOnPrimaryDataStoreObject(PrimaryDataStoreInfo primaryDataStore, TemplateInfo template, TemplatePrimaryDataStoreVO vo) { + this.dataStore = primaryDataStore; + this.template = template; + this.vo = vo; + } - @Override - public PrimaryDataStoreInfo getPrimaryDataStore() { - return this.dataStore; - } + @Override + public String getPath() { + return vo.getInstallPath(); + } - @Override - public TemplateInfo getTemplate() { - return this.template; - } - - public void updateStatus(Status status) { - vo.setDownloadState(status); - templateStoreDao.update(vo.getId(), vo); - } + @Override + public void setPath(String path) { + this.vo.setInstallPath(path); + } + + @Override + public PrimaryDataStoreInfo getPrimaryDataStore() { + return this.dataStore; + } + + @Override + public TemplateInfo getTemplate() { + return this.template; + } + + public void updateStatus(Status status) { + vo.setDownloadState(status); + templateStoreDao.update(vo.getId(), vo); + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManager.java b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManager.java index 2038edfb07a..eb0b6706fbf 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManager.java @@ -22,6 +22,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.storage.image.TemplateInfo; public interface TemplatePrimaryDataStoreManager { - public TemplateOnPrimaryDataStoreInfo createTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore); - public TemplateOnPrimaryDataStoreInfo findTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore); + public TemplateOnPrimaryDataStoreInfo createTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore); + + public TemplateOnPrimaryDataStoreInfo findTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManagerImpl.java index aec3c4d04ed..95ea49ffaf5 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/TemplatePrimaryDataStoreManagerImpl.java @@ -24,31 +24,35 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.storage.image.TemplateInfo; import org.apache.cloudstack.storage.volume.db.TemplatePrimaryDataStoreDao; import org.apache.cloudstack.storage.volume.db.TemplatePrimaryDataStoreVO; +import org.springframework.stereotype.Component; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteriaService; import com.cloud.utils.db.SearchCriteria.Op; +@Component public class TemplatePrimaryDataStoreManagerImpl implements TemplatePrimaryDataStoreManager { - @Inject - TemplatePrimaryDataStoreDao templateStoreDao; - @Override - public TemplateOnPrimaryDataStoreObject createTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore) { - - TemplatePrimaryDataStoreVO templateStoreVO = new TemplatePrimaryDataStoreVO(dataStore.getId(), template.getId()); - templateStoreVO = templateStoreDao.persist(templateStoreVO); - TemplateOnPrimaryDataStoreObject templateStoreObject = new TemplateOnPrimaryDataStoreObject(dataStore, template, templateStoreVO); - return templateStoreObject; - } - @Override - public TemplateOnPrimaryDataStoreObject findTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore) { - SearchCriteriaService sc = SearchCriteria2.create(TemplatePrimaryDataStoreVO.class); - sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, template.getId()); - sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, dataStore.getId()); - sc.addAnd(sc.getEntity().getDownloadState(), Op.EQ, VMTemplateStorageResourceAssoc.Status.DOWNLOADED); - TemplatePrimaryDataStoreVO templateStoreVO = sc.find(); - TemplateOnPrimaryDataStoreObject templateStoreObject = new TemplateOnPrimaryDataStoreObject(dataStore, template, templateStoreVO); - return templateStoreObject; - } + @Inject + TemplatePrimaryDataStoreDao templateStoreDao; + + @Override + public TemplateOnPrimaryDataStoreObject createTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore) { + + TemplatePrimaryDataStoreVO templateStoreVO = new TemplatePrimaryDataStoreVO(dataStore.getId(), template.getId()); + templateStoreVO = templateStoreDao.persist(templateStoreVO); + TemplateOnPrimaryDataStoreObject templateStoreObject = new TemplateOnPrimaryDataStoreObject(dataStore, template, templateStoreVO); + return templateStoreObject; + } + + @Override + public TemplateOnPrimaryDataStoreObject findTemplateOnPrimaryDataStore(TemplateInfo template, PrimaryDataStoreInfo dataStore) { + SearchCriteriaService sc = SearchCriteria2.create(TemplatePrimaryDataStoreVO.class); + sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, template.getId()); + sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, dataStore.getId()); + sc.addAnd(sc.getEntity().getDownloadState(), Op.EQ, VMTemplateStorageResourceAssoc.Status.DOWNLOADED); + TemplatePrimaryDataStoreVO templateStoreVO = sc.find(); + TemplateOnPrimaryDataStoreObject templateStoreObject = new TemplateOnPrimaryDataStoreObject(dataStore, template, templateStoreVO); + return templateStoreObject; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java index 424c7f720d8..cc48f10ada6 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEntityImpl.java @@ -55,6 +55,12 @@ public class VolumeEntityImpl implements VolumeEntity { return volumeInfo.getId(); } + @Override + public String getExternalId() { + // TODO Auto-generated method stub + return null; + } + @Override public String getCurrentState() { return volumeInfo.getCurrentState().toString(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEvent.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEvent.java index 33d1261ead9..663584b9dba 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEvent.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeEvent.java @@ -19,16 +19,5 @@ package org.apache.cloudstack.storage.volume; public enum VolumeEvent { - CreateRequested, - CopyRequested, - CopySucceeded, - CopyFailed, - OperationFailed, - OperationSucceeded, - OperationRetry, - UploadRequested, - MigrationRequested, - SnapshotRequested, - DestroyRequested, - ExpungingRequested; + CreateRequested, CopyRequested, CopySucceeded, CopyFailed, OperationFailed, OperationSucceeded, OperationRetry, UploadRequested, MigrationRequested, SnapshotRequested, DestroyRequested, ExpungingRequested; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManager.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManager.java index daaadc19047..22e9bafa5d0 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManager.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManager.java @@ -25,9 +25,13 @@ import com.cloud.storage.VolumeVO; import com.cloud.utils.fsm.NoTransitionException; public interface VolumeManager { - VolumeVO allocateDuplicateVolume(VolumeVO oldVol); - VolumeVO processEvent(Volume vol, Volume.Event event) throws NoTransitionException; - VolumeProfile getProfile(long volumeId); - VolumeVO getVolume(long volumeId); - VolumeVO updateVolume(VolumeVO volume); + VolumeVO allocateDuplicateVolume(VolumeVO oldVol); + + VolumeVO processEvent(Volume vol, Volume.Event event) throws NoTransitionException; + + VolumeProfile getProfile(long volumeId); + + VolumeVO getVolume(long volumeId); + + VolumeVO updateVolume(VolumeVO volume); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManagerImpl.java index 2a5ac867e55..241bc3b8f29 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeManagerImpl.java @@ -28,43 +28,38 @@ import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; public class VolumeManagerImpl implements VolumeManager { - private StateMachine2 _volStateMachine; - @Inject - protected VolumeDao _volumeDao; - + private StateMachine2 _volStateMachine; + @Inject + protected VolumeDao _volumeDao; - public VolumeVO allocateDuplicateVolume(VolumeVO oldVol) { - VolumeVO newVol = new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), oldVol.getSize()); - newVol.setTemplateId(oldVol.getTemplateId()); - newVol.setDeviceId(oldVol.getDeviceId()); - newVol.setInstanceId(oldVol.getInstanceId()); - newVol.setRecreatable(oldVol.isRecreatable()); - newVol.setReservationId(oldVol.getReservationId()); - return null; - //return _volumeDao.persist(newVol); - } - + public VolumeVO allocateDuplicateVolume(VolumeVO oldVol) { + VolumeVO newVol = new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), oldVol.getSize()); + newVol.setTemplateId(oldVol.getTemplateId()); + newVol.setDeviceId(oldVol.getDeviceId()); + newVol.setInstanceId(oldVol.getInstanceId()); + newVol.setRecreatable(oldVol.isRecreatable()); + newVol.setReservationId(oldVol.getReservationId()); + return null; + // return _volumeDao.persist(newVol); + } - public VolumeVO processEvent(Volume vol, Volume.Event event) throws NoTransitionException { - //_volStateMachine.transitTo(vol, event, null, _volumeDao); - return _volumeDao.findById(vol.getId()); - } + public VolumeVO processEvent(Volume vol, Volume.Event event) throws NoTransitionException { + // _volStateMachine.transitTo(vol, event, null, _volumeDao); + return _volumeDao.findById(vol.getId()); + } + public VolumeProfile getProfile(long volumeId) { + // TODO Auto-generated method stub + return null; + } - public VolumeProfile getProfile(long volumeId) { - // TODO Auto-generated method stub - return null; - } + public VolumeVO getVolume(long volumeId) { + // TODO Auto-generated method stub + return null; + } - - public VolumeVO getVolume(long volumeId) { - // TODO Auto-generated method stub - return null; - } - - - public VolumeVO updateVolume(VolumeVO volume) { - // TODO Auto-generated method stub - return null; - } + public VolumeVO updateVolume(VolumeVO volume) { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java index 9814ecb86ed..9349e6b11cc 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeMotionService.java @@ -19,5 +19,5 @@ package org.apache.cloudstack.storage.volume; public interface VolumeMotionService { - boolean copyVolume(String volumeUri, String destVolumeUri); + boolean copyVolume(String volumeUri, String destVolumeUri); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeObject.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeObject.java index d495c3518aa..f57fb758387 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeObject.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeObject.java @@ -1,6 +1,5 @@ package org.apache.cloudstack.storage.volume; - import java.util.Date; import javax.inject.Inject; @@ -24,112 +23,112 @@ import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; public class VolumeObject implements VolumeInfo { - private static final Logger s_logger = Logger.getLogger(VolumeObject.class); - protected VolumeVO volumeVO; - private StateMachine2 _volStateMachine; - protected PrimaryDataStore dataStore; - @Inject - VolumeDiskTypeHelper diskTypeHelper; - @Inject - VolumeTypeHelper volumeTypeHelper; - @Inject - VolumeDao volumeDao; - - public VolumeObject(PrimaryDataStore dataStore, VolumeVO volumeVO) { - this.volumeVO = volumeVO; - this.dataStore = dataStore; - } - - public String getUuid() { - return volumeVO.getUuid(); - } - - public void setPath(String uuid) { - volumeVO.setUuid(uuid); - } - - public String getPath() { - return volumeVO.getPath(); - } - - public String getTemplateUuid() { - return null; - } - - public String getTemplatePath() { - return null; - } - - public PrimaryDataStoreInfo getDataStoreInfo() { - return dataStore.getDataStoreInfo(); - } - - public Volume.State getState() { - return volumeVO.getState(); - } + private static final Logger s_logger = Logger.getLogger(VolumeObject.class); + protected VolumeVO volumeVO; + private StateMachine2 _volStateMachine; + protected PrimaryDataStore dataStore; + @Inject + VolumeDiskTypeHelper diskTypeHelper; + @Inject + VolumeTypeHelper volumeTypeHelper; + @Inject + VolumeDao volumeDao; - public PrimaryDataStore getDataStore() { - return dataStore; - } - - public long getSize() { - return volumeVO.getSize(); - } - - public VolumeDiskType getDiskType() { - return diskTypeHelper.getDiskType(volumeVO.getDiskType()); - } - - public VolumeType getType() { - return volumeTypeHelper.getType(volumeVO.getVolumeType()); - } - - public long getVolumeId() { - return volumeVO.getId(); - } - - public void setVolumeDiskType(VolumeDiskType type) { - volumeVO.setDiskType(type.toString()); - } - - public boolean stateTransit(VolumeEvent event) { - boolean result = false; - try { - result = _volStateMachine.transitTo(volumeVO, event, null, volumeDao); - } catch (NoTransitionException e) { - String errorMessage = "Failed to transit volume: " + this.getVolumeId() + ", due to: " + e.toString(); - s_logger.debug(errorMessage); - throw new CloudRuntimeException(errorMessage); - } - return result; - } - - public void update() { - volumeDao.update(volumeVO.getId(), volumeVO); - volumeVO = volumeDao.findById(volumeVO.getId()); - } + public VolumeObject(PrimaryDataStore dataStore, VolumeVO volumeVO) { + this.volumeVO = volumeVO; + this.dataStore = dataStore; + } - @Override - public long getId() { - // TODO Auto-generated method stub - return 0; - } + public String getUuid() { + return volumeVO.getUuid(); + } - @Override - public State getCurrentState() { - // TODO Auto-generated method stub - return null; - } + public void setPath(String uuid) { + volumeVO.setUuid(uuid); + } - @Override - public State getDesiredState() { - // TODO Auto-generated method stub - return null; - } + public String getPath() { + return volumeVO.getPath(); + } - @Override - public Date getCreatedData() { - // TODO Auto-generated method stub - return null; - } + public String getTemplateUuid() { + return null; + } + + public String getTemplatePath() { + return null; + } + + public PrimaryDataStoreInfo getDataStoreInfo() { + return dataStore.getDataStoreInfo(); + } + + public Volume.State getState() { + return volumeVO.getState(); + } + + public PrimaryDataStore getDataStore() { + return dataStore; + } + + public long getSize() { + return volumeVO.getSize(); + } + + public VolumeDiskType getDiskType() { + return diskTypeHelper.getDiskType(volumeVO.getDiskType()); + } + + public VolumeType getType() { + return volumeTypeHelper.getType(volumeVO.getVolumeType()); + } + + public long getVolumeId() { + return volumeVO.getId(); + } + + public void setVolumeDiskType(VolumeDiskType type) { + volumeVO.setDiskType(type.toString()); + } + + public boolean stateTransit(VolumeEvent event) { + boolean result = false; + try { + result = _volStateMachine.transitTo(volumeVO, event, null, volumeDao); + } catch (NoTransitionException e) { + String errorMessage = "Failed to transit volume: " + this.getVolumeId() + ", due to: " + e.toString(); + s_logger.debug(errorMessage); + throw new CloudRuntimeException(errorMessage); + } + return result; + } + + public void update() { + volumeDao.update(volumeVO.getId(), volumeVO); + volumeVO = volumeDao.findById(volumeVO.getId()); + } + + @Override + public long getId() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public State getCurrentState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public State getDesiredState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getCreatedData() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeService.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeService.java index 773d2f1216d..36a22569592 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeService.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeService.java @@ -26,52 +26,53 @@ import org.apache.cloudstack.engine.subsystem.api.storage.disktype.VolumeDiskTyp import org.apache.cloudstack.engine.subsystem.api.storage.type.VolumeType; import org.apache.cloudstack.storage.image.TemplateInfo; - public interface VolumeService { - /** + /** * */ - VolumeEntity allocateVolumeInDb(long size, VolumeType type,String volName, Long templateId); - + VolumeEntity allocateVolumeInDb(long size, VolumeType type, String volName, Long templateId); + /** * Creates the volume based on the given criteria * * @param cmd - * + * * @return the volume object */ - VolumeInfo createVolume(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType); + VolumeInfo createVolume(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType); /** * Delete volume + * * @param volumeId * @return * @throws ConcurrentOperationException */ boolean deleteVolume(long volumeId); - + /** * */ boolean cloneVolume(long volumeId, long baseVolId); - + /** * */ boolean createVolumeFromSnapshot(long volumeId, long snapshotId); - + /** * */ String grantAccess(VolumeInfo volume, EndPoint endpointId); - + TemplateOnPrimaryDataStoreInfo grantAccess(TemplateOnPrimaryDataStoreInfo template, EndPoint endPoint); - + /** * */ boolean rokeAccess(long volumeId, long endpointId); VolumeEntity getVolumeEntity(long volumeId); + VolumeInfo createVolumeFromTemplate(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType, TemplateInfo template); } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java index 68d01602ae8..f994847f464 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java @@ -47,141 +47,141 @@ import com.cloud.utils.exception.CloudRuntimeException; @Service public class VolumeServiceImpl implements VolumeService { - @Inject - VolumeDao volDao; - @Inject - PrimaryDataStoreManager dataStoreMgr; - @Inject - TemplatePrimaryDataStoreManager templatePrimaryStoreMgr; - @Inject - ImageMotionService imageMotion; - @Override - public VolumeInfo createVolume(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType) { - PrimaryDataStore dataStore = dataStoreMgr.getPrimaryDataStore(dataStoreId); - if (dataStore == null) { - throw new CloudRuntimeException("Can't find dataStoreId: " + dataStoreId); - } - - if (dataStore.exists(volume)) { - return volume; - } - - VolumeObject vo = (VolumeObject)volume; - vo.stateTransit(VolumeEvent.CreateRequested); - - try { - VolumeInfo vi = dataStore.createVolume(vo, diskType); - vo.stateTransit(VolumeEvent.OperationSucceeded); - return vi; - } catch (Exception e) { - vo.stateTransit(VolumeEvent.OperationFailed); - throw new CloudRuntimeException(e.toString()); - } - } + @Inject + VolumeDao volDao; + @Inject + PrimaryDataStoreManager dataStoreMgr; + @Inject + TemplatePrimaryDataStoreManager templatePrimaryStoreMgr; + @Inject + ImageMotionService imageMotion; - @DB - @Override - public boolean deleteVolume(long volumeId) { - return true; - } + @Override + public VolumeInfo createVolume(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType) { + PrimaryDataStore dataStore = dataStoreMgr.getPrimaryDataStore(dataStoreId); + if (dataStore == null) { + throw new CloudRuntimeException("Can't find dataStoreId: " + dataStoreId); + } - @Override - public boolean cloneVolume(long volumeId, long baseVolId) { - // TODO Auto-generated method stub - return false; - } + if (dataStore.exists(volume)) { + return volume; + } - @Override - public boolean createVolumeFromSnapshot(long volumeId, long snapshotId) { - // TODO Auto-generated method stub - return false; - } + VolumeObject vo = (VolumeObject) volume; + vo.stateTransit(VolumeEvent.CreateRequested); - @Override - public boolean rokeAccess(long volumeId, long endpointId) { - // TODO Auto-generated method stub - return false; - } + try { + VolumeInfo vi = dataStore.createVolume(vo, diskType); + vo.stateTransit(VolumeEvent.OperationSucceeded); + return vi; + } catch (Exception e) { + vo.stateTransit(VolumeEvent.OperationFailed); + throw new CloudRuntimeException(e.toString()); + } + } - @Override - public VolumeEntity allocateVolumeInDb(long size, VolumeType type, String volName, Long templateId) { - VolumeVO vo = volDao.allocVolume(size, type, volName, templateId); - return new VolumeEntityImpl(new VolumeObject(null, vo)); - } + @DB + @Override + public boolean deleteVolume(long volumeId) { + return true; + } - @Override - public VolumeEntity getVolumeEntity(long volumeId) { - VolumeVO vo = volDao.findById(volumeId); - if (vo == null) { - return null; - } - - if (vo.getPoolId() == null) { - return new VolumeEntityImpl(new VolumeObject(null, vo)); - } else { - PrimaryDataStore dataStore = dataStoreMgr.getPrimaryDataStore(vo.getPoolId()); - return new VolumeEntityImpl(dataStore.getVolume(volumeId)); - } - } + @Override + public boolean cloneVolume(long volumeId, long baseVolId) { + // TODO Auto-generated method stub + return false; + } + @Override + public boolean createVolumeFromSnapshot(long volumeId, long snapshotId) { + // TODO Auto-generated method stub + return false; + } - @Override - public String grantAccess(VolumeInfo volume, EndPoint endpointId) { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean rokeAccess(long volumeId, long endpointId) { + // TODO Auto-generated method stub + return false; + } - protected TemplateOnPrimaryDataStoreObject createBaseImage(PrimaryDataStore dataStore, TemplateInfo template) { - TemplateOnPrimaryDataStoreObject templateOnPrimaryStoreObj = (TemplateOnPrimaryDataStoreObject)templatePrimaryStoreMgr.createTemplateOnPrimaryDataStore(template, dataStore); - templateOnPrimaryStoreObj.updateStatus(Status.CREATING); - try { - dataStore.installTemplate(templateOnPrimaryStoreObj); - templateOnPrimaryStoreObj.updateStatus(Status.CREATED); - } catch (Exception e) { - templateOnPrimaryStoreObj.updateStatus(Status.ABANDONED); - throw new CloudRuntimeException(e.toString()); - } - - templateOnPrimaryStoreObj.updateStatus(Status.DOWNLOAD_IN_PROGRESS); - try { - imageMotion.copyTemplate(templateOnPrimaryStoreObj); - templateOnPrimaryStoreObj.updateStatus(Status.DOWNLOADED); - } catch (Exception e) { - templateOnPrimaryStoreObj.updateStatus(Status.ABANDONED); - throw new CloudRuntimeException(e.toString()); - } - - return templateOnPrimaryStoreObj; - } - - @Override - public VolumeInfo createVolumeFromTemplate(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType, TemplateInfo template) { - PrimaryDataStore pd = dataStoreMgr.getPrimaryDataStore(dataStoreId); - TemplateOnPrimaryDataStoreInfo templateOnPrimaryStore = pd.getTemplate(template); - if (templateOnPrimaryStore == null) { - templateOnPrimaryStore = createBaseImage(pd, template); - } - - VolumeObject vo = (VolumeObject)volume; - try { - vo.stateTransit(VolumeEvent.CreateRequested); - } catch (Exception e) { - throw new CloudRuntimeException(e.toString()); - } - - try { - volume = pd.createVoluemFromBaseImage(volume, templateOnPrimaryStore); - vo.stateTransit(VolumeEvent.OperationSucceeded); - } catch (Exception e) { - vo.stateTransit(VolumeEvent.OperationFailed); - throw new CloudRuntimeException(e.toString()); - } - return volume; - } + @Override + public VolumeEntity allocateVolumeInDb(long size, VolumeType type, String volName, Long templateId) { + VolumeVO vo = volDao.allocVolume(size, type, volName, templateId); + return new VolumeEntityImpl(new VolumeObject(null, vo)); + } - @Override - public TemplateOnPrimaryDataStoreInfo grantAccess(TemplateOnPrimaryDataStoreInfo template, EndPoint endPoint) { - // TODO Auto-generated method stub - return null; - } + @Override + public VolumeEntity getVolumeEntity(long volumeId) { + VolumeVO vo = volDao.findById(volumeId); + if (vo == null) { + return null; + } + + if (vo.getPoolId() == null) { + return new VolumeEntityImpl(new VolumeObject(null, vo)); + } else { + PrimaryDataStore dataStore = dataStoreMgr.getPrimaryDataStore(vo.getPoolId()); + return new VolumeEntityImpl(dataStore.getVolume(volumeId)); + } + } + + @Override + public String grantAccess(VolumeInfo volume, EndPoint endpointId) { + // TODO Auto-generated method stub + return null; + } + + protected TemplateOnPrimaryDataStoreObject createBaseImage(PrimaryDataStore dataStore, TemplateInfo template) { + TemplateOnPrimaryDataStoreObject templateOnPrimaryStoreObj = (TemplateOnPrimaryDataStoreObject) templatePrimaryStoreMgr.createTemplateOnPrimaryDataStore(template, dataStore); + templateOnPrimaryStoreObj.updateStatus(Status.CREATING); + try { + dataStore.installTemplate(templateOnPrimaryStoreObj); + templateOnPrimaryStoreObj.updateStatus(Status.CREATED); + } catch (Exception e) { + templateOnPrimaryStoreObj.updateStatus(Status.ABANDONED); + throw new CloudRuntimeException(e.toString()); + } + + templateOnPrimaryStoreObj.updateStatus(Status.DOWNLOAD_IN_PROGRESS); + try { + imageMotion.copyTemplate(templateOnPrimaryStoreObj); + templateOnPrimaryStoreObj.updateStatus(Status.DOWNLOADED); + } catch (Exception e) { + templateOnPrimaryStoreObj.updateStatus(Status.ABANDONED); + throw new CloudRuntimeException(e.toString()); + } + + return templateOnPrimaryStoreObj; + } + + @Override + public VolumeInfo createVolumeFromTemplate(VolumeInfo volume, long dataStoreId, VolumeDiskType diskType, TemplateInfo template) { + PrimaryDataStore pd = dataStoreMgr.getPrimaryDataStore(dataStoreId); + TemplateOnPrimaryDataStoreInfo templateOnPrimaryStore = pd.getTemplate(template); + if (templateOnPrimaryStore == null) { + templateOnPrimaryStore = createBaseImage(pd, template); + } + + VolumeObject vo = (VolumeObject) volume; + try { + vo.stateTransit(VolumeEvent.CreateRequested); + } catch (Exception e) { + throw new CloudRuntimeException(e.toString()); + } + + try { + volume = pd.createVoluemFromBaseImage(volume, templateOnPrimaryStore); + vo.stateTransit(VolumeEvent.OperationSucceeded); + } catch (Exception e) { + vo.stateTransit(VolumeEvent.OperationFailed); + throw new CloudRuntimeException(e.toString()); + } + return volume; + } + + @Override + public TemplateOnPrimaryDataStoreInfo grantAccess(TemplateOnPrimaryDataStoreInfo template, EndPoint endPoint) { + // TODO Auto-generated method stub + return null; + } } 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 0abef22ad0f..70e705f1ace 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 @@ -36,183 +36,192 @@ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.utils.db.GenericDaoBase; @Entity -@Table(name="template_spool_ref") +@Table(name = "template_spool_ref") public class TemplatePrimaryDataStoreVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - long id; - - @Column(name="pool_id") - private long poolId; - - @Column(name="template_id") long templateId; - - @Column(name=GenericDaoBase.CREATED_COLUMN) Date created = null; - - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) Date lastUpdated = null; - - @Column (name="download_pct") int downloadPercent; - - @Column (name="download_state") - @Enumerated(EnumType.STRING) Status downloadState; - - @Column (name="local_path") String localDownloadPath; - - @Column (name="error_str") String errorString; - - @Column (name="job_id") String jobId; - - @Column (name="install_path") String installPath; - - @Column (name="template_size") long templateSize; - - @Column (name="marked_for_gc") boolean markedForGC; - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + long id; + + @Column(name = "pool_id") + private long poolId; + + @Column(name = "template_id") + long templateId; + + @Column(name = GenericDaoBase.CREATED_COLUMN) + Date created = null; + + @Column(name = "last_updated") + @Temporal(value = TemporalType.TIMESTAMP) + Date lastUpdated = null; + + @Column(name = "download_pct") + int downloadPercent; + + @Column(name = "download_state") + @Enumerated(EnumType.STRING) + Status downloadState; + + @Column(name = "local_path") + String localDownloadPath; + + @Column(name = "error_str") + String errorString; + + @Column(name = "job_id") + String jobId; + + @Column(name = "install_path") + String installPath; + + @Column(name = "template_size") + long templateSize; + + @Column(name = "marked_for_gc") + boolean markedForGC; + public String getInstallPath() { - return installPath; - } - + return installPath; + } + 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; + } public long getTemplateId() { - return templateId; - } + return templateId; + } public void setTemplateId(long templateId) { - this.templateId = templateId; - } + this.templateId = templateId; + } public int getDownloadPercent() { - return downloadPercent; - } + return downloadPercent; + } public void setDownloadPercent(int downloadPercent) { - this.downloadPercent = downloadPercent; - } + this.downloadPercent = downloadPercent; + } public void setDownloadState(Status downloadState) { - this.downloadState = downloadState; - } + this.downloadState = downloadState; + } public long getId() { - return id; - } + return id; + } public Date getCreated() { - return created; - } + return created; + } public Date getLastUpdated() { - return lastUpdated; - } - + return lastUpdated; + } + public void setLastUpdated(Date date) { - lastUpdated = date; - } - + lastUpdated = date; + } + public void setInstallPath(String installPath) { - this.installPath = installPath; - } + this.installPath = installPath; + } public Status getDownloadState() { - return downloadState; - } + return downloadState; + } - public TemplatePrimaryDataStoreVO(long poolId, long templateId) { - super(); - this.poolId = poolId; - this.templateId = templateId; - this.downloadState = Status.NOT_DOWNLOADED; - this.markedForGC = false; - } + public TemplatePrimaryDataStoreVO(long poolId, long templateId) { + super(); + this.poolId = poolId; + this.templateId = templateId; + this.downloadState = Status.NOT_DOWNLOADED; + this.markedForGC = false; + } - public TemplatePrimaryDataStoreVO(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 TemplatePrimaryDataStoreVO(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 TemplatePrimaryDataStoreVO() { - - } + protected TemplatePrimaryDataStoreVO() { + + } public void setLocalDownloadPath(String localPath) { - this.localDownloadPath = localPath; - } + this.localDownloadPath = localPath; + } public String getLocalDownloadPath() { - return localDownloadPath; - } + return localDownloadPath; + } public void setErrorString(String errorString) { - this.errorString = errorString; - } + this.errorString = errorString; + } public String getErrorString() { - return errorString; - } + return errorString; + } public void setJobId(String jobId) { - this.jobId = jobId; - } + this.jobId = jobId; + } public String getJobId() { - return jobId; - } - - public void setTemplateSize(long templateSize) { - this.templateSize = templateSize; - } - - public boolean getMarkedForGC() { - return markedForGC; - } - - public void setMarkedForGC(boolean markedForGC) { - this.markedForGC = markedForGC; - } + return jobId; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof TemplatePrimaryDataStoreVO) { - TemplatePrimaryDataStoreVO other = (TemplatePrimaryDataStoreVO)obj; - return (this.templateId==other.getTemplateId() && this.poolId==other.getPoolId()); - } - return false; - } + public void setTemplateSize(long templateSize) { + this.templateSize = templateSize; + } - @Override - public int hashCode() { - Long tid = new Long(templateId); - Long hid = new Long(poolId); - return tid.hashCode()+hid.hashCode(); - } - - @Override + public boolean getMarkedForGC() { + return markedForGC; + } + + public void setMarkedForGC(boolean markedForGC) { + this.markedForGC = markedForGC; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof TemplatePrimaryDataStoreVO) { + TemplatePrimaryDataStoreVO other = (TemplatePrimaryDataStoreVO) 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 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(); + } } \ No newline at end of file diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDao.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDao.java index a5cd0e84fb5..85124ec9cad 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDao.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDao.java @@ -21,8 +21,6 @@ import java.util.List; import org.apache.cloudstack.engine.subsystem.api.storage.type.VolumeType; import org.apache.cloudstack.storage.volume.VolumeEvent; - - import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Volume; @@ -31,51 +29,51 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; public interface VolumeDao extends GenericDao, StateDao { - - List findDetachedByAccount(long accountId); - + + List findDetachedByAccount(long accountId); + List findByAccount(long accountId); - + Pair getCountAndTotalByPool(long poolId); - + Pair getNonDestroyedCountAndTotalByPool(long poolId); - + List findByInstance(long id); - + List findByInstanceAndType(long id, VolumeType vType); - + List findByInstanceIdDestroyed(long vmId); - + List findByAccountAndPod(long accountId, long podId); - + List findByTemplateAndZone(long templateId, long zoneId); - + void deleteVolumesByInstance(long instanceId); - + void attachVolume(long volumeId, long vmId, long deviceId); - + void detachVolume(long volumeId); - + boolean isAnyVolumeActivelyUsingTemplateOnPool(long templateId, long poolId); - + List findCreatedByInstance(long id); - + List findByPoolId(long poolId); - - List findByInstanceAndDeviceId(long instanceId, long deviceId); - + + List findByInstanceAndDeviceId(long instanceId, long deviceId); + List findUsableVolumesForInstance(long instanceId); - - Long countAllocatedVolumesForAccount(long accountId); - + + Long countAllocatedVolumesForAccount(long accountId); + HypervisorType getHypervisorType(long volumeId); - + List listVolumesToBeDestroyed(); - + ImageFormat getImageFormat(Long volumeId); - + List findReadyRootVolumesByInstance(long instanceId); - + List listPoolIdsByVolumeCount(long dcId, Long podId, Long clusterId, long accountId); VolumeVO allocVolume(long size, VolumeType type, String volName, Long templateId); diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDaoImpl.java index 25aa2aa1750..59211a88d82 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeDaoImpl.java @@ -50,7 +50,7 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; -@Local(value=VolumeDao.class) +@Local(value = VolumeDao.class) @Component public class VolumeDaoImpl extends GenericDaoBase implements VolumeDao { private static final Logger s_logger = Logger.getLogger(VolumeDaoImpl.class); @@ -61,23 +61,22 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol protected final SearchBuilder InstanceStatesSearch; protected final SearchBuilder AllFieldsSearch; protected GenericSearchBuilder CountByAccount; - ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); - + //ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); + ResourceTagsDaoImpl _tagsDao = null; 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(); @@ -85,172 +84,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", new RootDisk().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, VolumeType vType) { + + @Override + public List findByInstanceAndType(long id, VolumeType 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", new RootDisk().toString()); - 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", new RootDisk().toString()); + 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; } } - - protected VolumeDaoImpl() { - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ); + + protected 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); @@ -262,33 +261,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); @@ -297,75 +296,78 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol CountByAccount = createSearchBuilder(Long.class); CountByAccount.select(null, Func.COUNT, null); CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); - CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); + CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); CountByAccount.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); - return customSearch(sc, null).get(0); - } + sc.setParameters("state", Volume.State.Destroy); + return customSearch(sc, null).get(0); + } - public static class SumCount { - public long sum; - public long count; - public SumCount() { - } - } + public static class SumCount { + public long sum; + public long count; + + public SumCount() { + } + } @Override public List listVolumesToBeDestroyed() { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("state", Volume.State.Destroy); - + return listBy(sc); } - @Override - public boolean updateState(Volume.State currentState, - VolumeEvent event, Volume.State nextState, VolumeVO 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(Volume.State currentState, VolumeEvent event, Volume.State nextState, VolumeVO 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) { @@ -379,7 +381,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)); @@ -391,8 +393,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); @@ -401,7 +404,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) { @@ -415,12 +418,12 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol txn.commit(); return result; } - + @Override @DB public VolumeVO allocVolume(long size, VolumeType type, String volName, Long templateId) { - VolumeVO vol = new VolumeVO(size, type.toString(), volName, templateId); - vol = this.persist(vol); - return vol; + VolumeVO vol = new VolumeVO(size, type.toString(), volName, templateId); + vol = this.persist(vol); + return vol; } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java index fc9dbc5b011..04104f67797 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/VolumeVO.java @@ -16,6 +16,7 @@ //under the License. package org.apache.cloudstack.storage.volume.db; + import java.util.Date; import java.util.UUID; @@ -33,8 +34,6 @@ import javax.persistence.TemporalType; import org.apache.cloudstack.engine.subsystem.api.storage.disktype.Unknown; - - import com.cloud.api.Identity; import com.cloud.storage.Volume; import com.cloud.storage.Storage.StoragePoolType; @@ -44,383 +43,383 @@ import com.cloud.utils.fsm.StateObject; @Entity @Table(name = "volumes") -public class VolumeVO implements Identity, StateObject{ - @Id - @TableGenerator(name = "volume_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "volume_seq", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.TABLE) - @Column(name = "id") - long id; - - @Column(name = "name") - String name; - - @Column(name = "pool_id") - Long poolId; - - @Column(name = "last_pool_id") - Long lastPoolId; - - @Column(name = "account_id") - long accountId; - - @Column(name = "domain_id") - long domainId; - - @Column(name = "instance_id") - Long instanceId = null; - - @Column(name = "device_id") - Long deviceId = null; - - @Column(name = "size") - long size; - - @Column(name = "folder") - String folder; - - @Column(name = "path") - String path; - - @Column(name = "pod_id") - Long podId; - - @Column(name = "created") - Date created; - - @Column(name = "attached") - @Temporal(value = TemporalType.TIMESTAMP) - Date attached; - - @Column(name = "data_center_id") - long dataCenterId; - - @Column(name = "host_ip") - String hostip; - - @Column(name = "disk_offering_id") - long diskOfferingId; - - @Column(name = "template_id") - Long templateId; - - @Column(name = "first_snapshot_backup_uuid") - String firstSnapshotBackupUuid; - - @Column(name = "volume_type") - String volumeType = "UNKNOWN"; - - @Column(name = "pool_type") - @Enumerated(EnumType.STRING) - StoragePoolType poolType; - - @Column(name = "disk_type") - String diskType = new Unknown().toString(); - - @Column(name = GenericDao.REMOVED_COLUMN) - Date removed; - - @Column(name = "updated") - @Temporal(value = TemporalType.TIMESTAMP) - Date updated; - - @Column(name="update_count", updatable = true, nullable=false) - protected long updatedCount; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code. - - @Column(name = "recreatable") - boolean recreatable; - - @Column(name = "state") - @Enumerated(value = EnumType.STRING) - private Volume.State state; - - @Column(name = "chain_info") - String chainInfo; - - @Column(name = "uuid") - String uuid; - - @Column(name="reservation") - String reservationId; - - // Real Constructor - public VolumeVO(long size, String type, String name, Long templateId) { - this.volumeType = type.toString(); - this.size = size; - this.name = name; - this.templateId = templateId; - this.uuid = UUID.randomUUID().toString(); - } - - // Copy Constructor - public VolumeVO(VolumeVO that) { - this(that.getSize(), that.getVolumeType(), that.getName(), that.getTemplateId()); - this.recreatable = that.isRecreatable(); - this.state = that.getState(); - this.size = that.getSize(); - this.diskOfferingId = that.getDiskOfferingId(); - this.poolId = that.getPoolId(); - this.attached = that.getAttached(); - this.chainInfo = that.getChainInfo(); - this.templateId = that.getTemplateId(); - this.deviceId = that.getDeviceId(); - this.uuid = UUID.randomUUID().toString(); - } - - public long getUpdatedCount() { - return this.updatedCount; - } - - public void incrUpdatedCount() { - this.updatedCount++; - } - - public void decrUpdatedCount() { - this.updatedCount--; - } - - public boolean isRecreatable() { - return recreatable; - } - - public void setRecreatable(boolean recreatable) { - this.recreatable = recreatable; - } - - public long getId() { - return id; - } - - - public Long getPodId() { - return podId; - } - - - public long getDataCenterId() { - return dataCenterId; - } - - public String getName() { - return name; - } - - public long getAccountId() { - return accountId; - } - - public void setPoolType(StoragePoolType poolType) { - this.poolType = poolType; - } - - public StoragePoolType getPoolType() { - return poolType; - } - - public long getDomainId() { - return domainId; - } - - public String getFolder() { - return folder; - } - - public String getPath() { - return path; - } - - protected VolumeVO() { - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public Long getInstanceId() { - return instanceId; - } - - public Long getDeviceId() { - return deviceId; - } - - public void setDeviceId(Long deviceId) { - this.deviceId = deviceId; - } - - public String getVolumeType() { - return volumeType; - } - - public void setName(String name) { - this.name = name; - } - - public void setFolder(String folder) { - this.folder = folder; - } - - public void setAccountId(long accountId) { - this.accountId = accountId; - } - - public void setDomainId(long domainId) { - this.domainId = domainId; - } - - public void setInstanceId(Long instanceId) { - this.instanceId = instanceId; - } - - public void setPath(String path) { - this.path = path; - } - - public String getHostIp() { - return hostip; - } - - public void setHostIp(String hostip) { - this.hostip = hostip; - } - - public void setPodId(Long podId) { - this.podId = podId; - } - - public void setDataCenterId(long dataCenterId) { - this.dataCenterId = dataCenterId; - } - - public void setVolumeType(String type) { - volumeType = type; - } - - public Date getCreated() { - return created; - } - - public Date getRemoved() { - return removed; - } - - public void setRemoved(Date removed) { - this.removed = removed; - } - - public long getDiskOfferingId() { - return diskOfferingId; - } - - public void setDiskOfferingId(long diskOfferingId) { - this.diskOfferingId = diskOfferingId; - } - - public Long getTemplateId() { - return templateId; - } - - public void setTemplateId(Long templateId) { - this.templateId = templateId; - } - - public String getFirstSnapshotBackupUuid() { - return firstSnapshotBackupUuid; - } - - public void setFirstSnapshotBackupUuid(String firstSnapshotBackupUuid) { - this.firstSnapshotBackupUuid = firstSnapshotBackupUuid; - } - - public Long getPoolId() { - return poolId; - } - - public void setPoolId(Long poolId) { - this.poolId = poolId; - } - - public Date getUpdated() { - return updated; - } - - public Volume.State getState() { - return state; - } - - public void setUpdated(Date updated) { - this.updated = updated; - } - - @Override - public String toString() { - return new StringBuilder("Vol[").append(id).append("|vm=").append(instanceId).append("|").append(volumeType).append("]").toString(); - } - - public Date getAttached() { - return this.attached; - } - - public void setAttached(Date attached) { - this.attached = attached; - } - - public String getChainInfo() { - return this.chainInfo; - } - - public void setChainInfo(String chainInfo) { - this.chainInfo = chainInfo; - } - - public Long getLastPoolId() { - return this.lastPoolId; - } - - public void setLastPoolId(Long poolId) { - this.lastPoolId = poolId; - } - - @Override - public int hashCode() { - return NumbersUtil.hash(id); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof VolumeVO) { - return id == ((VolumeVO) obj).id; - } else { - return false; - } - } - - public String getReservationId() { - return this.reservationId; - } - - public void setReservationId(String reserv) { - this.reservationId = reserv; - } - - @Override - public String getUuid() { - return this.uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getDiskType() { - return diskType; - } - - public void setDiskType(String type) { - diskType = type; - } +public class VolumeVO implements Identity, StateObject { + @Id + @TableGenerator(name = "volume_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "volume_seq", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.TABLE) + @Column(name = "id") + long id; + + @Column(name = "name") + String name; + + @Column(name = "pool_id") + Long poolId; + + @Column(name = "last_pool_id") + Long lastPoolId; + + @Column(name = "account_id") + long accountId; + + @Column(name = "domain_id") + long domainId; + + @Column(name = "instance_id") + Long instanceId = null; + + @Column(name = "device_id") + Long deviceId = null; + + @Column(name = "size") + long size; + + @Column(name = "folder") + String folder; + + @Column(name = "path") + String path; + + @Column(name = "pod_id") + Long podId; + + @Column(name = "created") + Date created; + + @Column(name = "attached") + @Temporal(value = TemporalType.TIMESTAMP) + Date attached; + + @Column(name = "data_center_id") + long dataCenterId; + + @Column(name = "host_ip") + String hostip; + + @Column(name = "disk_offering_id") + long diskOfferingId; + + @Column(name = "template_id") + Long templateId; + + @Column(name = "first_snapshot_backup_uuid") + String firstSnapshotBackupUuid; + + @Column(name = "volume_type") + String volumeType = "UNKNOWN"; + + @Column(name = "pool_type") + @Enumerated(EnumType.STRING) + StoragePoolType poolType; + + @Column(name = "disk_type") + String diskType = new Unknown().toString(); + + @Column(name = GenericDao.REMOVED_COLUMN) + Date removed; + + @Column(name = "updated") + @Temporal(value = TemporalType.TIMESTAMP) + Date updated; + + @Column(name = "update_count", updatable = true, nullable = false) + protected long updatedCount; // This field should be updated everytime the + // state is updated. There's no set method in + // the vo object because it is done with in the + // dao code. + + @Column(name = "recreatable") + boolean recreatable; + + @Column(name = "state") + @Enumerated(value = EnumType.STRING) + private Volume.State state; + + @Column(name = "chain_info") + String chainInfo; + + @Column(name = "uuid") + String uuid; + + @Column(name = "reservation") + String reservationId; + + // Real Constructor + public VolumeVO(long size, String type, String name, Long templateId) { + this.volumeType = type.toString(); + this.size = size; + this.name = name; + this.templateId = templateId; + this.uuid = UUID.randomUUID().toString(); + } + + // Copy Constructor + public VolumeVO(VolumeVO that) { + this(that.getSize(), that.getVolumeType(), that.getName(), that.getTemplateId()); + this.recreatable = that.isRecreatable(); + this.state = that.getState(); + this.size = that.getSize(); + this.diskOfferingId = that.getDiskOfferingId(); + this.poolId = that.getPoolId(); + this.attached = that.getAttached(); + this.chainInfo = that.getChainInfo(); + this.templateId = that.getTemplateId(); + this.deviceId = that.getDeviceId(); + this.uuid = UUID.randomUUID().toString(); + } + + public long getUpdatedCount() { + return this.updatedCount; + } + + public void incrUpdatedCount() { + this.updatedCount++; + } + + public void decrUpdatedCount() { + this.updatedCount--; + } + + public boolean isRecreatable() { + return recreatable; + } + + public void setRecreatable(boolean recreatable) { + this.recreatable = recreatable; + } + + public long getId() { + return id; + } + + public Long getPodId() { + return podId; + } + + public long getDataCenterId() { + return dataCenterId; + } + + public String getName() { + return name; + } + + public long getAccountId() { + return accountId; + } + + public void setPoolType(StoragePoolType poolType) { + this.poolType = poolType; + } + + public StoragePoolType getPoolType() { + return poolType; + } + + public long getDomainId() { + return domainId; + } + + public String getFolder() { + return folder; + } + + public String getPath() { + return path; + } + + protected VolumeVO() { + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public Long getInstanceId() { + return instanceId; + } + + public Long getDeviceId() { + return deviceId; + } + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + public String getVolumeType() { + return volumeType; + } + + public void setName(String name) { + this.name = name; + } + + public void setFolder(String folder) { + this.folder = folder; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public void setInstanceId(Long instanceId) { + this.instanceId = instanceId; + } + + public void setPath(String path) { + this.path = path; + } + + public String getHostIp() { + return hostip; + } + + public void setHostIp(String hostip) { + this.hostip = hostip; + } + + public void setPodId(Long podId) { + this.podId = podId; + } + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + public void setVolumeType(String type) { + volumeType = type; + } + + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public long getDiskOfferingId() { + return diskOfferingId; + } + + public void setDiskOfferingId(long diskOfferingId) { + this.diskOfferingId = diskOfferingId; + } + + public Long getTemplateId() { + return templateId; + } + + public void setTemplateId(Long templateId) { + this.templateId = templateId; + } + + public String getFirstSnapshotBackupUuid() { + return firstSnapshotBackupUuid; + } + + public void setFirstSnapshotBackupUuid(String firstSnapshotBackupUuid) { + this.firstSnapshotBackupUuid = firstSnapshotBackupUuid; + } + + public Long getPoolId() { + return poolId; + } + + public void setPoolId(Long poolId) { + this.poolId = poolId; + } + + public Date getUpdated() { + return updated; + } + + public Volume.State getState() { + return state; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + @Override + public String toString() { + return new StringBuilder("Vol[").append(id).append("|vm=").append(instanceId).append("|").append(volumeType).append("]").toString(); + } + + public Date getAttached() { + return this.attached; + } + + public void setAttached(Date attached) { + this.attached = attached; + } + + public String getChainInfo() { + return this.chainInfo; + } + + public void setChainInfo(String chainInfo) { + this.chainInfo = chainInfo; + } + + public Long getLastPoolId() { + return this.lastPoolId; + } + + public void setLastPoolId(Long poolId) { + this.lastPoolId = poolId; + } + + @Override + public int hashCode() { + return NumbersUtil.hash(id); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof VolumeVO) { + return id == ((VolumeVO) obj).id; + } else { + return false; + } + } + + public String getReservationId() { + return this.reservationId; + } + + public void setReservationId(String reserv) { + this.reservationId = reserv; + } + + @Override + public String getUuid() { + return this.uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getDiskType() { + return diskType; + } + + public void setDiskType(String type) { + diskType = type; + } } - diff --git a/engine/storage/test/org/apache/cloudstack/storage/test/volumeServiceTest.java b/engine/storage/test/org/apache/cloudstack/storage/test/volumeServiceTest.java index ebd41ed0e49..d096cd5a45c 100644 --- a/engine/storage/test/org/apache/cloudstack/storage/test/volumeServiceTest.java +++ b/engine/storage/test/org/apache/cloudstack/storage/test/volumeServiceTest.java @@ -21,11 +21,13 @@ package org.apache.cloudstack.storage.test; import static org.junit.Assert.*; import java.awt.List; +import java.util.HashMap; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.inject.Inject; +import javax.naming.ConfigurationException; import org.apache.cloudstack.engine.subsystem.api.storage.disktype.QCOW2; import org.apache.cloudstack.engine.subsystem.api.storage.disktype.VHD; @@ -35,23 +37,18 @@ import org.apache.cloudstack.engine.subsystem.api.storage.disktype.VolumeDiskTyp import org.apache.cloudstack.engine.subsystem.api.storage.type.VolumeTypeHelper; import org.apache.cloudstack.storage.datastore.DefaultPrimaryDataStoreImpl; import org.apache.cloudstack.storage.datastore.provider.DefaultPrimaryDatastoreProviderImpl; -import org.apache.cloudstack.storage.datastore.provider.PrimaryDataStoreProvider; import org.apache.cloudstack.storage.image.format.ISO; import org.apache.cloudstack.storage.image.format.ImageFormat; import org.apache.cloudstack.storage.image.format.ImageFormatHelper; import org.apache.cloudstack.storage.image.format.OVA; import org.apache.cloudstack.storage.image.format.Unknown; -import org.apache.cloudstack.storage.volume.VolumeMotionService; -import org.apache.cloudstack.storage.volume.VolumeService; -import org.apache.cloudstack.storage.volume.db.VolumeDao; +import org.apache.cloudstack.storage.image.provider.ImageDataStoreProviderManager; import org.junit.Before; import org.junit.Test; + import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; + import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.mockito.Mockito.*; @@ -61,37 +58,25 @@ import com.cloud.utils.component.ComponentInject; import com.cloud.utils.db.DB; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="storageContext.xml") +@ContextConfiguration(locations="classpath:/resource/storageContext.xml") public class volumeServiceTest { - @Autowired - protected VolumeService volService; - @Inject - protected VolumeDao volumeDao; - @Autowired - protected VolumeMotionService vmotion; + @Inject + ImageDataStoreProviderManager imageProviderMgr; @Before public void setUp() { - Mockito.when(vmotion.copyVolume(null, null)).thenReturn(false); + } - @DB + @Test public void test() { - assertTrue(volService.deleteVolume(1) != false); - assertNotNull(volumeDao); - //VolumeVO vol = new VolumeVO(Volume.Type.DATADISK, "test", 1, 2, 2, 1, 1); - //volumeDao.persist(vol); - /* - VolumeVO volume = new VolumeVO(); - String name = "test"; - long size = 100; - volume.setName(name); - volume.setSize(size); - volumeDao.persist(volume); - VolumeVO newVol = volumeDao.getVolumeByName(name); - assertTrue(newVol.getSize() == volume.getSize()); - */ - - fail("Not yet implemented"); + try { + + imageProviderMgr.configure("image Provider", new HashMap()); + + } catch (ConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } //@Test diff --git a/engine/storage/test/org/apache/cloudstack/storage/test/storageContext.xml b/engine/storage/test/resource/storageContext.xml similarity index 97% rename from engine/storage/test/org/apache/cloudstack/storage/test/storageContext.xml rename to engine/storage/test/resource/storageContext.xml index c32004bb61d..0dab1f559b0 100644 --- a/engine/storage/test/org/apache/cloudstack/storage/test/storageContext.xml +++ b/engine/storage/test/resource/storageContext.xml @@ -14,7 +14,7 @@ - + diff --git a/server/src/com/cloud/storage/dao/VolumeDaoImpl.java b/server/src/com/cloud/storage/dao/VolumeDaoImpl.java index 37f8fcf0738..065f50bc0e9 100755 --- a/server/src/com/cloud/storage/dao/VolumeDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VolumeDaoImpl.java @@ -50,7 +50,6 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; -@Component @Local(value=VolumeDao.class) public class VolumeDaoImpl extends GenericDaoBase implements VolumeDao { private static final Logger s_logger = Logger.getLogger(VolumeDaoImpl.class);