forked from AnythingLinux/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemplateManagerImpl.java
More file actions
executable file
·1763 lines (1533 loc) · 75.7 KB
/
TemplateManagerImpl.java
File metadata and controls
executable file
·1763 lines (1533 loc) · 75.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 com.cloud.template;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd;
import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd;
import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd;
import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd;
import org.apache.cloudstack.api.command.user.iso.ListIsoPermissionsCmd;
import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd;
import org.apache.cloudstack.api.command.user.iso.UpdateIsoPermissionsCmd;
import org.apache.cloudstack.api.command.user.template.CopyTemplateCmd;
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.ExtractTemplateCmd;
import org.apache.cloudstack.api.command.user.template.ListTemplatePermissionsCmd;
import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd;
import org.apache.cloudstack.api.command.user.template.UpdateTemplatePermissionsCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
import org.apache.cloudstack.engine.subsystem.api.storage.Scope;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.storage.command.AttachCommand;
import org.apache.cloudstack.storage.command.CommandResult;
import org.apache.cloudstack.storage.command.DettachCommand;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.ComputeChecksumCommand;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.NfsTO;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.dao.UserVmJoinDao;
import com.cloud.api.query.vo.UserVmJoinVO;
import com.cloud.configuration.Config;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.projects.Project;
import com.cloud.projects.ProjectManager;
import com.cloud.resource.ResourceManager;
import com.cloud.server.ConfigurationServer;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.LaunchPermissionVO;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePool;
import com.cloud.storage.StoragePoolHostVO;
import com.cloud.storage.StoragePoolStatus;
import com.cloud.storage.TemplateProfile;
import com.cloud.storage.Upload;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStoragePoolVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeManager;
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.UploadDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateDetailsDao;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VMTemplateS3Dao;
import com.cloud.storage.dao.VMTemplateSwiftDao;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.download.DownloadMonitor;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.storage.upload.UploadMonitor;
import com.cloud.template.TemplateAdapter.TemplateAdapterType;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountService;
import com.cloud.user.AccountVO;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.EnumUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Component
@Local(value = { TemplateManager.class, TemplateApiService.class })
public class TemplateManagerImpl extends ManagerBase implements TemplateManager, TemplateApiService {
private final static Logger s_logger = Logger.getLogger(TemplateManagerImpl.class);
@Inject
VMTemplateDao _tmpltDao;
@Inject
TemplateDataStoreDao _tmplStoreDao;
@Inject
VMTemplatePoolDao _tmpltPoolDao;
@Inject
VMTemplateZoneDao _tmpltZoneDao;
@Inject
protected VMTemplateDetailsDao _templateDetailsDao;
@Inject
VMInstanceDao _vmInstanceDao;
@Inject
PrimaryDataStoreDao _poolDao;
@Inject
StoragePoolHostDao _poolHostDao;
@Inject
EventDao _eventDao;
@Inject
DownloadMonitor _downloadMonitor;
@Inject
UploadMonitor _uploadMonitor;
@Inject
UserAccountDao _userAccountDao;
@Inject
AccountDao _accountDao;
@Inject
UserDao _userDao;
@Inject
AgentManager _agentMgr;
@Inject
AccountManager _accountMgr;
@Inject
HostDao _hostDao;
@Inject
DataCenterDao _dcDao;
@Inject
UserVmDao _userVmDao;
@Inject
VolumeDao _volumeDao;
@Inject
SnapshotDao _snapshotDao;
@Inject
VMTemplateSwiftDao _tmpltSwiftDao;
@Inject
VMTemplateS3Dao _vmS3TemplateDao;
@Inject
ConfigurationDao _configDao;
@Inject
ClusterDao _clusterDao;
@Inject
DomainDao _domainDao;
@Inject
UploadDao _uploadDao;
@Inject
protected GuestOSDao _guestOSDao;
@Inject
StorageManager _storageMgr;
@Inject
AsyncJobManager _asyncMgr;
@Inject
UserVmManager _vmMgr;
@Inject
UsageEventDao _usageEventDao;
@Inject
HypervisorGuruManager _hvGuruMgr;
@Inject
AccountService _accountService;
@Inject
ResourceLimitService _resourceLimitMgr;
@Inject
SecondaryStorageVmManager _ssvmMgr;
@Inject
LaunchPermissionDao _launchPermissionDao;
@Inject
ProjectManager _projectMgr;
@Inject
VolumeDataFactory _volFactory;
@Inject
TemplateDataFactory _tmplFactory;
@Inject
SnapshotDataFactory _snapshotFactory;
@Inject
TemplateService _tmpltSvr;
@Inject
DataStoreManager _dataStoreMgr;
@Inject
protected ResourceManager _resourceMgr;
@Inject
VolumeManager _volumeMgr;
@Inject
ImageStoreDao _imageStoreDao;
@Inject
EndPointSelector _epSelector;
@Inject
UserVmJoinDao _userVmJoinDao;
@Inject
ConfigurationServer _configServer;
int _primaryStorageDownloadWait;
int _storagePoolMaxWaitSeconds = 3600;
boolean _disableExtraction = false;
ExecutorService _preloadExecutor;
@Inject
protected List<TemplateAdapter> _adapters;
@Inject
StorageCacheManager cacheMgr;
@Inject
EndPointSelector selector;
private TemplateAdapter getAdapter(HypervisorType type) {
TemplateAdapter adapter = null;
if (type == HypervisorType.BareMetal) {
adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName());
} else {
// see HypervisorTemplateAdapter
adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.Hypervisor.getName());
}
if (adapter == null) {
throw new CloudRuntimeException("Cannot find template adapter for " + type.toString());
}
return adapter;
}
@Override
@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);
if (template != null) {
return template;
} else {
throw new CloudRuntimeException("Failed to create ISO");
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template")
public VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException {
Account account = CallContext.current().getCallingAccount();
if (cmd.getTemplateTag() != null) {
if (!_accountService.isRootAdmin(account.getType())) {
throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
}
}
if(cmd.isRoutingType() != null){
if(!_accountService.isRootAdmin(account.getType())){
throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
}
}
TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
TemplateProfile profile = adapter.prepare(cmd);
VMTemplateVO template = adapter.create(profile);
if (template != null) {
return template;
} else {
throw new CloudRuntimeException("Failed to create a template");
}
}
@Override
public DataStore getImageStore(String storeUuid, Long zoneId) {
DataStore imageStore = null;
if (storeUuid != null) {
imageStore = _dataStoreMgr.getDataStore(storeUuid, DataStoreRole.Image);
} else {
List<DataStore> stores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
if (stores.size() > 1) {
throw new CloudRuntimeException("multiple image stores, don't know which one to use");
}
imageStore = stores.get(0);
}
return imageStore;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_EXTRACT, eventDescription = "extracting ISO", async = true)
public String extract(ExtractIsoCmd cmd) {
Account account = CallContext.current().getCallingAccount();
Long templateId = cmd.getId();
Long zoneId = cmd.getZoneId();
String url = cmd.getUrl();
String mode = cmd.getMode();
Long eventId = cmd.getStartEventId();
return extract(account, templateId, url, zoneId, mode, eventId, true);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_EXTRACT, eventDescription = "extracting template", async = true)
public String extract(ExtractTemplateCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Long templateId = cmd.getId();
Long zoneId = cmd.getZoneId();
String url = cmd.getUrl();
String mode = cmd.getMode();
Long eventId = cmd.getStartEventId();
VirtualMachineTemplate template = getTemplate(templateId);
if (template == null) {
throw new InvalidParameterValueException("unable to find template with id " + templateId);
}
TemplateAdapter adapter = getAdapter(template.getHypervisorType());
TemplateProfile profile = adapter.prepareExtractTemplate(cmd);
return extract(caller, templateId, url, zoneId, mode, eventId, false);
}
@Override
public VirtualMachineTemplate prepareTemplate(long templateId, long zoneId) {
VMTemplateVO vmTemplate = _tmpltDao.findById(templateId);
if (vmTemplate == null) {
throw new InvalidParameterValueException("Unable to find template id=" + templateId);
}
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.ModifyEntry, true, vmTemplate);
prepareTemplateInAllStoragePools(vmTemplate, zoneId);
return vmTemplate;
}
private String extract(Account caller, Long templateId, String url, Long zoneId, String mode, Long eventId, boolean isISO) {
String desc = Upload.Type.TEMPLATE.toString();
if (isISO) {
desc = Upload.Type.ISO.toString();
}
eventId = eventId == null ? 0 : eventId;
if (!_accountMgr.isRootAdmin(caller.getType()) && _disableExtraction) {
throw new PermissionDeniedException("Extraction has been disabled by admin");
}
VMTemplateVO template = _tmpltDao.findById(templateId);
if (template == null || template.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find " + desc + " with id " + templateId);
}
if (template.getTemplateType() == Storage.TemplateType.SYSTEM) {
throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName()
+ " as it is a default System template");
} else if (template.getTemplateType() == Storage.TemplateType.PERHOST) {
throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName()
+ " as it resides on host and not on SSVM");
}
if (isISO) {
if (template.getFormat() != ImageFormat.ISO) {
throw new InvalidParameterValueException("Unsupported format, could not extract the ISO");
}
} else {
if (template.getFormat() == ImageFormat.ISO) {
throw new InvalidParameterValueException("Unsupported format, could not extract the template");
}
}
if (zoneId != null && _dcDao.findById(zoneId) == null) {
throw new IllegalArgumentException("Please specify a valid zone.");
}
if (!_accountMgr.isRootAdmin(caller.getType()) && !template.isExtractable()) {
throw new InvalidParameterValueException("Unable to extract template id=" + templateId + " as it's not extractable");
}
_accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
List<DataStore> ssStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
TemplateDataStoreVO tmpltStoreRef = null;
ImageStoreEntity tmpltStore = null;
if (ssStores != null) {
for (DataStore store : ssStores) {
tmpltStoreRef = _tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
if (tmpltStoreRef != null) {
if (tmpltStoreRef.getDownloadState() == com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
tmpltStore = (ImageStoreEntity) store;
break;
}
}
}
}
if (tmpltStoreRef == null) {
throw new InvalidParameterValueException("The " + desc + " has not been downloaded ");
}
return tmpltStore.createEntityExtractUrl(tmpltStoreRef.getInstallPath(), template.getFormat());
}
public void prepareTemplateInAllStoragePools(final VMTemplateVO template, long zoneId) {
List<StoragePoolVO> pools = _poolDao.listByStatus(StoragePoolStatus.Up);
for (final StoragePoolVO pool : pools) {
if (pool.getDataCenterId() == zoneId) {
s_logger.info("Schedule to preload template " + template.getId() + " into primary storage " + pool.getId());
_preloadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
reallyRun();
} catch (Throwable e) {
s_logger.warn("Unexpected exception ", e);
}
}
private void reallyRun() {
s_logger.info("Start to preload template " + template.getId() + " into primary storage " + pool.getId());
StoragePool pol = (StoragePool) _dataStoreMgr.getPrimaryDataStore(pool.getId());
prepareTemplateForCreate(template, pol);
s_logger.info("End of preloading template " + template.getId() + " into primary storage " + pool.getId());
}
});
} else {
s_logger.info("Skip loading template " + template.getId() + " into primary storage " + pool.getId() + " as pool zone "
+ pool.getDataCenterId() + " is ");
}
}
}
@Override
@DB
public VMTemplateStoragePoolVO prepareTemplateForCreate(VMTemplateVO templ, StoragePool pool) {
VMTemplateVO template = _tmpltDao.findById(templ.getId(), true);
long poolId = pool.getId();
long templateId = template.getId();
VMTemplateStoragePoolVO templateStoragePoolRef = null;
TemplateDataStoreVO templateStoreRef = null;
templateStoragePoolRef = _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
if (templateStoragePoolRef != null) {
templateStoragePoolRef.setMarkedForGC(false);
_tmpltPoolDao.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);
}
return templateStoragePoolRef;
}
}
templateStoreRef = _tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, pool.getDataCenterId(),
VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
if (templateStoreRef == null) {
s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
return null;
}
List<StoragePoolHostVO> vos = _poolHostDao.listByHostStatus(poolId, com.cloud.host.Status.Up);
if (vos == null || vos.isEmpty()) {
throw new CloudRuntimeException("Cannot download " + templateId + " to poolId " + poolId
+ " since there is no host in the Up state connected to this pool");
}
if (templateStoragePoolRef == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Downloading template " + templateId + " to pool " + poolId);
}
DataStore srcSecStore = _dataStoreMgr.getDataStore(templateStoreRef.getDataStoreId(), DataStoreRole.Image);
TemplateInfo srcTemplate = _tmplFactory.getTemplate(templateId, srcSecStore);
AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.prepareTemplateOnPrimary(srcTemplate, pool);
try {
TemplateApiResult result = future.get();
if (result.isFailed()) {
s_logger.debug("prepare template failed:" + result.getResult());
return null;
}
return _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
} catch (Exception ex) {
s_logger.debug("failed to copy template from image store:" + srcSecStore.getName() + " to primary storage");
}
}
return null;
}
@Override
public String getChecksum(DataStore store, String templatePath) {
EndPoint ep = _epSelector.select(store);
ComputeChecksumCommand cmd = new ComputeChecksumCommand(store.getTO(), templatePath);
Answer answer = ep.sendMessage(cmd);
if (answer != null && answer.getResult()) {
return answer.getDetails();
}
return null;
}
@Override
@DB
public boolean resetTemplateDownloadStateOnPool(long templateStoragePoolRefId) {
// have to use the same lock that prepareTemplateForCreate use to
// maintain state consistency
VMTemplateStoragePoolVO templateStoragePoolRef = _tmpltPoolDao.acquireInLockTable(templateStoragePoolRefId, 1200);
if (templateStoragePoolRef == null) {
s_logger.warn("resetTemplateDownloadStateOnPool failed - unable to lock TemplateStorgePoolRef " + templateStoragePoolRefId);
return false;
}
try {
templateStoragePoolRef.setDownloadState(VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED);
_tmpltPoolDao.update(templateStoragePoolRefId, templateStoragePoolRef);
} finally {
_tmpltPoolDao.releaseFromLockTable(templateStoragePoolRefId);
}
return true;
}
@Override
@DB
public boolean copy(long userId, VMTemplateVO template, DataStore srcSecStore, DataCenterVO dstZone) throws StorageUnavailableException,
ResourceAllocationException {
long tmpltId = template.getId();
long dstZoneId = dstZone.getId();
// find all eligible image stores for the destination zone
List<DataStore> dstSecStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(dstZoneId));
if (dstSecStores == null || dstSecStores.isEmpty()) {
throw new StorageUnavailableException("Destination zone is not ready, no image store associated", DataCenter.class, dstZone.getId());
}
AccountVO account = _accountDao.findById(template.getAccountId());
// 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()));
// Event details
String copyEventType;
String createEventType;
if (template.getFormat().equals(ImageFormat.ISO)) {
copyEventType = EventTypes.EVENT_ISO_COPY;
createEventType = EventTypes.EVENT_ISO_CREATE;
} else {
copyEventType = EventTypes.EVENT_TEMPLATE_COPY;
createEventType = EventTypes.EVENT_TEMPLATE_CREATE;
}
Transaction txn = Transaction.currentTxn();
txn.start();
TemplateInfo srcTemplate = _tmplFactory.getTemplate(template.getId(), srcSecStore);
// Copy will just find one eligible image store for the destination zone
// and copy template there, not propagate to all image stores
// for that zone
for (DataStore dstSecStore : dstSecStores) {
TemplateDataStoreVO dstTmpltStore = _tmplStoreDao.findByStoreTemplate(dstSecStore.getId(), tmpltId);
if (dstTmpltStore != null && dstTmpltStore.getDownloadState() == Status.DOWNLOADED) {
return true; // already downloaded on this image store
}
AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.copyTemplate(srcTemplate, dstSecStore);
try {
TemplateApiResult result = future.get();
if (result.isFailed()) {
s_logger.debug("copy template failed for image store " + dstSecStore.getName() + ":" + result.getResult());
continue; // try next image store
}
_tmpltDao.addTemplateToZone(template, dstZoneId);
if (account.getId() != Account.ACCOUNT_ID_SYSTEM) {
UsageEventUtils.publishUsageEvent(copyEventType, account.getId(), dstZoneId, tmpltId, null, null, null, srcTmpltStore.getSize(),
template.getClass().getName(), template.getUuid());
}
return true;
} catch (Exception ex) {
s_logger.debug("failed to copy template to image store:" + dstSecStore.getName() + " ,will try next one");
}
}
return false;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_COPY, eventDescription = "copying template", async = true)
public VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException {
Long templateId = cmd.getId();
Long userId = CallContext.current().getCallingUserId();
Long sourceZoneId = cmd.getSourceZoneId();
Long destZoneId = cmd.getDestinationZoneId();
Account caller = CallContext.current().getCallingAccount();
// Verify parameters
if (sourceZoneId.equals(destZoneId)) {
throw new InvalidParameterValueException("Please specify different source and destination zones.");
}
DataCenterVO sourceZone = _dcDao.findById(sourceZoneId);
if (sourceZone == null) {
throw new InvalidParameterValueException("Please specify a valid source zone.");
}
DataCenterVO dstZone = _dcDao.findById(destZoneId);
if (dstZone == null) {
throw new InvalidParameterValueException("Please specify a valid destination zone.");
}
VMTemplateVO template = _tmpltDao.findById(templateId);
if (template == null || template.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find template with id");
}
DataStore dstSecStore = getImageStore(destZoneId, templateId);
if (dstSecStore != null) {
s_logger.debug("There is template " + templateId + " in secondary storage " + dstSecStore.getName() + " in zone " + destZoneId
+ " , don't need to copy");
return template;
}
DataStore srcSecStore = getImageStore(sourceZoneId, templateId);
if (srcSecStore == null) {
throw new InvalidParameterValueException("There is no template " + templateId + " in zone " + sourceZoneId);
}
if (srcSecStore.getScope().getScopeType() == ScopeType.REGION) {
s_logger.debug("Template " + templateId + " is in region-wide secondary storage " + dstSecStore.getName() + " , don't need to copy");
return template;
}
_accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
boolean success = copy(userId, template, srcSecStore, dstZone);
if (success) {
// increase resource count
long accountId = template.getAccountId();
if (template.getSize() != null) {
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.secondary_storage, template.getSize());
}
return template;
} else {
throw new CloudRuntimeException("Failed to copy template");
}
}
@Override
public boolean delete(long userId, long templateId, Long zoneId) {
VMTemplateVO template = _tmpltDao.findById(templateId);
if (template == null || template.getRemoved() != null) {
throw new InvalidParameterValueException("Please specify a valid template.");
}
TemplateAdapter adapter = getAdapter(template.getHypervisorType());
return adapter.delete(new TemplateProfile(userId, template, zoneId));
}
@Override
public List<VMTemplateStoragePoolVO> getUnusedTemplatesInPool(StoragePoolVO pool) {
List<VMTemplateStoragePoolVO> unusedTemplatesInPool = new ArrayList<VMTemplateStoragePoolVO>();
List<VMTemplateStoragePoolVO> allTemplatesInPool = _tmpltPoolDao.listByPoolId(pool.getId());
for (VMTemplateStoragePoolVO templatePoolVO : allTemplatesInPool) {
VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
// If this is a routing template, consider it in use
if (template.getTemplateType() == TemplateType.SYSTEM) {
continue;
}
// If the template is not yet downloaded to the pool, consider it in
// use
if (templatePoolVO.getDownloadState() != Status.DOWNLOADED) {
continue;
}
if (template.getFormat() != ImageFormat.ISO && !_volumeDao.isAnyVolumeActivelyUsingTemplateOnPool(template.getId(), pool.getId())) {
unusedTemplatesInPool.add(templatePoolVO);
}
}
return unusedTemplatesInPool;
}
@Override
public void evictTemplateFromStoragePool(VMTemplateStoragePoolVO templatePoolVO) {
StoragePool pool = (StoragePool) _dataStoreMgr.getPrimaryDataStore(templatePoolVO.getPoolId());
VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Evicting " + templatePoolVO);
}
DestroyCommand cmd = new DestroyCommand(pool, templatePoolVO);
try {
Answer answer = _storageMgr.sendToPool(pool, cmd);
if (answer != null && answer.getResult()) {
// Remove the templatePoolVO
if (_tmpltPoolDao.remove(templatePoolVO.getId())) {
s_logger.debug("Successfully evicted template: " + template.getName() + " from storage pool: " + pool.getName());
}
} else {
s_logger.info("Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
}
} catch (StorageUnavailableException e) {
s_logger.info("Storage is unavailable currently. Will retry evicte template: " + template.getName() + " from storage pool: "
+ pool.getName());
}
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
final Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);
String value = _configDao.getValue(Config.PrimaryStorageDownloadWait.toString());
_primaryStorageDownloadWait = NumbersUtil.parseInt(value, Integer.parseInt(Config.PrimaryStorageDownloadWait.getDefaultValue()));
String disableExtraction = _configDao.getValue(Config.DisableExtraction.toString());
_disableExtraction = (disableExtraction == null) ? false : Boolean.parseBoolean(disableExtraction);
_storagePoolMaxWaitSeconds = NumbersUtil.parseInt(_configDao.getValue(Config.StoragePoolMaxWaitSeconds.key()), 3600);
_preloadExecutor = Executors.newFixedThreadPool(8, new NamedThreadFactory("Template-Preloader"));
return true;
}
protected TemplateManagerImpl() {
}
@Override
public boolean templateIsDeleteable(VMTemplateHostVO templateHostRef) {
VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templateHostRef.getTemplateId());
long templateId = template.getId();
HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId());
long zoneId = secondaryStorageHost.getDataCenterId();
DataCenterVO zone = _dcDao.findById(zoneId);
// Check if there are VMs running in the template host ref's zone that
// use the template
List<VMInstanceVO> nonExpungedVms = _vmInstanceDao.listNonExpungedByZoneAndTemplate(zoneId, templateId);
if (!nonExpungedVms.isEmpty()) {
s_logger.debug("Template " + template.getName() + " in zone " + zone.getName()
+ " is not deleteable because there are non-expunged VMs deployed from this template.");
return false;
}
List<UserVmVO> userVmUsingIso = _userVmDao.listByIsoId(templateId);
// check if there is any VM using this ISO.
if (!userVmUsingIso.isEmpty()) {
s_logger.debug("ISO " + template.getName() + " in zone " + zone.getName() + " is not deleteable because it is attached to "
+ userVmUsingIso.size() + " VMs");
return false;
}
// Check if there are any snapshots for the template in the template
// host ref's zone
List<VolumeVO> volumes = _volumeDao.findByTemplateAndZone(templateId, zoneId);
for (VolumeVO volume : volumes) {
List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdVersion(volume.getId(), "2.1");
if (!snapshots.isEmpty()) {
s_logger.debug("Template " + template.getName() + " in zone " + zone.getName()
+ " is not deleteable because there are 2.1 snapshots using this template.");
return false;
}
}
return true;
}
@Override
public boolean templateIsDeleteable(long templateId) {
List<UserVmJoinVO> userVmUsingIso = _userVmJoinDao.listActiveByIsoId(templateId);
// check if there is any Vm using this ISO. We only need to check the
// case where templateId is an ISO since
// VM can be launched from ISO in secondary storage, while template will
// always be copied to
// primary storage before deploying VM.
if (!userVmUsingIso.isEmpty()) {
s_logger.debug("ISO " + templateId + " is not deleteable because it is attached to " + userVmUsingIso.size() + " VMs");
return false;
}
return true;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_DETACH, eventDescription = "detaching ISO", async = true)
public boolean detachIso(long vmId) {
Account caller = CallContext.current().getCallingAccount();
Long userId = CallContext.current().getCallingUserId();
// Verify input parameters
UserVmVO vmInstanceCheck = _userVmDao.findById(vmId);
if (vmInstanceCheck == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
UserVm userVM = _userVmDao.findById(vmId);
if (userVM == null) {
throw new InvalidParameterValueException("Please specify a valid VM.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
Long isoId = userVM.getIsoId();
if (isoId == null) {
throw new InvalidParameterValueException("The specified VM has no ISO attached to it.");
}
CallContext.current().setEventDetails("Vm Id: " +vmId+ " ISO Id: "+isoId);
State vmState = userVM.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
boolean result = attachISOToVM(vmId, userId, isoId, false); // attach=false
// => detach
if (result) {
return result;
} else {
throw new CloudRuntimeException("Failed to detach iso");
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_ATTACH, eventDescription = "attaching ISO", async = true)
public boolean attachIso(long isoId, long vmId) {
Account caller = CallContext.current().getCallingAccount();
Long userId = CallContext.current().getCallingUserId();
// Verify input parameters
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
VMTemplateVO iso = _tmpltDao.findById(isoId);
if (iso == null || iso.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find an ISO with id " + isoId);
}
// check permissions
// check if caller has access to VM and ISO
// and also check if the VM's owner has access to the ISO.
_accountMgr.checkAccess(caller, null, false, iso, vm);
Account vmOwner = _accountDao.findById(vm.getAccountId());
_accountMgr.checkAccess(vmOwner, null, false, iso, vm);
State vmState = vm.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
if ("xen-pv-drv-iso".equals(iso.getDisplayText()) && vm.getHypervisorType() != Hypervisor.HypervisorType.XenServer) {
throw new InvalidParameterValueException("Cannot attach Xenserver PV drivers to incompatible hypervisor " + vm.getHypervisorType());
}
if ("vmware-tools.iso".equals(iso.getName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
throw new InvalidParameterValueException("Cannot attach VMware tools drivers to incompatible hypervisor " + vm.getHypervisorType());
}
boolean result = attachISOToVM(vmId, userId, isoId, true);
if (result) {
return result;
} else {
throw new CloudRuntimeException("Failed to attach iso");
}
}
// for ISO, we need to consider whether to copy to cache storage or not if it is not on NFS, since our hypervisor resource always assumes that they are in NFS
@Override
public TemplateInfo prepareIso(long isoId, long dcId){
TemplateInfo tmplt = _tmplFactory.getTemplate(isoId, DataStoreRole.Image, dcId);
if (tmplt == null || tmplt.getFormat() != ImageFormat.ISO ) {
s_logger.warn("ISO: " + isoId + " does not exist in vm_template table");
return null;
}
if (tmplt.getDataStore() != null && !(tmplt.getDataStore().getTO() instanceof NfsTO)) {
// if it is s3, need to download into cache storage first
Scope destScope = new ZoneScope(dcId);
TemplateInfo cacheData = (TemplateInfo) cacheMgr.createCacheObject(tmplt, destScope);
if (cacheData == null) {
s_logger.error("Failed in copy iso from S3 to cache storage");
return null;
}
return cacheData;
} else{
return tmplt;
}
}
private boolean attachISOToVM(long vmId, long isoId, boolean attach) {
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null) {