This is an automated email from the ASF dual-hosted git repository.

dahn pushed a commit to branch 4.20
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit 06ee2fea76d1b5f4fced86793e18e365bd68b7c2
Author: Daniel Augusto Veronezi Salvador 
<[email protected]>
AuthorDate: Sun Feb 22 10:44:24 2026 -0300

    Implement/fix limit validation for secondary storage
---
 .../manager/BareMetalTemplateAdapter.java          |   1 -
 .../cloud/storage/ImageStoreUploadMonitorImpl.java |  26 +-
 .../com/cloud/storage/VolumeApiServiceImpl.java    |   3 +-
 .../cloud/template/HypervisorTemplateAdapter.java  |  35 +-
 .../com/cloud/template/TemplateAdapterBase.java    |   3 -
 .../com/cloud/template/TemplateManagerImpl.java    | 111 ++++--
 .../cloud/template/TemplateManagerImplTest.java    | 402 +++------------------
 7 files changed, 158 insertions(+), 423 deletions(-)

diff --git 
a/plugins/hypervisors/baremetal/src/main/java/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
 
b/plugins/hypervisors/baremetal/src/main/java/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
index 940897de3c9..c6c38a39809 100644
--- 
a/plugins/hypervisors/baremetal/src/main/java/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
+++ 
b/plugins/hypervisors/baremetal/src/main/java/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
@@ -106,7 +106,6 @@ public class BareMetalTemplateAdapter extends 
TemplateAdapterBase implements Tem
             }
         }
 
-        _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
         return template;
     }
 
diff --git 
a/server/src/main/java/com/cloud/storage/ImageStoreUploadMonitorImpl.java 
b/server/src/main/java/com/cloud/storage/ImageStoreUploadMonitorImpl.java
index 334e9f10835..408eb69917a 100755
--- a/server/src/main/java/com/cloud/storage/ImageStoreUploadMonitorImpl.java
+++ b/server/src/main/java/com/cloud/storage/ImageStoreUploadMonitorImpl.java
@@ -26,6 +26,10 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import com.cloud.agent.api.to.OVFInformationTO;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.resourcelimit.CheckedReservation;
+import com.cloud.user.Account;
+import com.cloud.user.dao.AccountDao;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
@@ -37,6 +41,7 @@ import 
org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
 import org.apache.cloudstack.framework.config.ConfigKey;
 import org.apache.cloudstack.framework.config.Configurable;
 import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+import org.apache.cloudstack.reservation.dao.ReservationDao;
 import org.apache.cloudstack.storage.command.UploadStatusAnswer;
 import org.apache.cloudstack.storage.command.UploadStatusAnswer.UploadStatus;
 import org.apache.cloudstack.storage.command.UploadStatusCommand;
@@ -117,6 +122,10 @@ public class ImageStoreUploadMonitorImpl extends 
ManagerBase implements ImageSto
     private TemplateJoinDao templateJoinDao;
     @Inject
     private DeployAsIsHelper deployAsIsHelper;
+    @Inject
+    private ReservationDao reservationDao;
+    @Inject
+    private AccountDao accountDao;
 
     private long _nodeId;
     private ScheduledExecutorService _executor = null;
@@ -436,8 +445,23 @@ public class ImageStoreUploadMonitorImpl extends 
ManagerBase implements ImageSto
                                     break;
                                 }
                             }
+
+                            Account owner = 
accountDao.findById(template.getAccountId());
+                            long templateSize = answer.getVirtualSize();
+
+                            try (CheckedReservation 
secondaryStorageReservation = new CheckedReservation(owner, 
Resource.ResourceType.secondary_storage, null, null, templateSize, 
reservationDao, _resourceLimitMgr)) {
+                                
_resourceLimitMgr.incrementResourceCount(owner.getId(), 
Resource.ResourceType.secondary_storage, templateSize);
+                            } catch (ResourceAllocationException e) {
+                                
tmpTemplateDataStore.setDownloadState(VMTemplateStorageResourceAssoc.Status.UPLOAD_ERROR);
+                                tmpTemplateDataStore.setState(State.Failed);
+                                stateMachine.transitTo(tmpTemplate, 
VirtualMachineTemplate.Event.OperationFailed, null, _templateDao);
+                                msg = String.format("Upload of template [%s] 
failed because its owner [%s] does not have enough secondary storage space 
available.", template.getUuid(), owner.getUuid());
+                                logger.warn(msg);
+                                sendAlert = true;
+                                break;
+                            }
+
                             stateMachine.transitTo(tmpTemplate, 
VirtualMachineTemplate.Event.OperationSucceeded, null, _templateDao);
-                            
_resourceLimitMgr.incrementResourceCount(template.getAccountId(), 
Resource.ResourceType.secondary_storage, answer.getVirtualSize());
                             //publish usage event
                             String etype = EventTypes.EVENT_TEMPLATE_CREATE;
                             if (tmpTemplate.getFormat() == 
Storage.ImageFormat.ISO) {
diff --git a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java 
b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java
index 38102619be5..a975bd62408 100644
--- a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java
+++ b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java
@@ -107,6 +107,7 @@ import 
org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO;
 import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
+import org.apache.cloudstack.utils.bytescale.ByteScaleUtils;
 import org.apache.cloudstack.utils.identity.ManagementServerNode;
 import org.apache.cloudstack.utils.imagestore.ImageStoreUtil;
 import org.apache.cloudstack.utils.jsinterpreter.TagAsRuleHelper;
@@ -522,7 +523,7 @@ public class VolumeApiServiceImpl extends ManagerBase 
implements VolumeApiServic
                 Account account = _accountDao.findById(accountId);
                 Domain domain = domainDao.findById(account.getDomainId());
 
-                
command.setDefaultMaxSecondaryStorageInGB(_resourceLimitMgr.findCorrectResourceLimitForAccountAndDomain(account,
 domain, ResourceType.secondary_storage, null));
+                
command.setDefaultMaxSecondaryStorageInGB(ByteScaleUtils.bytesToGibibytes(_resourceLimitMgr.findCorrectResourceLimitForAccountAndDomain(account,
 domain, ResourceType.secondary_storage, null)));
                 command.setAccountId(accountId);
                 Gson gson = new GsonBuilder().create();
                 String metadata = 
EncryptionUtil.encodeData(gson.toJson(command), key);
diff --git 
a/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java 
b/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java
index 1422e788e24..c096ef0eb1d 100644
--- a/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java
+++ b/server/src/main/java/com/cloud/template/HypervisorTemplateAdapter.java
@@ -37,10 +37,8 @@ import org.apache.cloudstack.annotation.AnnotationService;
 import org.apache.cloudstack.annotation.dao.AnnotationDao;
 import org.apache.cloudstack.api.ApiCommandResourceType;
 import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
-import org.apache.cloudstack.api.command.user.iso.GetUploadParamsForIsoCmd;
 import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
 import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
-import 
org.apache.cloudstack.api.command.user.template.GetUploadParamsForTemplateCmd;
 import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.direct.download.DirectDownloadManager;
@@ -66,6 +64,7 @@ import 
org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
 import org.apache.cloudstack.storage.heuristics.HeuristicRuleHelper;
 import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
+import org.apache.cloudstack.utils.bytescale.ByteScaleUtils;
 import org.apache.cloudstack.utils.security.DigestHelper;
 import org.apache.commons.collections.CollectionUtils;
 
@@ -217,19 +216,6 @@ public class HypervisorTemplateAdapter extends 
TemplateAdapterBase {
             profile.setSize(templateSize);
         }
         profile.setUrl(url);
-        // Check that the resource limit for secondary storage won't be 
exceeded
-        
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
-                ResourceType.secondary_storage,
-                UriUtils.getRemoteSize(url, followRedirects));
-        return profile;
-    }
-
-    @Override
-    public TemplateProfile prepare(GetUploadParamsForIsoCmd cmd) throws 
ResourceAllocationException {
-        TemplateProfile profile = super.prepare(cmd);
-
-        // Check that the resource limit for secondary storage won't be 
exceeded
-        
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
 ResourceType.secondary_storage);
         return profile;
     }
 
@@ -247,19 +233,7 @@ public class HypervisorTemplateAdapter extends 
TemplateAdapterBase {
             profile.setSize(templateSize);
         }
         profile.setUrl(url);
-        // Check that the resource limit for secondary storage won't be 
exceeded
-        
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
-                ResourceType.secondary_storage,
-                UriUtils.getRemoteSize(url, followRedirects));
-        return profile;
-    }
-
-    @Override
-    public TemplateProfile prepare(GetUploadParamsForTemplateCmd cmd) throws 
ResourceAllocationException {
-        TemplateProfile profile = super.prepare(cmd);
 
-        // Check that the resource limit for secondary storage won't be 
exceeded
-        
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
 ResourceType.secondary_storage);
         return profile;
     }
 
@@ -287,7 +261,6 @@ public class HypervisorTemplateAdapter extends 
TemplateAdapterBase {
             persistDirectDownloadTemplate(template.getId(), profile.getSize());
         }
 
-        _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
         return template;
     }
 
@@ -434,7 +407,7 @@ public class HypervisorTemplateAdapter extends 
TemplateAdapterBase {
                 if(payloads.isEmpty()) {
                     throw new CloudRuntimeException("unable to find zone or an 
image store with enough capacity");
                 }
-                
_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
+
                 return payloads;
             }
         });
@@ -477,7 +450,7 @@ public class HypervisorTemplateAdapter extends 
TemplateAdapterBase {
             Account account = _accountDao.findById(accountId);
             Domain domain = _domainDao.findById(account.getDomainId());
 
-            
payload.setDefaultMaxSecondaryStorageInGB(_resourceLimitMgr.findCorrectResourceLimitForAccountAndDomain(account,
 domain, ResourceType.secondary_storage, null));
+            
payload.setDefaultMaxSecondaryStorageInGB(ByteScaleUtils.bytesToGibibytes(_resourceLimitMgr.findCorrectResourceLimitForAccountAndDomain(account,
 domain, ResourceType.secondary_storage, null)));
             payload.setAccountId(accountId);
             payload.setRemoteEndPoint(ep.getPublicAddr());
             payload.setRequiresHvm(template.requiresHvm());
@@ -543,8 +516,8 @@ public class HypervisorTemplateAdapter extends 
TemplateAdapterBase {
                     UsageEventUtils.publishUsageEvent(etype, 
template.getAccountId(), -1, template.getId(), template.getName(), null, null, 
physicalSize,
                         template.getSize(), 
VirtualMachineTemplate.class.getName(), template.getUuid());
                 }
-                _resourceLimitMgr.incrementResourceCount(accountId, 
ResourceType.secondary_storage, template.getSize());
             }
+             _resourceLimitMgr.recalculateResourceCount(accountId, 
tmplt.getDomainId(), ResourceType.secondary_storage.getOrdinal());
         }
 
         return null;
diff --git a/server/src/main/java/com/cloud/template/TemplateAdapterBase.java 
b/server/src/main/java/com/cloud/template/TemplateAdapterBase.java
index d932a9e018b..e63097916ce 100644
--- a/server/src/main/java/com/cloud/template/TemplateAdapterBase.java
+++ b/server/src/main/java/com/cloud/template/TemplateAdapterBase.java
@@ -51,7 +51,6 @@ import 
org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
 
 import com.cloud.api.ApiDBUtils;
 import com.cloud.configuration.Config;
-import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.dc.DataCenterVO;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.domain.dao.DomainDao;
@@ -227,8 +226,6 @@ public abstract class TemplateAdapterBase extends 
AdapterBase implements Templat
             throw new IllegalArgumentException("Unable to find user with id " 
+ userId);
         }
 
-        _resourceLimitMgr.checkResourceLimit(templateOwner, 
ResourceType.template);
-
         // If a zoneId is specified, make sure it is valid
         if (zoneIdList != null) {
             for (Long zoneId :zoneIdList) {
diff --git a/server/src/main/java/com/cloud/template/TemplateManagerImpl.java 
b/server/src/main/java/com/cloud/template/TemplateManagerImpl.java
index bf470205107..5c34e2a7473 100755
--- a/server/src/main/java/com/cloud/template/TemplateManagerImpl.java
+++ b/server/src/main/java/com/cloud/template/TemplateManagerImpl.java
@@ -35,6 +35,8 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import com.cloud.cpu.CPU;
+import com.cloud.resourcelimit.CheckedReservation;
+import com.cloud.utils.UriUtils;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.api.BaseCmd;
@@ -87,6 +89,7 @@ import 
org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.framework.messagebus.MessageBus;
 import org.apache.cloudstack.framework.messagebus.PublishScope;
 import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+import org.apache.cloudstack.reservation.dao.ReservationDao;
 import org.apache.cloudstack.secstorage.dao.SecondaryStorageHeuristicDao;
 import org.apache.cloudstack.secstorage.heuristics.HeuristicType;
 import org.apache.cloudstack.snapshot.SnapshotHelper;
@@ -323,6 +326,9 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
     @Inject
     private HeuristicRuleHelper heuristicRuleHelper;
 
+    @Inject
+    private ReservationDao reservationDao;
+
     private TemplateAdapter getAdapter(HypervisorType type) {
         TemplateAdapter adapter = null;
         if (type == HypervisorType.BareMetal) {
@@ -347,15 +353,30 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
     @ActionEvent(eventType = EventTypes.EVENT_ISO_CREATE, eventDescription = 
"Creating ISO")
     public VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws 
ResourceAllocationException {
         TemplateAdapter adapter = getAdapter(HypervisorType.None);
-        TemplateProfile profile = adapter.prepare(cmd);
-        VMTemplateVO template = adapter.create(profile);
+        Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
 
-        if (template != null) {
-            
CallContext.current().putContextParameter(VirtualMachineTemplate.class, 
template.getUuid());
-            return template;
-        } else {
-            throw new CloudRuntimeException("Failed to create ISO");
+        // Secondary storage resource count is not incremented for 
BareMetalTemplateAdapter
+        // Note: checking the file size before registering will require the 
Management Server host to have access to the Internet and a DNS server
+        long secondaryStorageUsage = adapter instanceof 
HypervisorTemplateAdapter && !cmd.isDirectDownload() ?
+                UriUtils.getRemoteSize(cmd.getUrl(), 
StorageManager.DataStoreDownloadFollowRedirects.value()) : 0L;
+
+        try (CheckedReservation templateReservation = new 
CheckedReservation(owner, ResourceType.template, null, null, 1L, 
reservationDao, _resourceLimitMgr);
+             CheckedReservation secondaryStorageReservation = new 
CheckedReservation(owner, ResourceType.secondary_storage, null, null, 
secondaryStorageUsage, reservationDao, _resourceLimitMgr)) {
+            TemplateProfile profile = adapter.prepare(cmd);
+            VMTemplateVO template = adapter.create(profile);
+
+            // Secondary storage resource usage will be recalculated in 
com.cloud.template.HypervisorTemplateAdapter.createTemplateAsyncCallBack
+            _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
+            if (secondaryStorageUsage > 0) {
+                
_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.secondary_storage, secondaryStorageUsage);
+            }
+            if (template != null) {
+                
CallContext.current().putContextParameter(VirtualMachineTemplate.class, 
template.getUuid());
+                return template;
+            }
         }
+
+        throw new CloudRuntimeException("Failed to create ISO");
     }
 
     @Override
@@ -374,18 +395,32 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
         }
 
         TemplateAdapter adapter = 
getAdapter(HypervisorType.getType(cmd.getHypervisor()));
+        Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
+
+        long secondaryStorageUsage = adapter instanceof 
HypervisorTemplateAdapter && !cmd.isDirectDownload() ?
+                UriUtils.getRemoteSize(cmd.getUrl(), 
StorageManager.DataStoreDownloadFollowRedirects.value()) : 0L;
+
+        try (CheckedReservation templateReservation = new 
CheckedReservation(owner, ResourceType.template, null, null, 1L, 
reservationDao, _resourceLimitMgr);
+             CheckedReservation secondaryStorageReservation = new 
CheckedReservation(owner, ResourceType.secondary_storage, null, null, 
secondaryStorageUsage, reservationDao, _resourceLimitMgr)) {
         TemplateProfile profile = adapter.prepare(cmd);
         VMTemplateVO template = adapter.create(profile);
 
+        // Secondary storage resource usage will be recalculated in 
com.cloud.template.HypervisorTemplateAdapter.createTemplateAsyncCallBack
+        // for HypervisorTemplateAdapter
+        _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
+        if (secondaryStorageUsage > 0) {
+            _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.secondary_storage, secondaryStorageUsage);
+        }
+
         if (template != null) {
             
CallContext.current().putContextParameter(VirtualMachineTemplate.class, 
template.getUuid());
             if (cmd instanceof RegisterVnfTemplateCmd) {
                 vnfTemplateManager.persistVnfTemplate(template.getId(), 
(RegisterVnfTemplateCmd) cmd);
             }
             return template;
-        } else {
-            throw new CloudRuntimeException("Failed to create a Template");
         }
+        }
+        throw new CloudRuntimeException("Failed to create a Template");
     }
 
     /**
@@ -449,17 +484,35 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_ISO_CREATE, eventDescription = 
"Creating post upload ISO")
     public GetUploadParamsResponse 
registerIsoForPostUpload(GetUploadParamsForIsoCmd cmd) throws 
ResourceAllocationException, MalformedURLException {
-        TemplateAdapter adapter = getAdapter(HypervisorType.None);
-        TemplateProfile profile = adapter.prepare(cmd);
-        return registerPostUploadInternal(adapter, profile);
+        Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
+
+        try (CheckedReservation templateReservation = new 
CheckedReservation(owner, ResourceType.template, null, null, 1L, 
reservationDao, _resourceLimitMgr)) {
+            TemplateAdapter adapter = getAdapter(HypervisorType.None);
+            TemplateProfile profile = adapter.prepare(cmd);
+
+            GetUploadParamsResponse response = 
registerPostUploadInternal(adapter, profile);
+
+            _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
+
+            return response;
+        }
     }
 
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, 
eventDescription = "Creating post upload Template")
     public GetUploadParamsResponse 
registerTemplateForPostUpload(GetUploadParamsForTemplateCmd cmd) throws 
ResourceAllocationException, MalformedURLException {
-        TemplateAdapter adapter = 
getAdapter(HypervisorType.getType(cmd.getHypervisor()));
-        TemplateProfile profile = adapter.prepare(cmd);
-        return registerPostUploadInternal(adapter, profile);
+        Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
+
+        try (CheckedReservation templateReservation = new 
CheckedReservation(owner, ResourceType.template, null, null, 1L, 
reservationDao, _resourceLimitMgr)) {
+            TemplateAdapter adapter = 
getAdapter(HypervisorType.getType(cmd.getHypervisor()));
+            TemplateProfile profile = adapter.prepare(cmd);
+
+            GetUploadParamsResponse response = 
registerPostUploadInternal(adapter, profile);
+
+            _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), 
ResourceType.template);
+
+            return response;
+        }
     }
 
     @Override
@@ -826,9 +879,6 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
         // find the size of the template to be copied
         TemplateDataStoreVO srcTmpltStore = 
_tmplStoreDao.findByStoreTemplate(srcSecStore.getId(), tmpltId);
 
-        _resourceLimitMgr.checkResourceLimit(account, ResourceType.template);
-        _resourceLimitMgr.checkResourceLimit(account, 
ResourceType.secondary_storage, new Long(srcTmpltStore.getSize()).longValue());
-
         // Event details
         String copyEventType;
         if (template.getFormat().equals(ImageFormat.ISO)) {
@@ -975,21 +1025,21 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
                 // sync template from cache store to region store if it is not 
there, for cases where we are going to migrate existing NFS to S3.
                 _tmpltSvr.syncTemplateToRegionStore(template, srcSecStore);
             }
+
+            AccountVO templateOwner = 
_accountDao.findById(template.getAccountId());
+
             for (Long destZoneId : destZoneIds) {
                 DataStore dstSecStore = getImageStore(destZoneId, templateId);
                 if (dstSecStore != null) {
                     logger.debug("There is Template {} in secondary storage {} 
in zone {} , don't need to copy", template, dstSecStore, 
dataCenterVOs.get(destZoneId));
                     continue;
                 }
+                try (CheckedReservation secondaryStorageReservation = new 
CheckedReservation(templateOwner, ResourceType.secondary_storage, null, null, 
template.getSize(), reservationDao, _resourceLimitMgr)) {
                 if (!copy(userId, template, srcSecStore, 
dataCenterVOs.get(destZoneId))) {
                     failedZones.add(dataCenterVOs.get(destZoneId).getName());
+                    continue;
                 }
-                else{
-                    if (template.getSize() != null) {
-                        // increase resource count
-                        long accountId = template.getAccountId();
-                        _resourceLimitMgr.incrementResourceCount(accountId, 
ResourceType.secondary_storage, template.getSize());
-                    }
+                
_resourceLimitMgr.incrementResourceCount(templateOwner.getId(), 
ResourceType.secondary_storage, template.getSize());
                 }
             }
         }
@@ -1012,9 +1062,6 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
 
         AccountVO account = _accountDao.findById(template.getAccountId());
 
-
-        _resourceLimitMgr.checkResourceLimit(account, ResourceType.template);
-
         try {
             _tmpltDao.addTemplateToZone(template, dstZoneId);
             return true;
@@ -1946,8 +1993,9 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
             }
         }
 
-        _resourceLimitMgr.checkResourceLimit(templateOwner, 
ResourceType.template);
-        _resourceLimitMgr.checkResourceLimit(templateOwner, 
ResourceType.secondary_storage, new Long(volume != null ? volume.getSize() : 
snapshot.getSize()).longValue());
+        long templateSize = volume != null ? volume.getSize() : 
snapshot.getSize();
+        try (CheckedReservation templateReservation = new 
CheckedReservation(templateOwner, ResourceType.template, null, null, 1L, 
reservationDao, _resourceLimitMgr);
+             CheckedReservation secondaryStorageReservation = new 
CheckedReservation(templateOwner, ResourceType.secondary_storage, null, null, 
templateSize, reservationDao, _resourceLimitMgr)) {
 
         if (!isAdmin || featured == null) {
             featured = Boolean.FALSE;
@@ -2036,8 +2084,7 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
             }
 
             _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), 
ResourceType.template);
-            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), 
ResourceType.secondary_storage,
-                    new Long(volume != null ? volume.getSize() : 
snapshot.getSize()));
+            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), 
ResourceType.secondary_storage, templateSize);
         }
 
         if (template != null) {
@@ -2046,7 +2093,7 @@ public class TemplateManagerImpl extends ManagerBase 
implements TemplateManager,
         } else {
             throw new CloudRuntimeException("Failed to create a Template");
         }
-
+        }
     }
 
     @Override
diff --git 
a/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java 
b/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java
index 576930e46f4..7893d28d9ca 100755
--- a/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java
+++ b/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java
@@ -19,26 +19,17 @@
 package com.cloud.template;
 
 
-import com.cloud.agent.AgentManager;
-import com.cloud.api.query.dao.UserVmJoinDao;
-import com.cloud.configuration.Resource;
-import com.cloud.dc.dao.DataCenterDao;
-import com.cloud.deployasis.dao.TemplateDeployAsIsDetailsDao;
-import com.cloud.domain.dao.DomainDao;
-import com.cloud.event.dao.UsageEventDao;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.exception.ResourceAllocationException;
 import com.cloud.host.Status;
-import com.cloud.host.dao.HostDao;
 import com.cloud.hypervisor.Hypervisor;
 import com.cloud.hypervisor.HypervisorGuruManager;
-import com.cloud.projects.ProjectManager;
+import com.cloud.resourcelimit.CheckedReservation;
 import com.cloud.storage.DataStoreRole;
 import com.cloud.storage.GuestOSVO;
 import com.cloud.storage.Snapshot;
 import com.cloud.storage.SnapshotVO;
 import com.cloud.storage.Storage;
-import com.cloud.storage.StorageManager;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.StoragePoolStatus;
 import com.cloud.storage.TemplateProfile;
@@ -47,13 +38,11 @@ import com.cloud.storage.VMTemplateStorageResourceAssoc;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.VolumeVO;
 import com.cloud.storage.dao.GuestOSDao;
-import com.cloud.storage.dao.LaunchPermissionDao;
 import com.cloud.storage.dao.SnapshotDao;
 import com.cloud.storage.dao.StoragePoolHostDao;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.dao.VMTemplateDetailsDao;
 import com.cloud.storage.dao.VMTemplatePoolDao;
-import com.cloud.storage.dao.VMTemplateZoneDao;
 import com.cloud.storage.dao.VolumeDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
@@ -62,13 +51,11 @@ import com.cloud.user.ResourceLimitService;
 import com.cloud.user.User;
 import com.cloud.user.UserData;
 import com.cloud.user.UserVO;
-import com.cloud.user.dao.AccountDao;
-import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.concurrency.NamedThreadFactory;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.VMInstanceVO;
-import com.cloud.vm.dao.UserVmDao;
 import com.cloud.vm.dao.VMInstanceDao;
+import junit.framework.TestCase;
 import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd;
 import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
 import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
@@ -77,54 +64,34 @@ import 
org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd;
 import org.apache.cloudstack.api.command.user.template.UpdateVnfTemplateCmd;
 import 
org.apache.cloudstack.api.command.user.userdata.LinkUserDataToTemplateCmd;
 import org.apache.cloudstack.context.CallContext;
-import 
org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
-import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
 import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore;
-import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
-import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService;
-import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager;
 import 
org.apache.cloudstack.engine.subsystem.api.storage.StorageStrategyFactory;
-import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
-import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
-import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
-import org.apache.cloudstack.framework.messagebus.MessageBus;
-import org.apache.cloudstack.secstorage.dao.SecondaryStorageHeuristicDao;
+import org.apache.cloudstack.reservation.dao.ReservationDao;
 import org.apache.cloudstack.secstorage.heuristics.HeuristicType;
-import org.apache.cloudstack.snapshot.SnapshotHelper;
 import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
 import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
-import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
 import org.apache.cloudstack.storage.heuristics.HeuristicRuleHelper;
 import org.apache.cloudstack.storage.template.VnfTemplateManager;
-import org.apache.cloudstack.test.utils.SpringUtils;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockedConstruction;
 import org.mockito.Mockito;
+import org.mockito.Spy;
 import org.mockito.invocation.InvocationOnMock;
+import org.mockito.junit.MockitoJUnitRunner;
 import org.mockito.stubbing.Answer;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.FilterType;
-import org.springframework.core.type.classreading.MetadataReader;
-import org.springframework.core.type.classreading.MetadataReaderFactory;
-import org.springframework.core.type.filter.TypeFilter;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-import javax.inject.Inject;
-import java.io.IOException;
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
@@ -136,79 +103,77 @@ import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
-public class TemplateManagerImplTest {
+@RunWith(MockitoJUnitRunner.class)
+public class TemplateManagerImplTest extends TestCase {
 
-    @Inject
-    TemplateManagerImpl templateManager = new TemplateManagerImpl();
+    @Spy
+    @InjectMocks
+    TemplateManagerImpl templateManager;
 
-    @Inject
+    @Mock
     DataStoreManager dataStoreManager;
 
-    @Inject
+    @Mock
     VMTemplateDao vmTemplateDao;
 
-    @Inject
+    @Mock
     VMTemplatePoolDao vmTemplatePoolDao;
 
-    @Inject
+    @Mock
     TemplateDataStoreDao templateDataStoreDao;
 
-    @Inject
+    @Mock
     StoragePoolHostDao storagePoolHostDao;
 
-    @Inject
+    @Mock
     PrimaryDataStoreDao primaryDataStoreDao;
 
-    @Inject
+    @Mock
     ResourceLimitService resourceLimitMgr;
 
-    @Inject
+    @Mock
     ImageStoreDao imgStoreDao;
 
-    @Inject
+    @Mock
     GuestOSDao guestOSDao;
 
-    @Inject
-    VMTemplateDao tmpltDao;
-
-    @Inject
+    @Mock
     SnapshotDao snapshotDao;
 
-    @Inject
+    @Mock
+    VolumeDao volumeDao;
+
+    @Mock
     VMTemplateDetailsDao tmpltDetailsDao;
 
-    @Inject
+    @Mock
     StorageStrategyFactory storageStrategyFactory;
 
-    @Inject
+    @Mock
     VMInstanceDao _vmInstanceDao;
 
-    @Inject
-    private VMTemplateDao _tmpltDao;
+    @Mock
+    ReservationDao reservationDao;
 
-    @Inject
+    @Mock
     HypervisorGuruManager _hvGuruMgr;
 
-    @Inject
+    @Mock
     AccountManager _accountMgr;
-    @Inject
+
+    @Mock
     VnfTemplateManager vnfTemplateManager;
-    @Inject
-    TemplateDeployAsIsDetailsDao templateDeployAsIsDetailsDao;
 
-    @Inject
+    @Mock
     HeuristicRuleHelper heuristicRuleHelperMock;
 
     public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
@@ -238,7 +203,6 @@ public class TemplateManagerImplTest {
 
     @Before
     public void setUp() {
-        ComponentContext.initComponentsLifeCycle();
         AccountVO account = new AccountVO("admin", 1L, "networkDomain", 
Account.Type.NORMAL, "uuid");
         UserVO user = new UserVO(1, "testuser", "password", "firstname", 
"lastName", "email", "timezone", UUID.randomUUID().toString(), 
User.Source.UNKNOWN);
         CallContext.register(user, account);
@@ -272,7 +236,7 @@ public class TemplateManagerImplTest {
         List<TemplateAdapter> adapters  = new ArrayList<TemplateAdapter>();
         adapters.add(templateAdapter);
         when(cmd.getId()).thenReturn(0L);
-        when(_tmpltDao.findById(cmd.getId())).thenReturn(template);
+        when(vmTemplateDao.findById(cmd.getId())).thenReturn(template);
         when(cmd.getZoneId()).thenReturn(null);
 
         
when(template.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.None);
@@ -293,7 +257,6 @@ public class TemplateManagerImplTest {
         //case 2.2: When Force delete flag is 'false' and VM instance VO list 
is non empty.
         when(cmd.isForced()).thenReturn(false);
         VMInstanceVO vmInstanceVO = mock(VMInstanceVO.class);
-        when(vmInstanceVO.getInstanceName()).thenReturn("mydDummyVM");
         vmInstanceVOList.add(vmInstanceVO);
         
when(_vmInstanceDao.listNonExpungedByTemplate(anyLong())).thenReturn(vmInstanceVOList);
         try {
@@ -308,7 +271,6 @@ public class TemplateManagerImplTest {
         when(mockTemplate.getId()).thenReturn(202l);
 
         StoragePoolVO mockPool = mock(StoragePoolVO.class);
-        when(mockPool.getId()).thenReturn(2l);
 
         PrimaryDataStore mockPrimaryDataStore = mock(PrimaryDataStore.class);
         when(mockPrimaryDataStore.getId()).thenReturn(2l);
@@ -316,7 +278,6 @@ public class TemplateManagerImplTest {
         VMTemplateStoragePoolVO mockTemplateStore = 
mock(VMTemplateStoragePoolVO.class);
         
when(mockTemplateStore.getDownloadState()).thenReturn(VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
 
-        
when(dataStoreManager.getPrimaryDataStore(anyLong())).thenReturn(mockPrimaryDataStore);
         when(vmTemplateDao.findById(anyLong(), 
anyBoolean())).thenReturn(mockTemplate);
         when(vmTemplatePoolDao.findByPoolTemplate(anyLong(), anyLong(), 
nullable(String.class))).thenReturn(mockTemplateStore);
 
@@ -332,13 +293,11 @@ public class TemplateManagerImplTest {
         when(mockTemplate.getId()).thenReturn(202l);
 
         StoragePoolVO mockPool = mock(StoragePoolVO.class);
-        when(mockPool.getId()).thenReturn(2l);
 
         PrimaryDataStore mockPrimaryDataStore = mock(PrimaryDataStore.class);
         when(mockPrimaryDataStore.getId()).thenReturn(2l);
         when(mockPrimaryDataStore.getDataCenterId()).thenReturn(1l);
 
-        
when(dataStoreManager.getPrimaryDataStore(anyLong())).thenReturn(mockPrimaryDataStore);
         when(vmTemplateDao.findById(anyLong(), 
anyBoolean())).thenReturn(mockTemplate);
         when(vmTemplatePoolDao.findByPoolTemplate(anyLong(), anyLong(), 
nullable(String.class))).thenReturn(null);
         when(templateDataStoreDao.findByTemplateZoneDownloadStatus(202l, 1l, 
VMTemplateStorageResourceAssoc.Status.DOWNLOADED)).thenReturn(null);
@@ -353,7 +312,6 @@ public class TemplateManagerImplTest {
         when(mockTemplate.getId()).thenReturn(202l);
 
         StoragePoolVO mockPool = mock(StoragePoolVO.class);
-        when(mockPool.getId()).thenReturn(2l);
 
         PrimaryDataStore mockPrimaryDataStore = mock(PrimaryDataStore.class);
         when(mockPrimaryDataStore.getId()).thenReturn(2l);
@@ -361,7 +319,6 @@ public class TemplateManagerImplTest {
 
         TemplateDataStoreVO mockTemplateDataStore = 
mock(TemplateDataStoreVO.class);
 
-        
when(dataStoreManager.getPrimaryDataStore(anyLong())).thenReturn(mockPrimaryDataStore);
         when(vmTemplateDao.findById(anyLong(), 
anyBoolean())).thenReturn(mockTemplate);
         when(vmTemplatePoolDao.findByPoolTemplate(anyLong(), anyLong(), 
nullable(String.class))).thenReturn(null);
         when(templateDataStoreDao.findByTemplateZoneDownloadStatus(202l, 1l, 
VMTemplateStorageResourceAssoc.Status.DOWNLOADED)).thenReturn(mockTemplateDataStore);
@@ -412,20 +369,10 @@ public class TemplateManagerImplTest {
         PrimaryDataStore mockPrimaryDataStore = mock(PrimaryDataStore.class);
         VMTemplateStoragePoolVO mockTemplateStore = 
mock(VMTemplateStoragePoolVO.class);
 
-        when(mockPrimaryDataStore.getId()).thenReturn(2l);
-        when(mockPool.getId()).thenReturn(2l);
         when(mockPool.getStatus()).thenReturn(StoragePoolStatus.Disabled);
-        when(mockPool.getDataCenterId()).thenReturn(1l);
-        when(mockTemplate.getId()).thenReturn(202l);
-        
when(mockTemplateStore.getDownloadState()).thenReturn(VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
         when(vmTemplateDao.findById(anyLong())).thenReturn(mockTemplate);
-        
when(dataStoreManager.getPrimaryDataStore(anyLong())).thenReturn(mockPrimaryDataStore);
-        when(vmTemplateDao.findById(anyLong(), 
anyBoolean())).thenReturn(mockTemplate);
-        when(vmTemplatePoolDao.findByPoolTemplate(anyLong(), anyLong(), 
nullable(String.class))).thenReturn(mockTemplateStore);
         when(primaryDataStoreDao.findById(anyLong())).thenReturn(mockPool);
 
-        doNothing().when(mockTemplateStore).setMarkedForGC(anyBoolean());
-
         ExecutorService preloadExecutor = new CustomThreadPoolExecutor(8, 8, 
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(),
                 new NamedThreadFactory("Template-Preloader"));
         templateManager._preloadExecutor = preloadExecutor;
@@ -443,15 +390,10 @@ public class TemplateManagerImplTest {
 
         StoragePoolVO mockPool1 = mock(StoragePoolVO.class);
         when(mockPool1.getId()).thenReturn(2l);
-        when(mockPool1.getStatus()).thenReturn(StoragePoolStatus.Up);
         when(mockPool1.getDataCenterId()).thenReturn(1l);
         StoragePoolVO mockPool2 = mock(StoragePoolVO.class);
-        when(mockPool2.getId()).thenReturn(3l);
-        when(mockPool2.getStatus()).thenReturn(StoragePoolStatus.Up);
         when(mockPool2.getDataCenterId()).thenReturn(1l);
         StoragePoolVO mockPool3 = mock(StoragePoolVO.class);
-        when(mockPool3.getId()).thenReturn(4l);
-        when(mockPool3.getStatus()).thenReturn(StoragePoolStatus.Up);
         when(mockPool3.getDataCenterId()).thenReturn(2l);
         pools.add(mockPool1);
         pools.add(mockPool2);
@@ -464,9 +406,6 @@ public class TemplateManagerImplTest {
         
when(dataStoreManager.getPrimaryDataStore(anyLong())).thenReturn(mockPrimaryDataStore);
         when(vmTemplateDao.findById(anyLong(), 
anyBoolean())).thenReturn(mockTemplate);
         when(vmTemplatePoolDao.findByPoolTemplate(anyLong(), anyLong(), 
nullable(String.class))).thenReturn(mockTemplateStore);
-        when(primaryDataStoreDao.findById(2l)).thenReturn(mockPool1);
-        when(primaryDataStoreDao.findById(3l)).thenReturn(mockPool2);
-        when(primaryDataStoreDao.findById(4l)).thenReturn(mockPool3);
         
when(primaryDataStoreDao.listByStatus(StoragePoolStatus.Up)).thenReturn(pools);
 
         doNothing().when(mockTemplateStore).setMarkedForGC(anyBoolean());
@@ -494,7 +433,6 @@ public class TemplateManagerImplTest {
         when(mockCreateCmd.getVolumeId()).thenReturn(null);
         when(mockCreateCmd.getSnapshotId()).thenReturn(1L);
         when(mockCreateCmd.getOsTypeId()).thenReturn(1L);
-        when(mockCreateCmd.getEventDescription()).thenReturn("test");
         when(mockCreateCmd.getDetails()).thenReturn(null);
         when(mockCreateCmd.getZoneId()).thenReturn(null);
 
@@ -507,20 +445,17 @@ public class TemplateManagerImplTest {
         when(mockSnapshot.getState()).thenReturn(Snapshot.State.BackedUp);
         
when(mockSnapshot.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.XenServer);
 
-        
doNothing().when(resourceLimitMgr).checkResourceLimit(any(Account.class), 
eq(Resource.ResourceType.template));
-        
doNothing().when(resourceLimitMgr).checkResourceLimit(any(Account.class), 
eq(Resource.ResourceType.secondary_storage), anyLong());
-
         GuestOSVO mockGuestOS = mock(GuestOSVO.class);
         when(guestOSDao.findById(anyLong())).thenReturn(mockGuestOS);
 
-        when(tmpltDao.getNextInSequence(eq(Long.class), 
eq("id"))).thenReturn(1L);
+        when(vmTemplateDao.getNextInSequence(eq(Long.class), 
eq("id"))).thenReturn(1L);
 
         List<ImageStoreVO> mockRegionStores = new ArrayList<>();
         ImageStoreVO mockRegionStore = mock(ImageStoreVO.class);
         mockRegionStores.add(mockRegionStore);
         when(imgStoreDao.findRegionImageStores()).thenReturn(mockRegionStores);
 
-        when(tmpltDao.persist(any(VMTemplateVO.class))).thenAnswer(new 
Answer<VMTemplateVO>() {
+        when(vmTemplateDao.persist(any(VMTemplateVO.class))).thenAnswer(new 
Answer<VMTemplateVO>() {
             @Override
             public VMTemplateVO answer(InvocationOnMock invocationOnMock) 
throws Throwable {
                 Object[] args = invocationOnMock.getArguments();
@@ -528,8 +463,10 @@ public class TemplateManagerImplTest {
             }
         });
 
-        VMTemplateVO template = 
templateManager.createPrivateTemplateRecord(mockCreateCmd, mockTemplateOwner);
-        assertTrue("Template in a region store should have cross zones set", 
template.isCrossZones());
+        try (MockedConstruction<CheckedReservation> mockCheckedReservation = 
Mockito.mockConstruction(CheckedReservation.class)) {
+            VMTemplateVO template = 
templateManager.createPrivateTemplateRecord(mockCreateCmd, mockTemplateOwner);
+            assertTrue("Template in a region store should have cross zones 
set", template.isCrossZones());
+        }
     }
 
     @Test
@@ -541,7 +478,7 @@ public class TemplateManagerImplTest {
         
when(cmd.getUserdataPolicy()).thenReturn(UserData.UserDataOverridePolicy.ALLOWOVERRIDE);
 
         VMTemplateVO template = Mockito.mock(VMTemplateVO.class);
-        when(_tmpltDao.findById(anyLong())).thenReturn(template);
+        when(vmTemplateDao.findById(anyLong())).thenReturn(template);
 
         VirtualMachineTemplate resultTemplate = 
templateManager.linkUserDataToTemplate(cmd);
 
@@ -557,7 +494,6 @@ public class TemplateManagerImplTest {
         
when(cmd.getUserdataPolicy()).thenReturn(UserData.UserDataOverridePolicy.ALLOWOVERRIDE);
 
         VMTemplateVO template = Mockito.mock(VMTemplateVO.class);
-        when(_tmpltDao.findById(1L)).thenReturn(template);
 
         templateManager.linkUserDataToTemplate(cmd);
     }
@@ -571,7 +507,6 @@ public class TemplateManagerImplTest {
         
when(cmd.getUserdataPolicy()).thenReturn(UserData.UserDataOverridePolicy.ALLOWOVERRIDE);
 
         VMTemplateVO template = Mockito.mock(VMTemplateVO.class);
-        when(_tmpltDao.findById(1L)).thenReturn(template);
 
         templateManager.linkUserDataToTemplate(cmd);
     }
@@ -584,7 +519,7 @@ public class TemplateManagerImplTest {
         when(cmd.getUserdataId()).thenReturn(2L);
         
when(cmd.getUserdataPolicy()).thenReturn(UserData.UserDataOverridePolicy.ALLOWOVERRIDE);
 
-        when(_tmpltDao.findById(anyLong())).thenReturn(null);
+        when(vmTemplateDao.findById(anyLong())).thenReturn(null);
 
         templateManager.linkUserDataToTemplate(cmd);
     }
@@ -599,7 +534,7 @@ public class TemplateManagerImplTest {
 
         VMTemplateVO template = Mockito.mock(VMTemplateVO.class);
         when(template.getId()).thenReturn(1L);
-        when(_tmpltDao.findById(1L)).thenReturn(template);
+        when(vmTemplateDao.findById(1L)).thenReturn(template);
 
         VirtualMachineTemplate resultTemplate = 
templateManager.linkUserDataToTemplate(cmd);
 
@@ -630,7 +565,6 @@ public class TemplateManagerImplTest {
         DataStore dataStore = Mockito.mock(DataStore.class);
         VolumeVO volumeVO = Mockito.mock(VolumeVO.class);
 
-        Mockito.when(dataStoreManager.getDataStore(Mockito.anyString(), 
Mockito.any(DataStoreRole.class))).thenReturn(null);
         
Mockito.when(heuristicRuleHelperMock.getImageStoreIfThereIsHeuristicRule(Mockito.anyLong(),
 Mockito.any(HeuristicType.class), 
Mockito.any(VolumeVO.class))).thenReturn(null);
         
Mockito.when(dataStoreManager.getImageStoreWithFreeCapacity(Mockito.anyLong())).thenReturn(dataStore);
 
@@ -643,7 +577,6 @@ public class TemplateManagerImplTest {
         DataStore dataStore = Mockito.mock(DataStore.class);
         VolumeVO volumeVO = Mockito.mock(VolumeVO.class);
 
-        Mockito.when(dataStoreManager.getDataStore(Mockito.anyString(), 
Mockito.any(DataStoreRole.class))).thenReturn(null);
         
Mockito.when(heuristicRuleHelperMock.getImageStoreIfThereIsHeuristicRule(Mockito.anyLong(),
 Mockito.any(HeuristicType.class), 
Mockito.any(VolumeVO.class))).thenReturn(dataStore);
 
         templateManager.getImageStore(null, 1L, volumeVO);
@@ -773,243 +706,4 @@ public class TemplateManagerImplTest {
         Mockito.verify(heuristicRuleHelperMock, 
Mockito.times(1)).getImageStoreIfThereIsHeuristicRule(1L, 
HeuristicType.TEMPLATE, vmTemplateVOMock);
     }
 
-    @Configuration
-    @ComponentScan(basePackageClasses = {TemplateManagerImpl.class},
-            includeFilters = {@ComponentScan.Filter(value = 
TestConfiguration.Library.class, type = FilterType.CUSTOM)},
-            useDefaultFilters = false)
-    public static class TestConfiguration extends 
SpringUtils.CloudStackTestConfiguration {
-
-        @Bean
-        public DataStoreManager dataStoreManager() {
-            return Mockito.mock(DataStoreManager.class);
-        }
-
-        @Bean
-        public VMTemplateDao vmTemplateDao() {
-            return Mockito.mock(VMTemplateDao.class);
-        }
-
-        @Bean
-        public StorageStrategyFactory storageStrategyFactory() {
-            return Mockito.mock(StorageStrategyFactory.class);
-        }
-
-        @Bean
-        public VMTemplatePoolDao vmTemplatePoolDao() {
-            return Mockito.mock(VMTemplatePoolDao.class);
-        }
-
-        @Bean
-        public TemplateDataStoreDao templateDataStoreDao() {
-            return Mockito.mock(TemplateDataStoreDao.class);
-        }
-
-        @Bean
-        public VMTemplateZoneDao vmTemplateZoneDao() {
-            return Mockito.mock(VMTemplateZoneDao.class);
-        }
-
-        @Bean
-        public VMInstanceDao vmInstanceDao() {
-            return Mockito.mock(VMInstanceDao.class);
-        }
-
-        @Bean
-        public PrimaryDataStoreDao primaryDataStoreDao() {
-            return Mockito.mock(PrimaryDataStoreDao.class);
-        }
-
-        @Bean
-        public StoragePoolHostDao storagePoolHostDao() {
-            return Mockito.mock(StoragePoolHostDao.class);
-        }
-
-        @Bean
-        public AccountDao accountDao() {
-            return Mockito.mock(AccountDao.class);
-        }
-
-        @Bean
-        public AgentManager agentMgr() {
-            return Mockito.mock(AgentManager.class);
-        }
-
-        @Bean
-        public AccountManager accountManager() {
-            return Mockito.mock(AccountManager.class);
-        }
-
-        @Bean
-        public HostDao hostDao() {
-            return Mockito.mock(HostDao.class);
-        }
-
-        @Bean
-        public DataCenterDao dcDao() {
-            return Mockito.mock(DataCenterDao.class);
-        }
-
-        @Bean
-        public UserVmDao userVmDao() {
-            return Mockito.mock(UserVmDao.class);
-        }
-
-        @Bean
-        public VolumeDao volumeDao() {
-            return Mockito.mock(VolumeDao.class);
-        }
-
-        @Bean
-        public SnapshotDao snapshotDao() {
-            return Mockito.mock(SnapshotDao.class);
-        }
-
-        @Bean
-        public ConfigurationDao configDao() {
-            return Mockito.mock(ConfigurationDao.class);
-        }
-
-        @Bean
-        public DomainDao domainDao() {
-            return Mockito.mock(DomainDao.class);
-        }
-
-        @Bean
-        public GuestOSDao guestOSDao() {
-            return Mockito.mock(GuestOSDao.class);
-        }
-
-        @Bean
-        public StorageManager storageManager() {
-            return Mockito.mock(StorageManager.class);
-        }
-
-        @Bean
-        public UsageEventDao usageEventDao() {
-            return Mockito.mock(UsageEventDao.class);
-        }
-
-        @Bean
-        public ResourceLimitService resourceLimitMgr() {
-            return Mockito.mock(ResourceLimitService.class);
-        }
-
-        @Bean
-        public LaunchPermissionDao launchPermissionDao() {
-            return Mockito.mock(LaunchPermissionDao.class);
-        }
-
-        @Bean
-        public ProjectManager projectMgr() {
-            return Mockito.mock(ProjectManager.class);
-        }
-
-        @Bean
-        public VolumeDataFactory volFactory() {
-            return Mockito.mock(VolumeDataFactory.class);
-        }
-
-        @Bean
-        public TemplateDataFactory tmplFactory() {
-            return Mockito.mock(TemplateDataFactory.class);
-        }
-
-        @Bean
-        public SnapshotDataFactory snapshotFactory() {
-            return Mockito.mock(SnapshotDataFactory.class);
-        }
-
-        @Bean
-        public TemplateService tmpltSvr() {
-            return Mockito.mock(TemplateService.class);
-        }
-
-        @Bean
-        public VolumeOrchestrationService volumeMgr() {
-            return Mockito.mock(VolumeOrchestrationService.class);
-        }
-
-        @Bean
-        public EndPointSelector epSelector() {
-            return Mockito.mock(EndPointSelector.class);
-        }
-
-        @Bean
-        public UserVmJoinDao userVmJoinDao() {
-            return Mockito.mock(UserVmJoinDao.class);
-        }
-
-        @Bean
-        public SnapshotDataStoreDao snapshotStoreDao() {
-            return Mockito.mock(SnapshotDataStoreDao.class);
-        }
-
-        @Bean
-        public ImageStoreDao imageStoreDao() {
-            return Mockito.mock(ImageStoreDao.class);
-        }
-
-        @Bean
-        public MessageBus messageBus() {
-            return Mockito.mock(MessageBus.class);
-        }
-
-        @Bean
-        public StorageCacheManager cacheMgr() {
-            return Mockito.mock(StorageCacheManager.class);
-        }
-
-        @Bean
-        public TemplateAdapter templateAdapter() {
-            return Mockito.mock(TemplateAdapter.class);
-        }
-
-        @Bean
-        public VMTemplateDetailsDao vmTemplateDetailsDao() {
-            return Mockito.mock(VMTemplateDetailsDao.class);
-        }
-
-        @Bean
-        public HypervisorGuruManager hypervisorGuruManager() {
-            return Mockito.mock(HypervisorGuruManager.class);
-        }
-
-        @Bean
-        public VnfTemplateManager vnfTemplateManager() {
-            return Mockito.mock(VnfTemplateManager.class);
-        }
-
-        @Bean
-        public TemplateDeployAsIsDetailsDao templateDeployAsIsDetailsDao() {
-            return Mockito.mock(TemplateDeployAsIsDetailsDao.class);
-        }
-
-        @Bean
-        public SnapshotHelper snapshotHelper() {
-            return Mockito.mock(SnapshotHelper.class);
-        }
-
-        @Bean
-        public SnapshotService snapshotService() {
-            return Mockito.mock(SnapshotService.class);
-        }
-
-        @Bean
-        public SecondaryStorageHeuristicDao secondaryStorageHeuristicDao() {
-            return Mockito.mock(SecondaryStorageHeuristicDao.class);
-        }
-
-        @Bean
-        public HeuristicRuleHelper heuristicRuleHelper() {
-            return Mockito.mock(HeuristicRuleHelper.class);
-        }
-
-        public static class Library implements TypeFilter {
-            @Override
-            public boolean match(MetadataReader mdr, MetadataReaderFactory 
arg1) throws IOException {
-                ComponentScan cs = 
TestConfiguration.class.getAnnotation(ComponentScan.class);
-                return 
SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), 
cs);
-            }
-        }
-    }
 }

Reply via email to