-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathSystemVmTemplateRegistration.java
More file actions
1167 lines (1062 loc) · 52.1 KB
/
SystemVmTemplateRegistration.java
File metadata and controls
1167 lines (1062 loc) · 52.1 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.upgrade;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.config.dao.ConfigurationDaoImpl;
import org.apache.cloudstack.framework.config.impl.ConfigurationVO;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDaoImpl;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDaoImpl;
import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.cloudstack.utils.security.DigestHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ini4j.Ini;
import com.cloud.cpu.CPU;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.ClusterDaoImpl;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterDaoImpl;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.GuestOSDaoImpl;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateDaoImpl;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.storage.dao.VMTemplateZoneDaoImpl;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.upgrade.dao.BasicTemplateDataStoreDaoImpl;
import com.cloud.user.Account;
import com.cloud.utils.DateUtil;
import com.cloud.utils.HttpUtils;
import com.cloud.utils.Pair;
import com.cloud.utils.UriUtils;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.dao.VMInstanceDaoImpl;
public class SystemVmTemplateRegistration {
protected static Logger LOGGER = LogManager.getLogger(SystemVmTemplateRegistration.class);
private static final String MOUNT_COMMAND_BASE = "sudo mount -t nfs";
private static final String UMOUNT_COMMAND = "sudo umount %s";
private static final String RELATIVE_TEMPLATE_PATH = "./engine/schema/dist/systemvm-templates/";
private static final String ABSOLUTE_TEMPLATE_PATH = "/usr/share/cloudstack-management/templates/systemvm/";
private static final String TEMPLATES_PATH = fetchTemplatesPath();
private static final String METADATA_FILE_NAME = "metadata.ini";
private static final String METADATA_FILE = TEMPLATES_PATH + METADATA_FILE_NAME;
public static final String TEMPORARY_SECONDARY_STORE = "tmp";
private static final String PARTIAL_TEMPLATE_FOLDER = String.format("/template/tmpl/%d/", Account.ACCOUNT_ID_SYSTEM);
private static final String storageScriptsDir = "scripts/storage/secondary";
private static final Integer OTHER_LINUX_ID = 99;
private static Integer LINUX_12_ID = 363;
private static final Integer SCRIPT_TIMEOUT = 1800000;
private static final Integer LOCK_WAIT_TIMEOUT = 1200;
protected static final List<CPU.CPUArch> DOWNLOADABLE_TEMPLATE_ARCH_TYPES = Arrays.asList(
CPU.CPUArch.arm64
);
public static String CS_MAJOR_VERSION = null;
public static String CS_TINY_VERSION = null;
@Inject
DataCenterDao dataCenterDao;
@Inject
VMTemplateDao vmTemplateDao;
@Inject
VMTemplateZoneDao vmTemplateZoneDao;
@Inject
TemplateDataStoreDao templateDataStoreDao;
@Inject
VMInstanceDao vmInstanceDao;
@Inject
ImageStoreDao imageStoreDao;
@Inject
ImageStoreDetailsDao imageStoreDetailsDao;
@Inject
ClusterDao clusterDao;
@Inject
ConfigurationDao configurationDao;
@Inject
private GuestOSDao guestOSDao;
private String systemVmTemplateVersion;
private final File tempDownloadDir;
public SystemVmTemplateRegistration() {
dataCenterDao = new DataCenterDaoImpl();
vmTemplateDao = new VMTemplateDaoImpl();
vmTemplateZoneDao = new VMTemplateZoneDaoImpl();
templateDataStoreDao = new BasicTemplateDataStoreDaoImpl();
vmInstanceDao = new VMInstanceDaoImpl();
imageStoreDao = new ImageStoreDaoImpl();
imageStoreDetailsDao = new ImageStoreDetailsDaoImpl();
clusterDao = new ClusterDaoImpl();
configurationDao = new ConfigurationDaoImpl();
guestOSDao = new GuestOSDaoImpl();
tempDownloadDir = new File(System.getProperty("java.io.tmpdir"));
}
/**
* Convenience constructor method to use when there is no system VM template change for a new version.
*/
public SystemVmTemplateRegistration(String systemVmTemplateVersion) {
this();
this.systemVmTemplateVersion = systemVmTemplateVersion;
}
public static String getMountCommand(String nfsVersion, String device, String dir) {
String cmd = MOUNT_COMMAND_BASE;
if (StringUtils.isNotBlank(nfsVersion)) {
cmd = String.format("%s -o vers=%s", cmd, nfsVersion);
}
return String.format("%s %s %s", cmd, device, dir);
}
public String getSystemVmTemplateVersion() {
if (StringUtils.isEmpty(systemVmTemplateVersion)) {
return String.format("%s.%s", CS_MAJOR_VERSION, CS_TINY_VERSION);
}
return systemVmTemplateVersion;
}
public File getTempDownloadDir() {
return tempDownloadDir;
}
private static class SystemVMTemplateDetails {
Long id;
String uuid;
String name;
String uniqueName;
Date created;
String url;
String checksum;
ImageFormat format;
Integer guestOsId;
Hypervisor.HypervisorType hypervisorType;
CPU.CPUArch arch;
Long storeId;
Long size;
Long physicalSize;
String installPath;
boolean deployAsIs;
Date updated;
SystemVMTemplateDetails(String uuid, String name, Date created, String url, String checksum,
ImageFormat format, Integer guestOsId, Hypervisor.HypervisorType hypervisorType,
CPU.CPUArch arch, Long storeId) {
this.uuid = uuid;
this.name = name;
this.created = created;
this.url = url;
this.checksum = checksum;
this.format = format;
this.guestOsId = guestOsId;
this.hypervisorType = hypervisorType;
this.arch = arch;
this.storeId = storeId;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getUuid() {
return uuid;
}
public String getName() {
return name;
}
public Date getCreated() {
return created;
}
public String getUrl() {
return url;
}
public String getChecksum() {
return checksum;
}
public ImageFormat getFormat() {
return format;
}
public Integer getGuestOsId() {
return guestOsId;
}
public Hypervisor.HypervisorType getHypervisorType() {
return hypervisorType;
}
public CPU.CPUArch getArch() {
return arch;
}
public Long getStoreId() {
return storeId;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public Long getPhysicalSize() {
return physicalSize;
}
public void setPhysicalSize(Long physicalSize) {
this.physicalSize = physicalSize;
}
public String getInstallPath() {
return installPath;
}
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
public String getUniqueName() {
return uniqueName;
}
public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName;
}
public boolean isDeployAsIs() {
return deployAsIs;
}
public void setDeployAsIs(boolean deployAsIs) {
this.deployAsIs = deployAsIs;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
public static final List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> hypervisorList = Arrays.asList(
new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.amd64),
new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.arm64),
new Pair<>(Hypervisor.HypervisorType.VMware, CPU.CPUArch.amd64),
new Pair<>(Hypervisor.HypervisorType.XenServer, CPU.CPUArch.amd64),
new Pair<>(Hypervisor.HypervisorType.Hyperv, CPU.CPUArch.amd64),
new Pair<>(Hypervisor.HypervisorType.LXC, CPU.CPUArch.amd64),
new Pair<>(Hypervisor.HypervisorType.Ovm3, CPU.CPUArch.amd64)
);
public static final Map<String, MetadataTemplateDetails> NewTemplateMap = new HashMap<>();
public static final Map<Hypervisor.HypervisorType, String> RouterTemplateConfigurationNames = new HashMap<>() {
{
put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
put(Hypervisor.HypervisorType.XenServer, "router.template.xenserver");
put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
put(Hypervisor.HypervisorType.Ovm3, "router.template.ovm3");
}
};
public static Map<Hypervisor.HypervisorType, Integer> hypervisorGuestOsMap = new HashMap<>() {
{
put(Hypervisor.HypervisorType.KVM, LINUX_12_ID);
put(Hypervisor.HypervisorType.XenServer, OTHER_LINUX_ID);
put(Hypervisor.HypervisorType.VMware, OTHER_LINUX_ID);
put(Hypervisor.HypervisorType.Hyperv, LINUX_12_ID);
put(Hypervisor.HypervisorType.LXC, LINUX_12_ID);
put(Hypervisor.HypervisorType.Ovm3, LINUX_12_ID);
}
};
public static final Map<Hypervisor.HypervisorType, ImageFormat> hypervisorImageFormat = new HashMap<Hypervisor.HypervisorType, ImageFormat>() {
{
put(Hypervisor.HypervisorType.KVM, ImageFormat.QCOW2);
put(Hypervisor.HypervisorType.XenServer, ImageFormat.VHD);
put(Hypervisor.HypervisorType.VMware, ImageFormat.OVA);
put(Hypervisor.HypervisorType.Hyperv, ImageFormat.VHD);
put(Hypervisor.HypervisorType.LXC, ImageFormat.QCOW2);
put(Hypervisor.HypervisorType.Ovm3, ImageFormat.RAW);
}
};
public boolean validateIfSeeded(TemplateDataStoreVO templDataStoreVO, String url, String path, String nfsVersion) {
String filePath = null;
try {
filePath = Files.createTempDirectory(TEMPORARY_SECONDARY_STORE).toString();
if (filePath == null) {
throw new CloudRuntimeException("Failed to create temporary directory to mount secondary store");
}
mountStore(url, filePath, nfsVersion);
int lastIdx = path.lastIndexOf(File.separator);
String partialDirPath = path.substring(0, lastIdx);
String templatePath = filePath + File.separator + partialDirPath;
File templateProps = new File(templatePath + "/template.properties");
if (templateProps.exists()) {
Pair<Long, Long> templateSizes = readTemplatePropertiesSizes(templatePath + "/template.properties");
updateSeededTemplateDetails(templDataStoreVO.getTemplateId(), templDataStoreVO.getDataStoreId(),
templateSizes.first(), templateSizes.second());
LOGGER.info("SystemVM Template already seeded, skipping registration");
return true;
}
LOGGER.info("SystemVM Template not seeded");
return false;
} catch (Exception e) {
LOGGER.error("Failed to verify if the Template is seeded", e);
throw new CloudRuntimeException("Failed to verify if the Template is seeded", e);
} finally {
unmountStore(filePath);
try {
Files.delete(Path.of(filePath));
} catch (IOException e) {
LOGGER.error(String.format("Failed to delete temporary directory: %s", filePath));
}
}
}
private static String getHypervisorArchLog(Hypervisor.HypervisorType hypervisorType, CPU.CPUArch arch) {
StringBuilder sb = new StringBuilder("hypervisor: ").append(hypervisorType.name());
if (Hypervisor.HypervisorType.KVM.equals(hypervisorType)) {
sb.append(", arch: ").append(arch == null ? CPU.CPUArch.amd64.getType() : arch.getType());
}
return sb.toString();
}
protected static String getHypervisorArchKey(Hypervisor.HypervisorType hypervisorType, CPU.CPUArch arch) {
if (Hypervisor.HypervisorType.KVM.equals(hypervisorType)) {
return String.format("%s-%s", hypervisorType.name().toLowerCase(),
arch == null ? CPU.CPUArch.amd64.getType() : arch.getType());
}
return hypervisorType.name().toLowerCase();
}
protected static MetadataTemplateDetails getMetadataTemplateDetails(Hypervisor.HypervisorType hypervisorType,
CPU.CPUArch arch) {
return NewTemplateMap.get(getHypervisorArchKey(hypervisorType, arch));
}
public VMTemplateVO getRegisteredTemplate(String templateName, CPU.CPUArch arch) {
return vmTemplateDao.findLatestTemplateByName(templateName, arch);
}
private static boolean isRunningInTest() {
return "true".equalsIgnoreCase(System.getProperty("test.mode"));
}
/**
* Attempts to determine the templates directory path by locating the metadata file.
* <p>
* This method checks if the application is running in a test environment by invoking
* {@code isRunningInTest()}. If so, it immediately returns the {@code RELATIVE_TEMPLATE_PATH}.
* </p>
* <p>
* Otherwise, it creates a list of candidate paths (typically including both relative and absolute
* template paths) and iterates through them. For each candidate, it constructs the metadata file
* path by appending {@code METADATA_FILE_NAME} to {@code RELATIVE_TEMPLATE_PATH} (note: the candidate
* path is not used in the file path construction in this implementation) and checks if that file exists.
* If the metadata file exists, the candidate path is returned.
* </p>
* <p>
* If none of the candidate paths contain the metadata file, the method logs an error and throws a
* {@link CloudRuntimeException}.
* </p>
*
* @return the path to the templates directory if the metadata file is found, or {@code RELATIVE_TEMPLATE_PATH}
* when running in a test environment.
* @throws CloudRuntimeException if the metadata file cannot be located in any of the candidate paths.
*/
private static String fetchTemplatesPath() {
if (isRunningInTest()) {
return RELATIVE_TEMPLATE_PATH;
}
List<String> paths = Arrays.asList(RELATIVE_TEMPLATE_PATH, ABSOLUTE_TEMPLATE_PATH);
for (String path : paths) {
String filePath = path + METADATA_FILE_NAME;
LOGGER.debug("Looking for file [ {} ] in the classpath.", filePath);
File metaFile = new File(filePath);
if (metaFile.exists()) {
return path;
}
}
String errMsg = String.format("Unable to locate metadata file in your setup at %s", StringUtils.join(paths));
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
private List<Long> getEligibleZoneIds() {
List<Long> zoneIds = new ArrayList<>();
List<ImageStoreVO> stores = imageStoreDao.findByProtocol("nfs");
for (ImageStoreVO store : stores) {
if (!zoneIds.contains(store.getDataCenterId())) {
zoneIds.add(store.getDataCenterId());
}
}
return zoneIds;
}
protected Pair<String, Long> getNfsStoreInZone(Long zoneId) {
ImageStoreVO storeVO = imageStoreDao.findOneByZoneAndProtocol(zoneId, "nfs");
if (storeVO == null) {
String errMsg = String.format("Failed to fetch NFS store in zone = %s for SystemVM Template registration",
zoneId);
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
String url = storeVO.getUrl();
Long storeId = storeVO.getId();
return new Pair<>(url, storeId);
}
public static void mountStore(String storeUrl, String path, String nfsVersion) {
try {
if (storeUrl == null) {
return;
}
URI uri = new URI(UriUtils.encodeURIComponent(storeUrl));
String host = uri.getHost();
String mountPath = uri.getPath();
Script.runSimpleBashScript(getMountCommand(nfsVersion, host + ":" + mountPath, path));
} catch (Exception e) {
String msg = "NFS Store URL is not in the correct format";
LOGGER.error(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
private VMTemplateVO createTemplateObjectInDB(SystemVMTemplateDetails details) {
Long templateId = vmTemplateDao.getNextInSequence(Long.class, "id");
VMTemplateVO template = new VMTemplateVO();
template.setUuid(details.getUuid());
template.setUniqueName(String.format("routing-%s" , String.valueOf(templateId)));
template.setName(details.getName());
template.setPublicTemplate(false);
template.setFeatured(false);
template.setTemplateType(Storage.TemplateType.SYSTEM);
template.setRequiresHvm(true);
template.setBits(64);
template.setAccountId(Account.ACCOUNT_ID_SYSTEM);
template.setUrl(details.getUrl());
template.setChecksum(details.getChecksum());
template.setEnablePassword(false);
template.setDisplayText(details.getName());
template.setFormat(details.getFormat());
template.setGuestOSId(details.getGuestOsId());
template.setCrossZones(true);
template.setHypervisorType(details.getHypervisorType());
template.setArch(details.getArch());
template.setState(VirtualMachineTemplate.State.Inactive);
template.setDeployAsIs(false);
template = vmTemplateDao.persist(template);
return template;
}
private VMTemplateZoneVO createOrUpdateTemplateZoneEntry(long zoneId, long templateId) {
VMTemplateZoneVO templateZoneVO = vmTemplateZoneDao.findByZoneTemplate(zoneId, templateId);
if (templateZoneVO == null) {
templateZoneVO = new VMTemplateZoneVO(zoneId, templateId, new java.util.Date());
templateZoneVO = vmTemplateZoneDao.persist(templateZoneVO);
} else {
templateZoneVO.setLastUpdated(new java.util.Date());
if (!vmTemplateZoneDao.update(templateZoneVO.getId(), templateZoneVO)) {
templateZoneVO = null;
}
}
return templateZoneVO;
}
private void createCrossZonesTemplateZoneRefEntries(Long templateId) {
List<DataCenterVO> dcs = dataCenterDao.listAll();
for (DataCenterVO dc : dcs) {
VMTemplateZoneVO templateZoneVO = createOrUpdateTemplateZoneEntry(dc.getId(), templateId);
if (templateZoneVO == null) {
throw new CloudRuntimeException(String.format("Failed to create template_zone_ref record for the systemVM Template (id: %s) and zone: %s", templateId, dc));
}
}
}
private void createTemplateStoreRefEntry(SystemVMTemplateDetails details) {
TemplateDataStoreVO templateDataStoreVO = new TemplateDataStoreVO(details.storeId, details.getId(), details.getCreated(), 0,
VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, null, details.getInstallPath(), details.getUrl());
templateDataStoreVO.setDataStoreRole(DataStoreRole.Image);
templateDataStoreVO = templateDataStoreDao.persist(templateDataStoreVO);
if (templateDataStoreVO == null) {
throw new CloudRuntimeException(String.format("Failed to create template_store_ref record for the systemVM Template for hypervisor: %s", details.getHypervisorType().name()));
}
}
public void updateTemplateDetails(SystemVMTemplateDetails details) {
VMTemplateVO template = vmTemplateDao.findById(details.getId());
template.setSize(details.getSize());
template.setState(VirtualMachineTemplate.State.Active);
vmTemplateDao.update(template.getId(), template);
TemplateDataStoreVO templateDataStoreVO = templateDataStoreDao.findByStoreTemplate(details.getStoreId(), template.getId());
templateDataStoreVO.setSize(details.getSize());
templateDataStoreVO.setPhysicalSize(details.getPhysicalSize());
templateDataStoreVO.setDownloadPercent(100);
templateDataStoreVO.setDownloadState(VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
templateDataStoreVO.setLastUpdated(details.getUpdated());
templateDataStoreVO.setState(ObjectInDataStoreStateMachine.State.Ready);
boolean updated = templateDataStoreDao.update(templateDataStoreVO.getId(), templateDataStoreVO);
if (!updated) {
throw new CloudRuntimeException("Failed to update template_store_ref entry for registered systemVM Template");
}
}
public void updateSeededTemplateDetails(long templateId, long storeId, long size, long physicalSize) {
VMTemplateVO template = vmTemplateDao.findById(templateId);
template.setSize(size);
vmTemplateDao.update(template.getId(), template);
TemplateDataStoreVO templateDataStoreVO = templateDataStoreDao.findByStoreTemplate(storeId, template.getId());
templateDataStoreVO.setSize(size);
templateDataStoreVO.setPhysicalSize(physicalSize);
templateDataStoreVO.setLastUpdated(new Date(DateUtil.currentGMTTime().getTime()));
boolean updated = templateDataStoreDao.update(templateDataStoreVO.getId(), templateDataStoreVO);
if (!updated) {
throw new CloudRuntimeException("Failed to update template_store_ref entry for seeded systemVM template");
}
}
public void updateSystemVMEntries(Long templateId, Hypervisor.HypervisorType hypervisorType) {
vmInstanceDao.updateSystemVmTemplateId(templateId, hypervisorType);
}
private void updateSystemVmTemplateGuestOsId() {
String systemVmGuestOsName = "Debian GNU/Linux 12 (64-bit)"; // default
try {
GuestOSVO guestOS = guestOSDao.findOneByDisplayName(systemVmGuestOsName);
if (guestOS != null) {
LOGGER.debug("Updating SystemVM Template Guest OS [{}] id", systemVmGuestOsName);
SystemVmTemplateRegistration.LINUX_12_ID = Math.toIntExact(guestOS.getId());
hypervisorGuestOsMap.put(Hypervisor.HypervisorType.KVM, LINUX_12_ID);
hypervisorGuestOsMap.put(Hypervisor.HypervisorType.Hyperv, LINUX_12_ID);
hypervisorGuestOsMap.put(Hypervisor.HypervisorType.LXC, LINUX_12_ID);
hypervisorGuestOsMap.put(Hypervisor.HypervisorType.Ovm3, LINUX_12_ID);
}
} catch (Exception e) {
LOGGER.warn("Couldn't update SystemVM Template Guest OS id, due to {}", e.getMessage());
}
}
public void updateConfigurationParams(Map<String, String> configParams) {
for (Map.Entry<String, String> config : configParams.entrySet()) {
boolean updated = configurationDao.update(config.getKey(), config.getValue());
if (!updated) {
throw new CloudRuntimeException(String.format("Failed to update configuration parameter %s", config.getKey()));
}
}
}
private static Pair<Long, Long> readTemplatePropertiesSizes(String path) {
File tmpFile = new File(path);
Long size = null;
Long physicalSize = 0L;
try (FileReader fr = new FileReader(tmpFile); BufferedReader brf = new BufferedReader(fr);) {
String line = null;
while ((line = brf.readLine()) != null) {
if (line.startsWith("size=")) {
physicalSize = Long.parseLong(line.split("=")[1]);
} else if (line.startsWith("virtualsize=")) {
size = Long.parseLong(line.split("=")[1]);
}
if (size == null) {
size = physicalSize;
}
}
} catch (IOException ex) {
LOGGER.warn("Failed to read from template.properties", ex);
}
return new Pair<>(size, physicalSize);
}
public static void readTemplateProperties(String path, SystemVMTemplateDetails details) {
Pair<Long, Long> templateSizes = readTemplatePropertiesSizes(path);
details.setSize(templateSizes.first());
details.setPhysicalSize(templateSizes.second());
}
private void updateTemplateTablesOnFailure(long templateId) {
VMTemplateVO template = vmTemplateDao.createForUpdate(templateId);
template.setState(VirtualMachineTemplate.State.Inactive);
vmTemplateDao.update(template.getId(), template);
vmTemplateDao.remove(templateId);
TemplateDataStoreVO templateDataStoreVO = templateDataStoreDao.findByTemplate(template.getId(), DataStoreRole.Image);
templateDataStoreDao.remove(templateDataStoreVO.getId());
}
public static void unmountStore(String filePath) {
try {
LOGGER.info("Unmounting store");
String umountCmd = String.format(UMOUNT_COMMAND, filePath);
Script.runSimpleBashScript(umountCmd);
try {
Files.deleteIfExists(Paths.get(filePath));
} catch (IOException e) {
LOGGER.error(String.format("Failed to cleanup mounted store at: %s", filePath), e);
}
} catch (Exception e) {
String msg = String.format("Failed to unmount store mounted at %s", filePath);
LOGGER.error(msg, e);
throw new CloudRuntimeException(msg, e);
}
}
private void setupTemplate(String templateName, Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch,
String destTempFolder) throws CloudRuntimeException {
String setupTmpltScript = Script.findScript(storageScriptsDir, "setup-sysvm-tmplt");
if (setupTmpltScript == null) {
throw new CloudRuntimeException("Unable to find the createtmplt.sh");
}
Script scr = new Script(setupTmpltScript, SCRIPT_TIMEOUT, LOGGER);
scr.add("-u", templateName);
MetadataTemplateDetails templateDetails = NewTemplateMap.get(getHypervisorArchKey(hypervisor, arch));
String filePath = StringUtils.isNotBlank(templateDetails.getDownloadedFilePath()) ?
templateDetails.getDownloadedFilePath() :
templateDetails.getDefaultFilePath();
scr.add("-f", filePath);
scr.add("-h", hypervisor.name().toLowerCase(Locale.ROOT));
scr.add("-d", destTempFolder);
String result = scr.execute();
if (result != null) {
String errMsg = String.format("Failed to create Template: %s ", result);
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
}
private Long performTemplateRegistrationOperations(Hypervisor.HypervisorType hypervisor,
String name, CPU.CPUArch arch, String url, String checksum, ImageFormat format, long guestOsId,
Long storeId, Long templateId, String filePath, TemplateDataStoreVO templateDataStoreVO) {
String templateName = UUID.randomUUID().toString();
Date created = new Date(DateUtil.currentGMTTime().getTime());
SystemVMTemplateDetails details = new SystemVMTemplateDetails(templateName, name, created,
url, checksum, format, (int) guestOsId, hypervisor, arch, storeId);
if (templateId == null) {
VMTemplateVO template = createTemplateObjectInDB(details);
if (template == null) {
throw new CloudRuntimeException(String.format("Failed to register Template for hypervisor: %s", hypervisor.name()));
}
templateId = template.getId();
}
createCrossZonesTemplateZoneRefEntries(templateId);
details.setId(templateId);
String destTempFolderName = String.valueOf(templateId);
String destTempFolder = filePath + PARTIAL_TEMPLATE_FOLDER + destTempFolderName;
details.setInstallPath(PARTIAL_TEMPLATE_FOLDER + destTempFolderName + File.separator + templateName + "." + hypervisorImageFormat.get(hypervisor).getFileExtension());
if (templateDataStoreVO == null) {
createTemplateStoreRefEntry(details);
}
setupTemplate(templateName, hypervisor, arch, destTempFolder);
readTemplateProperties(destTempFolder + "/template.properties", details);
details.setUpdated(new Date(DateUtil.currentGMTTime().getTime()));
updateTemplateDetails(details);
return templateId;
}
public void registerTemplate(Hypervisor.HypervisorType hypervisor, String name, Long storeId,
VMTemplateVO templateVO, TemplateDataStoreVO templateDataStoreVO, String filePath) {
try {
performTemplateRegistrationOperations(hypervisor, name, templateVO.getArch(), templateVO.getUrl(),
templateVO.getChecksum(), templateVO.getFormat(), templateVO.getGuestOSId(), storeId,
templateVO.getId(), filePath, templateDataStoreVO);
} catch (Exception e) {
String errMsg = String.format("Failed to register Template for hypervisor: %s", hypervisor);
LOGGER.error(errMsg, e);
updateTemplateTablesOnFailure(templateVO.getId());
cleanupStore(templateVO.getId(), filePath);
throw new CloudRuntimeException(errMsg, e);
}
}
public void registerTemplateForNonExistingEntries(Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch,
String name, Pair<String, Long> storeUrlAndId, String filePath) {
Long templateId = null;
try {
MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisor, arch);
templateId = performTemplateRegistrationOperations(hypervisor, name,
templateDetails.getArch(), templateDetails.getUrl(),
templateDetails.getChecksum(), hypervisorImageFormat.get(hypervisor),
hypervisorGuestOsMap.get(hypervisor), storeUrlAndId.second(), null, filePath, null);
Map<String, String> configParams = new HashMap<>();
configParams.put(RouterTemplateConfigurationNames.get(hypervisor), templateDetails.getName());
configParams.put("minreq.sysvmtemplate.version", getSystemVmTemplateVersion());
updateConfigurationParams(configParams);
updateSystemVMEntries(templateId, hypervisor);
} catch (Exception e) {
String errMsg = String.format("Failed to register Template for hypervisor: %s", hypervisor);
LOGGER.error(errMsg, e);
if (templateId != null) {
updateTemplateTablesOnFailure(templateId);
cleanupStore(templateId, filePath);
}
throw new CloudRuntimeException(errMsg, e);
}
}
protected void validateTemplateFileForHypervisorAndArch(Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch) {
MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisor, arch);
File templateFile = getTemplateFile(templateDetails);
if (templateFile == null) {
throw new CloudRuntimeException("Failed to find local template file");
}
if (isTemplateFileChecksumDifferent(templateDetails, templateFile)) {
throw new CloudRuntimeException("Checksum failed for local template file");
}
}
public void validateAndRegisterTemplate(Hypervisor.HypervisorType hypervisor, String name, Long storeId,
VMTemplateVO templateVO, TemplateDataStoreVO templateDataStoreVO, String filePath) {
validateTemplateFileForHypervisorAndArch(hypervisor, templateVO.getArch());
registerTemplate(hypervisor, name, storeId, templateVO, templateDataStoreVO, filePath);
}
public void validateAndRegisterTemplateForNonExistingEntries(Hypervisor.HypervisorType hypervisor,
CPU.CPUArch arch, String name, Pair<String, Long> storeUrlAndId, String filePath) {
validateTemplateFileForHypervisorAndArch(hypervisor, arch);
registerTemplateForNonExistingEntries(hypervisor, arch, name, storeUrlAndId, filePath);
}
protected static String getMetadataFilePath() {
return METADATA_FILE;
}
/**
* This method parses the metadata file consisting of the systemVM templates information
* @return the version of the systemvm template that is to be used. This is done in order
* to fallback on the latest available version of the systemVM template when there doesn't
* exist a template corresponding to the current code version.
*/
public static String parseMetadataFile() {
String metadataFilePath = getMetadataFilePath();
String errMsg = String.format("Failed to parse systemVM Template metadata file: %s", metadataFilePath);
final Ini ini = new Ini();
try (FileReader reader = new FileReader(metadataFilePath)) {
ini.load(reader);
} catch (IOException e) {
LOGGER.error(errMsg, e);
throw new CloudRuntimeException(errMsg, e);
}
if (!ini.containsKey("default")) {
errMsg = String.format("%s as unable to default section", errMsg);
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
for (Pair<Hypervisor.HypervisorType, CPU.CPUArch> hypervisorType : hypervisorList) {
String key = getHypervisorArchKey(hypervisorType.first(), hypervisorType.second());
Ini.Section section = ini.get(key);
if (section == null) {
LOGGER.error("Failed to find details for {} in template metadata file: {}",
key, metadataFilePath);
continue;
}
NewTemplateMap.put(key, new MetadataTemplateDetails(
hypervisorType.first(),
section.get("templatename"),
section.get("filename"),
section.get("downloadurl"),
section.get("checksum"),
hypervisorType.second(),
section.get("guestos")));
}
Ini.Section defaultSection = ini.get("default");
return defaultSection.get("version").trim();
}
private static void cleanupStore(Long templateId, String filePath) {
String destTempFolder = filePath + PARTIAL_TEMPLATE_FOLDER + String.valueOf(templateId);
try {
Files.deleteIfExists(Paths.get(destTempFolder));
} catch (IOException e) {
LOGGER.error(String.format("Failed to cleanup mounted store at: %s", filePath), e);
}
}
protected File getTemplateFile(MetadataTemplateDetails templateDetails) {
File templateFile = new File(templateDetails.getDefaultFilePath());
if (templateFile.exists()) {
return templateFile;
}
LOGGER.debug("{} is not present", templateFile.getAbsolutePath());
if (DOWNLOADABLE_TEMPLATE_ARCH_TYPES.contains(templateDetails.getArch()) &&
StringUtils.isNotBlank(templateDetails.getUrl())) {
LOGGER.debug("Downloading the template file {} for {}",
templateDetails.getUrl(), templateDetails.getHypervisorArchLog());
Path path = Path.of(TEMPLATES_PATH);
if (!Files.isWritable(path)) {
templateFile = new File(tempDownloadDir, templateDetails.getFilename());
}
if (!templateFile.exists() &&
!HttpUtils.downloadFileWithProgress(templateDetails.getUrl(), templateFile.getAbsolutePath(),
LOGGER)) {
return null;
}
templateDetails.setDownloadedFilePath(templateFile.getAbsolutePath());
}
return templateFile;
}
protected boolean isTemplateFileChecksumDifferent(MetadataTemplateDetails templateDetails, File templateFile) {
String templateChecksum = DigestHelper.calculateChecksum(templateFile);
if (!templateChecksum.equals(templateDetails.getChecksum())) {
LOGGER.error("Checksum {} for file {} does not match checksum {} from metadata",
templateChecksum, templateFile, templateDetails.getChecksum());
return true;
}
return false;
}
protected void validateTemplates(List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> hypervisorsArchInUse) {
boolean templatesFound = true;
for (Pair<Hypervisor.HypervisorType, CPU.CPUArch> hypervisorArch : hypervisorsArchInUse) {
MetadataTemplateDetails matchedTemplate = getMetadataTemplateDetails(hypervisorArch.first(),
hypervisorArch.second());
if (matchedTemplate == null) {
templatesFound = false;
break;
}
File tempFile = getTemplateFile(matchedTemplate);
if (tempFile == null) {
LOGGER.warn("Failed to download template for {}, moving ahead",
matchedTemplate.getHypervisorArchLog());
continue;
}
if (isTemplateFileChecksumDifferent(matchedTemplate, tempFile)) {
templatesFound = false;
break;
}
}
if (!templatesFound) {
String errMsg = "SystemVM Template not found. Cannot upgrade system VMs";
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
}
protected void registerTemplatesForZone(long zoneId, String filePath) {
Pair<String, Long> storeUrlAndId = getNfsStoreInZone(zoneId);
String nfsVersion = getNfsVersion(storeUrlAndId.second());
mountStore(storeUrlAndId.first(), filePath, nfsVersion);
List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> hypervisorArchList =
clusterDao.listDistinctHypervisorsArchAcrossClusters(zoneId);
for (Pair<Hypervisor.HypervisorType, CPU.CPUArch> hypervisorArch : hypervisorArchList) {
Hypervisor.HypervisorType hypervisorType = hypervisorArch.first();
MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisorType,
hypervisorArch.second());
if (templateDetails == null) {
continue;
}
VMTemplateVO templateVO = getRegisteredTemplate(templateDetails.getName(), templateDetails.getArch());
if (templateVO != null) {
TemplateDataStoreVO templateDataStoreVO =
templateDataStoreDao.findByStoreTemplate(storeUrlAndId.second(), templateVO.getId());
if (templateDataStoreVO != null) {
String installPath = templateDataStoreVO.getInstallPath();
if (validateIfSeeded(templateDataStoreVO, storeUrlAndId.first(), installPath, nfsVersion)) {
continue;
}
}
registerTemplate(hypervisorType, templateDetails.getName(), storeUrlAndId.second(), templateVO,
templateDataStoreVO, filePath);
updateRegisteredTemplateDetails(templateVO.getId(), templateDetails);
continue;
}
registerTemplateForNonExistingEntries(hypervisorType, templateDetails.getArch(), templateDetails.getName(),
storeUrlAndId, filePath);
}
}
public void registerTemplates(List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> hypervisorsArchInUse) {
GlobalLock lock = GlobalLock.getInternLock("UpgradeDatabase-Lock");
try {
LOGGER.info("Grabbing lock to register Templates.");
if (!lock.lock(LOCK_WAIT_TIMEOUT)) {
throw new CloudRuntimeException("Unable to acquire lock to register SystemVM Template.");
}
try {
validateTemplates(hypervisorsArchInUse);
// Perform Registration if templates not already registered
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
List<Long> zoneIds = getEligibleZoneIds();
for (Long zoneId : zoneIds) {
String filePath = null;
try {
filePath = Files.createTempDirectory(TEMPORARY_SECONDARY_STORE).toString();
if (filePath == null) {
throw new CloudRuntimeException("Failed to create temporary file path to mount the store");
}
registerTemplatesForZone(zoneId, filePath);
unmountStore(filePath);
} catch (Exception e) {
unmountStore(filePath);
throw new CloudRuntimeException("Failed to register SystemVM Template. Upgrade failed");
}
}
}
});
} catch (Exception e) {
throw new CloudRuntimeException("Failed to register SystemVM Template. Upgrade failed");
}
} finally {
lock.unlock();
lock.releaseRef();
}
}
private void updateRegisteredTemplateDetails(Long templateId, MetadataTemplateDetails templateDetails) {
VMTemplateVO templateVO = vmTemplateDao.findById(templateId);
templateVO.setTemplateType(Storage.TemplateType.SYSTEM);
GuestOSVO guestOS = guestOSDao.findOneByDisplayName(templateDetails.getGuestOs());
if (guestOS != null) {
templateVO.setGuestOSId(guestOS.getId());
}
boolean updated = vmTemplateDao.update(templateVO.getId(), templateVO);
if (!updated) {
String errMsg = String.format("updateSystemVmTemplates:Exception while updating Template with id %s to be marked as 'system'", templateId);
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
Hypervisor.HypervisorType hypervisorType = templateDetails.getHypervisorType();