-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathSystemVmTemplateRegistration.java
More file actions
1376 lines (1272 loc) · 63.1 KB
/
SystemVmTemplateRegistration.java
File metadata and controls
1376 lines (1272 loc) · 63.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.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.cloudstack.utils.server.ServerPropertiesUtil;
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.dc.dao.DataCenterDetailsDao;
import com.cloud.dc.dao.DataCenterDetailsDaoImpl;
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);
protected static final String STORAGE_SCRIPTS_DIR = "scripts/storage/secondary";
private static final Integer OTHER_LINUX_ID = 99;
protected static Integer LINUX_12_ID = 363;
private static final Integer SCRIPT_TIMEOUT = 1800000;
private static final Integer LOCK_WAIT_TIMEOUT = 1200;
protected static final String TEMPLATE_DOWNLOAD_URL_KEY = "downloadurl";
protected static final String TEMPLATES_DOWNLOAD_REPOSITORY_KEY = "downloadrepository";
protected static final String TEMPLATES_CUSTOM_DOWNLOAD_REPOSITORY_KEY = "system.vm.templates.download.repository";
protected static final List<CPU.CPUArch> DOWNLOADABLE_TEMPLATE_ARCH_TYPES = Arrays.asList(
CPU.CPUArch.amd64,
CPU.CPUArch.arm64
);
protected static final String MINIMUM_SYSTEM_VM_VERSION_KEY = "minreq.sysvmtemplate.version";
protected static final String DEFAULT_SYSTEM_VM_GUEST_OS_NAME = "Debian GNU/Linux 12 (64-bit)";
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
DataCenterDetailsDao dataCenterDetailsDao;
@Inject
GuestOSDao guestOSDao;
private String systemVmTemplateVersion;
private final File tempDownloadDir;
public SystemVmTemplateRegistration() {
dataCenterDao = new DataCenterDaoImpl();
dataCenterDetailsDao = new DataCenterDetailsDaoImpl();
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;
}
protected 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;
}
}
protected static final List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> AVAILABLE_SYSTEM_TEMPLATES_HYPERVISOR_ARCH_LIST = 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)
);
protected static final List<MetadataTemplateDetails> METADATA_TEMPLATE_LIST = new ArrayList<>();
protected static final Map<Hypervisor.HypervisorType, String> ROUTER_TEMPLATE_CONFIGURATION_NAMES = 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");
}
};
protected static final Map<Hypervisor.HypervisorType, ImageFormat> HYPERVISOR_IMAGE_FORMAT_MAP = new HashMap<>() {
{
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);
}
};
protected 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);
}
};
private static boolean isRunningInTest() {
return "true".equalsIgnoreCase(System.getProperty("test.mode"));
}
private static String getHypervisorArchLog(Hypervisor.HypervisorType hypervisorType, CPU.CPUArch arch) {
StringBuilder sb = new StringBuilder("hypervisor: ").append(hypervisorType.name());
sb.append(", arch: ").append(arch == null ? CPU.CPUArch.amd64.getType() : arch.getType());
return sb.toString();
}
/**
* 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);
}
protected 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("Failed to cleanup mounted store at: {}", filePath, e);
}
}
protected 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);
}
protected static MetadataTemplateDetails getMetadataTemplateDetails(Hypervisor.HypervisorType hypervisorType,
CPU.CPUArch arch) {
return METADATA_TEMPLATE_LIST
.stream()
.filter(x -> Objects.equals(x.getHypervisorType(), hypervisorType) &&
Objects.equals(x.getArch(), arch))
.findFirst()
.orElse(null);
}
protected static String getMetadataFilePath() {
return METADATA_FILE;
}
protected static Ini.Section getMetadataSectionForHypervisorAndArch(Ini ini,
Hypervisor.HypervisorType hypervisorType, CPU.CPUArch arch) {
String key = String.format("%s-%s", hypervisorType.name().toLowerCase(),
arch.getType().toLowerCase());
Ini.Section section = ini.get(key);
if (section == null && !Hypervisor.HypervisorType.KVM.equals(hypervisorType)) {
key = String.format("%s", hypervisorType.name().toLowerCase());
section = ini.get(key);
}
return section;
}
protected 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);
}
/**
* This method parses the metadata file consisting of the system VM Templates information
* @return the version of the system VM Template that is to be used. This is done in order
* to fallback on the latest available version of the system VM 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 system VM 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);
}
Ini.Section defaultSection = ini.get("default");
String defaultDownloadRepository = defaultSection.get(TEMPLATES_DOWNLOAD_REPOSITORY_KEY);
String customDownloadRepository = ServerPropertiesUtil.getProperty(TEMPLATES_CUSTOM_DOWNLOAD_REPOSITORY_KEY);
boolean updateCustomDownloadRepository = StringUtils.isNotBlank(customDownloadRepository) &&
StringUtils.isNotBlank(defaultDownloadRepository);
for (Pair<Hypervisor.HypervisorType, CPU.CPUArch> hypervisorTypeArchPair : AVAILABLE_SYSTEM_TEMPLATES_HYPERVISOR_ARCH_LIST) {
String key = String.format("%s-%s", hypervisorTypeArchPair.first().name().toLowerCase(),
hypervisorTypeArchPair.second().getType().toLowerCase());
Ini.Section section = getMetadataSectionForHypervisorAndArch(ini, hypervisorTypeArchPair.first(),
hypervisorTypeArchPair.second());
if (section == null) {
LOGGER.error("Failed to find details for {} in template metadata file: {}",
getHypervisorArchLog(hypervisorTypeArchPair.first(), hypervisorTypeArchPair.second()),
metadataFilePath);
continue;
}
String url = section.get(TEMPLATE_DOWNLOAD_URL_KEY);
if (StringUtils.isNotBlank(url) && updateCustomDownloadRepository) {
url = url.replaceFirst(defaultDownloadRepository.trim(),
customDownloadRepository.trim());
LOGGER.debug("Updated download URL for {} using custom repository to {}", key, url);
}
METADATA_TEMPLATE_LIST.add(new MetadataTemplateDetails(
hypervisorTypeArchPair.first(),
section.get("templatename"),
section.get("filename"),
url,
section.get("checksum"),
hypervisorTypeArchPair.second(),
section.get("guestos")));
}
return defaultSection.get("version").trim();
}
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);
}
}
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);
}
}
protected File getTempDownloadDir() {
return tempDownloadDir;
}
protected void readTemplateProperties(String path, SystemVMTemplateDetails details) {
Pair<Long, Long> templateSizes = readTemplatePropertiesSizes(path);
details.setSize(templateSizes.first());
details.setPhysicalSize(templateSizes.second());
}
protected 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);
}
protected String getSystemVmTemplateVersion() {
if (StringUtils.isEmpty(systemVmTemplateVersion)) {
return String.format("%s.%s", CS_MAJOR_VERSION, CS_TINY_VERSION);
}
return systemVmTemplateVersion;
}
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(DigestHelper.prependAlgorithm(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;
}
protected 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;
}
protected 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 record for the system " +
"VM Template (ID : %d) and zone: %s", templateId, dc));
}
}
}
protected void createTemplateStoreRefEntry(SystemVMTemplateDetails details) {
TemplateDataStoreVO templateDataStoreVO = new TemplateDataStoreVO(details.getStoreId(), 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 record for the system VM " +
"template (ID : %d) and store (ID: %d)", details.getId(), details.getStoreId()));
}
}
protected 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 record for registered system VM Template");
}
}
protected 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 record for seeded system VM Template");
}
}
protected void updateSystemVMEntries(Long templateId, Hypervisor.HypervisorType hypervisorType) {
vmInstanceDao.updateSystemVmTemplateId(templateId, hypervisorType);
}
protected void updateHypervisorGuestOsMap() {
try {
GuestOSVO guestOS = guestOSDao.findOneByDisplayName(DEFAULT_SYSTEM_VM_GUEST_OS_NAME);
if (guestOS == null) {
LOGGER.warn("Couldn't find Guest OS by name [{}] to update system VM Template guest OS ID",
DEFAULT_SYSTEM_VM_GUEST_OS_NAME);
return;
}
LOGGER.debug("Updating system VM Template guest OS [{}] ID", DEFAULT_SYSTEM_VM_GUEST_OS_NAME);
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 System VM template guest OS ID, due to {}", e.getMessage());
}
}
protected void updateConfigurationParams(Hypervisor.HypervisorType hypervisorType, String templateName, Long zoneId) {
String configName = ROUTER_TEMPLATE_CONFIGURATION_NAMES.get(hypervisorType);
boolean updated = configurationDao.update(configName, templateName);
if (!updated) {
throw new CloudRuntimeException(String.format("Failed to update configuration parameter %s", configName));
}
if (zoneId != null) {
dataCenterDetailsDao.removeDetail(zoneId, configName);
}
updated = configurationDao.update(MINIMUM_SYSTEM_VM_VERSION_KEY, getSystemVmTemplateVersion());
if (!updated) {
throw new CloudRuntimeException(String.format("Failed to update configuration parameter %s", configName));
}
if (zoneId != null) {
dataCenterDetailsDao.removeDetail(zoneId, MINIMUM_SYSTEM_VM_VERSION_KEY);
}
}
protected void updateTemplateEntriesOnFailure(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);
if (templateDataStoreVO == null) {
return;
}
templateDataStoreDao.remove(templateDataStoreVO.getId());
}
protected void setupTemplateOnStore(String templateName, MetadataTemplateDetails templateDetails,
String destTempFolder) throws CloudRuntimeException {
String setupTmpltScript = Script.findScript(STORAGE_SCRIPTS_DIR, "setup-sysvm-tmplt");
if (setupTmpltScript == null) {
throw new CloudRuntimeException("Unable to find the setup-sysvm-tmplt script");
}
Script scr = new Script(setupTmpltScript, SCRIPT_TIMEOUT, LOGGER);
scr.add("-u", templateName);
String filePath = StringUtils.isNotBlank(templateDetails.getDownloadedFilePath()) ?
templateDetails.getDownloadedFilePath() :
templateDetails.getDefaultFilePath();
scr.add("-f", filePath);
scr.add("-h", templateDetails.getHypervisorType().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);
}
}
/**
* Register or update a system VM Template record and seed it on the target store.
*
* @param name display name of the template
* @param templateDetails metadata for the template
* @param url download URL of the template
* @param checksum expected checksum of the template file
* @param format image format of the template
* @param guestOsId guest OS id
* @param storeId target image store id
* @param templateId existing template id if present, otherwise {@code null}
* @param filePath temporary mount path for the store
* @param templateDataStoreVO existing template-store mapping; may be {@code null}
* @return the id of the template that was created or updated
*/
protected Long performTemplateRegistrationOperations(String name, MetadataTemplateDetails templateDetails,
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, templateDetails.getHypervisorType(), templateDetails.getArch(), storeId);
if (templateId == null) {
VMTemplateVO template = createTemplateObjectInDB(details);
if (template == null) {
throw new CloudRuntimeException(String.format("Failed to register Template for hypervisor: %s",
templateDetails.getHypervisorType().name()));
}
templateId = template.getId();
}
createCrossZonesTemplateZoneRefEntries(templateId);
details.setId(templateId);
String destTempFolderName = String.valueOf(templateId);
String destTempFolder = filePath + PARTIAL_TEMPLATE_FOLDER + destTempFolderName;
details.setInstallPath(String.format("%s%s%s%s.%s", PARTIAL_TEMPLATE_FOLDER, destTempFolderName,
File.separator, templateName,
HYPERVISOR_IMAGE_FORMAT_MAP.get(templateDetails.getHypervisorType()).getFileExtension()));
if (templateDataStoreVO == null) {
createTemplateStoreRefEntry(details);
}
setupTemplateOnStore(templateName, templateDetails, destTempFolder);
readTemplateProperties(destTempFolder + "/template.properties", details);
details.setUpdated(new Date(DateUtil.currentGMTTime().getTime()));
updateTemplateDetails(details);
return templateId;
}
/**
* Add an existing system VM Template to a secondary image store and update related DB entries.
*
* @param templateVO the existing VM template (must not be null)
* @param templateDetails the metadata details of the template to be added
* @param templateDataStoreVO optional existing template-store mapping; may be null
* @param zoneId zone id where the operation is performed
* @param storeId target image store id
* @param filePath temporary mount path for the store
* @throws CloudRuntimeException on failure; the method attempts rollback/cleanup
*/
protected void addExistingTemplateToStore(VMTemplateVO templateVO, MetadataTemplateDetails templateDetails,
TemplateDataStoreVO templateDataStoreVO, long zoneId, Long storeId, String filePath) {
try {
performTemplateRegistrationOperations(templateVO.getName(), templateDetails, templateVO.getUrl(),
templateVO.getChecksum(), templateVO.getFormat(), templateVO.getGuestOSId(), storeId,
templateVO.getId(), filePath, templateDataStoreVO);
} catch (Exception e) {
String errMsg = String.format("Failed to add %s to store ID: %d, zone ID: %d", templateVO, storeId, zoneId);
LOGGER.error(errMsg, e);
cleanupStore(templateVO.getId(), filePath);
throw new CloudRuntimeException(errMsg, e);
}
}
/**
* Registers a new system VM Template for the given hypervisor/arch when no existing template is present.
*
* @param name the name of the new template
* @param templateDetails the metadata details of the template to be registered
* @param zoneId the zone id for which the new template should be seeded
* @param storeId the store id on which the new template will be seeded
* @param filePath temporary mount path for the store
* @throws CloudRuntimeException on failure; the method attempts rollback/cleanup
*/
protected void registerNewTemplate(String name, MetadataTemplateDetails templateDetails, long zoneId, Long storeId,
String filePath) {
Long templateId = null;
Hypervisor.HypervisorType hypervisor = templateDetails.getHypervisorType();
try {
templateId = performTemplateRegistrationOperations(name, templateDetails, templateDetails.getUrl(),
templateDetails.getChecksum(), HYPERVISOR_IMAGE_FORMAT_MAP.get(hypervisor),
hypervisorGuestOsMap.get(hypervisor), storeId, null, filePath, null);
updateConfigurationParams(hypervisor, name, zoneId);
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) {
updateTemplateEntriesOnFailure(templateId);
cleanupStore(templateId, filePath);
}
throw new CloudRuntimeException(errMsg, e);
}
}
/**
* Validate presence and integrity of metadata and local template file for the given hypervisor/arch.
*
* @param hypervisor target hypervisor type
* @param arch target CPU architecture
* @return validated MetadataTemplateDetails
* @throws CloudRuntimeException if template is not available, missing, or checksum validation fails
*/
protected MetadataTemplateDetails getValidatedTemplateDetailsForHypervisorAndArch(
Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch) {
if (!AVAILABLE_SYSTEM_TEMPLATES_HYPERVISOR_ARCH_LIST.contains(new Pair<>(hypervisor, arch))) {
throw new CloudRuntimeException("No system VM Template available for the given hypervisor and arch");
}
MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisor, arch);
if (templateDetails == null) {
throw new CloudRuntimeException("No template details found for the given hypervisor and arch");
}
File templateFile = getTemplateFile(templateDetails);
if (templateFile == null) {
throw new CloudRuntimeException("Failed to find local template file");
}
if (templateDetails.isFileChecksumDifferent(templateFile)) {
throw new CloudRuntimeException("Checksum failed for local template file");
}
return templateDetails;
}
/**
* Return the local template file. Downloads it if not present locally and url is present.
*
* @param templateDetails template metadata; may set `downloadedFilePath`
* @return the template {@code File} on disk, or {@code null} if not found/downloaded
*/
protected File getTemplateFile(MetadataTemplateDetails templateDetails) {
File templateFile = new File(templateDetails.getDefaultFilePath());
if (templateFile.exists()) {
return templateFile;
}
LOGGER.debug("{} is not present", templateFile.getAbsolutePath());
if (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(getTempDownloadDir(), templateDetails.getFilename());
}
if (!templateFile.exists() &&
!HttpUtils.downloadFileWithProgress(templateDetails.getUrl(), templateFile.getAbsolutePath(),
LOGGER)) {
LOGGER.error("Failed to download template for {} using url: {}",
templateDetails.getHypervisorArchLog(), templateDetails.getUrl());
return null;
}
templateDetails.setDownloadedFilePath(templateFile.getAbsolutePath());
}
return templateFile;
}
/**
* Validate that templates for the provided hypervisor/architecture pairs which are in use and are valid.
*
* If a template is missing or validation fails for any required pair, a
* {@link CloudRuntimeException} is thrown to abort the upgrade. If system VM Template for a hypervisor/arch is
* not considered available then validation is skipped for that pair.
*
* @param hypervisorArchList list of hypervisor/architecture pairs to validate
*/
protected void validateTemplates(List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> hypervisorArchList) {
boolean templatesFound = true;
for (Pair<Hypervisor.HypervisorType, CPU.CPUArch> hypervisorArch : hypervisorArchList) {
if (!AVAILABLE_SYSTEM_TEMPLATES_HYPERVISOR_ARCH_LIST.contains(hypervisorArch)) {
LOGGER.info("No system VM Template available for {}. Skipping validation.",
getHypervisorArchLog(hypervisorArch.first(), hypervisorArch.second()));
continue;
}
try {
getValidatedTemplateDetailsForHypervisorAndArch(hypervisorArch.first(), hypervisorArch.second());
} catch (CloudRuntimeException e) {
LOGGER.error("Validation failed for {}: {}",
getHypervisorArchLog(hypervisorArch.first(), hypervisorArch.second()), e.getMessage());
templatesFound = false;
break;
}
}
if (!templatesFound) {
String errMsg = "SystemVM Template not found. Cannot upgrade system VMs";
LOGGER.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
}
/**
* Register or ensure system VM Templates are present on the NFS store for a given zone.
*
* Mounts the zone image store, enumerates hypervisors and architectures in the zone,
* and for each template either adds an existing template to the store or registers
* a new template as required.
*
* @param zoneId the zone id
* @param storeMountPath temporary mount path for the store
*/
protected void registerTemplatesForZone(long zoneId, String storeMountPath) {
Pair<String, Long> storeUrlAndId = getNfsStoreInZone(zoneId);
String nfsVersion = getNfsVersion(storeUrlAndId.second());
mountStore(storeUrlAndId.first(), storeMountPath, nfsVersion);
List<Pair<Hypervisor.HypervisorType, CPU.CPUArch>> hypervisorArchList =
clusterDao.listDistinctHypervisorsAndArchExcludingExternalType(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.getHypervisorType(), templateDetails.getArch(), templateDetails.getUrl());
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;
}
}
addExistingTemplateToStore(templateVO, templateDetails, templateDataStoreVO, zoneId,