forked from vmware/photon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
executable file
·1552 lines (1271 loc) · 53.2 KB
/
build.py
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
#!/usr/bin/env python3
# built-in imports
import os
import sys
import docker
import glob
import json
import subprocess
import shutil
import traceback
from argparse import ArgumentParser
from pathlib import PurePath
from subprocess import PIPE, Popen
# photon imports
sys.path.insert(
0,
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "support/package-builder"
),
)
sys.path.insert(
1,
os.path.join(os.path.dirname(os.path.realpath(__file__)), "support/image-builder"),
)
import imagebuilder
import GenerateOSSFiles
import PullSources as downloader
from builder import Builder
from constants import constants
from CommandUtils import CommandUtils
from Logger import Logger
from PackageManager import PackageManager
from StringUtils import StringUtils
from SpecDeps import SpecDependencyGenerator
from SpecData import SPECS
from support.check_spec import check_specs
from utils import Utils
targetDict = {
"image": [
"iso",
"ami",
"gce",
"azure",
"rpi",
"ova",
"ova_uefi",
"all",
"src-iso",
"ls1012afrwy",
"photon-docker-image",
"k8s-docker-images",
"all-images",
"minimal-iso",
"rt-iso",
],
"rpmBuild": [
"packages",
"packages-minimal",
"packages-rt",
"packages-initrd",
"packages-docker",
"updated-packages",
"tool-chain-stage1",
"tool-chain-stage2",
"check-packages",
"ostree-repo",
"generate-yaml-files",
"create-repo",
"distributed-build",
],
"buildEnvironment": [
"packages-cached",
"sources",
"sources-cached",
"publish-rpms",
"publish-x-rpms",
"publish-rpms-cached",
"publish-x-rpms-cached",
"photon-stage",
],
"cleanup": [
"clean",
"clean-install",
"clean-chroot",
"clean-stage-for-incremental-build",
],
"tool-checkup": [
"check-pre-reqs",
"check-spec-files",
"initialize-constants",
],
"utilities": [
"generate-dep-lists",
"pkgtree",
"imgtree",
"who-needs",
"print-upward-deps",
"pull-stage-rpms",
"clean-stage-rpms",
],
}
configdict = {}
check_prerequesite = {}
cmdUtils = CommandUtils()
runCommandInShell = cmdUtils.runCommandInShell
runShellCmd = cmdUtils.runShellCmd
curDir = os.getcwd()
photonDir = os.path.dirname(os.path.realpath(__file__))
def build_vixdiskutil():
if not os.path.exists(f"{photonDir}/tools/bin"):
cmdUtils.runShellCmd(f"mkdir -p {photonDir}/tools/bin")
if not os.path.exists(f"{photonDir}/tools/bin/vixdiskutil"):
runShellCmd(f"make -C {photonDir}/tools/src/vixDiskUtil")
class Build_Config:
buildThreads = 1
stagePath = ""
pkgJsonInput = None
rpmNoArchPath = ""
chrootPath = ""
generatedDataPath = ""
pullPublishRPMSDir = ""
pullPublishRPMS = ""
pullPublishXRPMS = ""
updatedRpmPath = ""
updatedRpmNoArchPath = ""
dockerEnv = "/.dockerenv"
updatedRpmArchPath = ""
pkgInfoFile = ""
rpmArchPath = ""
commonDir = ""
pkgBuildType = ""
dataDir = ""
packageListFile = "build_install_options_all.json"
pkgToBeCopiedConfFile = None
confFile = None
distributedBuildFile = "distributed_build_options.json"
@staticmethod
def setDockerEnv(dockerEnv):
Build_Config.dockerEnv = dockerEnv
@staticmethod
def setDistributedBuildFile(distributedBuildFile):
Build_Config.distributedBuildFile = distributedBuildFile
@staticmethod
def setPkgToBeCopiedConfFile(pkgToBeCopiedConfFile):
Build_Config.pkgToBeCopiedConfFile = pkgToBeCopiedConfFile
@staticmethod
def setRpmNoArchPath():
Build_Config.rpmNoArchPath = f"{constants.rpmPath}/noarch"
@staticmethod
def setRpmArchPath():
Build_Config.rpmArchPath = f"{constants.rpmPath}/{constants.buildArch}"
@staticmethod
def setConfFile(confFile):
Build_Config.confFile = confFile
@staticmethod
def setPkgBuildType(pkgBuildType):
Build_Config.pkgBuildType = pkgBuildType
@staticmethod
def setBuildThreads(buildThreads):
Build_Config.buildThreads = buildThreads
@staticmethod
def setPkgJsonInput(pkgJsonInput):
Build_Config.pkgJsonInput = pkgJsonInput
@staticmethod
def setUpdatedRpmPath(updatedRpmPath):
Build_Config.updatedRpmPath = updatedRpmPath
Build_Config.updatedRpmNoArchPath = f"{updatedRpmPath}/noarch"
Build_Config.updatedRpmArchPath = f"{updatedRpmPath}/{constants.buildArch}"
@staticmethod
def setStagePath(stagePath):
Build_Config.stagePath = stagePath
@staticmethod
def setPkgInfoFile(pkgInfoFile):
Build_Config.pkgInfoFile = pkgInfoFile
@staticmethod
def setChrootPath(chrootPath):
Build_Config.chrootPath = chrootPath
@staticmethod
def setGeneratedDataDir(generatedDataDir):
Build_Config.generatedDataPath = generatedDataDir
@staticmethod
def setCommonDir(commonDir):
Build_Config.commonDir = commonDir
@staticmethod
def setDataDir(dataDir):
Build_Config.dataDir = dataDir
pkgListFile = Build_Config.packageListFile
Build_Config.packageListFile = f"{dataDir}/{pkgListFile}"
@staticmethod
def setPullPublishRPMSDir(pullPublishRPMSDir):
Build_Config.pullPublishRPMSDir = pullPublishRPMSDir
@staticmethod
def setPullPublishXRPMS(pullPublishXRPMS):
Build_Config.pullPublishXRPMS = pullPublishXRPMS
@staticmethod
def setPullPublishRPMS(pullPublishRPMS):
Build_Config.pullPublishRPMS = pullPublishRPMS
"""
class Utilities is used for generating spec dependency, printing upward dependencies for package..
"""
class Utilities:
global configdict
global check_prerequesite
def __init__(self, args):
self.img = configdict.get("utility", {}).get("img", None)
self.json_file = configdict.get("utility", {}).get("file", "packages_*.json")
self.display_option = configdict.get("utility", {}).get(
"display-option", "json"
)
self.input_type = configdict.get("utility", {}).get("input-type", "json")
self.pkg = configdict.get("utility", {}).get("pkg", None)
self.args = args
self.logger = Logger.getLogger(
"SpecDeps", constants.logPath, constants.logLevel
)
if not os.path.isdir(Build_Config.generatedDataPath):
runCommandInShell(f"mkdir -p {Build_Config.generatedDataPath}")
if configdict["targetName"] in ["pkgtree", "who_needs", "print_upward_deps"]:
if "pkg" not in os.environ:
if not args or len(args) != 1:
raise Exception(
"Please provide package name as a parameter or as an environment variable pkg=<pkg-name>"
)
self.pkg = args[0]
else:
self.pkg = os.environ["pkg"]
self.display_option = "tree"
if configdict["targetName"] == "imgtree" and "img" not in os.environ:
raise Exception("img not present in os.environ")
if configdict["targetName"] == "imgtree":
self.json_file = "packages_" + os.environ["img"] + ".json"
self.specDepsObject = SpecDependencyGenerator(
constants.logPath, constants.logLevel
)
def generate_dep_lists(self):
check_prerequesite["generate-dep-lists"] = True
list_json_files = glob.glob(os.path.join(Build_Config.dataDir, self.json_file))
# Generate the expanded package dependencies json file based on package_list_file
self.logger.info(
"Generating the install time dependency list for all json files"
)
if list_json_files:
runShellCmd(
f"cp {Build_Config.dataDir}/build_install_options_all.json {Build_Config.dataDir}/build_install_options_minimal.json {Build_Config.dataDir}/build_install_options_rt.json {Build_Config.generatedDataPath}"
)
for json_file in list_json_files:
output_file = None
if self.display_option == "json":
output_file = os.path.join(
Build_Config.generatedDataPath,
os.path.splitext(os.path.basename(json_file))[0] + "_expanded.json",
)
self.specDepsObject.process(
self.input_type, json_file, self.display_option, output_file
)
shutil.copyfile(
json_file,
os.path.join(
Build_Config.generatedDataPath, os.path.basename(json_file)
),
)
def pkgtree(self):
self.input_type = "pkg"
self.specDepsObject.process(self.input_type, self.pkg, self.display_option)
def who_needs(self):
self.input_type = "who-needs"
self.specDepsObject.process(self.input_type, self.pkg, self.display_option)
def imgtree(self):
self.input_type = "json"
self.generate_dep_lists()
def print_upward_deps(self):
whoNeedsList = self.specDepsObject.process(
"get-upward-deps", self.pkg, self.display_option
)
self.logger.info("Upward dependencies: " + str(whoNeedsList))
def pull_stage_rpms(self):
if not self.args or len(self.args) != 1:
raise Exception("Please provide pull url as a parameter")
url = self.args[0]
files = self.specDepsObject.listRPMfilenames()
notFound = []
for f in files:
dst = os.path.join(constants.rpmPath, f)
if os.path.exists(dst):
continue
src = f"{url}/{f}"
print(f"Downloading {f}")
try:
downloader.downloadFile(src, dst)
except Exception:
self.logger.info("Not found")
notFound.append(f)
if notFound:
self.logger.info("List of missing files: " + str(notFound))
def clean_stage_rpms(self):
keepFiles = self.specDepsObject.listRPMfilenames(True)
rpmpath = os.path.join(constants.rpmPath, constants.currentArch)
allFiles = []
for f in os.listdir(rpmpath):
if os.path.isfile(f"{rpmpath}/{f}"):
allFiles.append(f"{constants.currentArch}/{f}")
rpmpath = f"{constants.rpmPath}/noarch"
for f in os.listdir(rpmpath):
if os.path.isfile(f"{rpmpath}/{f}"):
allFiles.append(f"noarch/{f}")
removeFiles = list(set(allFiles) - set(keepFiles))
for f in removeFiles:
filePath = os.path.join(constants.rpmPath, f)
print("Removing {}".format(f))
try:
os.remove(filePath)
except Exception as error:
print("Error while removing file {0}: {1}".format(filePath, error))
"""
class Buildenvironmentsetup does job like pulling toolchain RPMS and creating stage...
"""
class BuildEnvironmentSetup:
global configdict
global check_prerequesite
def packages_cached():
check_prerequesite["packages-cached"] = True
if not configdict["additional-path"]["photon-cache-path"]:
raise Exception("ERROR: photon-cache-path is empty")
runCommandInShell(
f"rm -rf {Build_Config.rpmNoArchPath}/* {Build_Config.rpmArchPath}/*"
)
runCommandInShell(
"cp -rf "
+ configdict["additional-path"]["photon-cache-path"]
+ f"/RPMS/noarch/* {Build_Config.rpmNoArchPath}"
)
runCommandInShell(
"cp -rf "
+ configdict["additional-path"]["photon-cache-path"]
+ f"/RPMS/{constants.currentArch}/* {Build_Config.rpmArchPath}"
)
RpmBuildTarget.create_repo()
def sources():
if check_prerequesite["sources"]:
return
if not configdict["additional-path"]["photon-sources-path"]:
check_prerequesite["sources"] = True
if not os.path.isdir(constants.sourcePath):
os.mkdir(constants.sourcePath)
else:
BuildEnvironmentSetup.sources_cached()
def sources_cached():
if check_prerequesite["sources-cached"]:
return
if not configdict["additional-path"]["photon-sources-path"]:
raise Exception("ERROR: photon-sources-path is empty")
print("Using cached SOURCES...")
runCommandInShell(
"ln -sf "
+ configdict["additional-path"]["photon-sources-path"]
+ " "
+ constants.sourcePath
)
check_prerequesite["sources-cached"] = True
def publish_rpms():
if check_prerequesite["publish-rpms"]:
return
if not configdict["additional-path"]["photon-publish-rpms-path"]:
check_prerequesite["publish-rpms"] = True
print("Pulling toolchain RPMS...")
cmd = f"cd {Build_Config.pullPublishRPMSDir} &&"
cmd = f"{cmd} {Build_Config.pullPublishRPMS} {constants.prevPublishRPMRepo}"
runShellCmd(cmd)
else:
BuildEnvironmentSetup.publish_rpms_cached()
def publish_rpms_cached():
if check_prerequesite["publish-rpms-cached"]:
return
if not os.path.isdir(
f"{constants.prevPublishRPMRepo}/{constants.currentArch}"
):
os.makedirs(f"{constants.prevPublishRPMRepo}/{constants.currentArch}")
if not os.path.isdir(f"{constants.prevPublishRPMRepo}/noarch"):
os.makedirs(f"{constants.prevPublishRPMRepo}/noarch")
cmd = f"cd {Build_Config.pullPublishRPMSDir} &&"
cmd = f"{cmd} {Build_Config.pullPublishRPMS} {constants.prevPublishRPMRepo} "
cmd += configdict["additional-path"]["photon-publish-rpms-path"]
runShellCmd(cmd)
check_prerequesite["publish-rpms-cached"] = True
def publish_x_rpms_cached():
if check_prerequesite["publish-x-rpms-cached"]:
return
if not os.path.isdir(
f"{constants.prevPublishXRPMRepo}/{constants.currentArch}"
):
os.makedirs(f"{constants.prevPublishXRPMRepo}/{constants.currentArch}")
if not os.path.isdir(f"{constants.prevPublishXRPMRepo}/noarch"):
os.makedirs(f"{constants.prevPublishXRPMRepo}/noarch")
cmd = f"cd {Build_Config.pullPublishRPMSDir} &&"
cmd = f"{cmd} {Build_Config.pullPublishXRPMS} {constants.prevPublishXRPMRepo} "
cmd += configdict["additional-path"]["photon-publish-x-rpms-path"]
runShellCmd(cmd)
check_prerequesite["publish-x-rpms-cached"] = True
def publish_x_rpms():
if check_prerequesite["publish-x-rpms"]:
return
if not configdict["additional-path"]["photon-publish-x-rpms-path"]:
check_prerequesite["publish-x-rpms"] = True
print("\nPulling X toolchain RPMS from packages.vmware.com ...")
cmd = f"cd {Build_Config.pullPublishRPMSDir} &&"
cmd = (
f"{cmd} {Build_Config.pullPublishXRPMS} {constants.prevPublishXRPMRepo}"
)
runShellCmd(cmd)
else:
BuildEnvironmentSetup.publish_x_rpms_cached()
def photon_stage():
if check_prerequesite["photon-stage"]:
return
print("\nCreating staging folder and subitems...")
stage_dirs = [
Build_Config.stagePath,
constants.buildRootPath,
constants.rpmPath,
Build_Config.rpmArchPath,
Build_Config.rpmNoArchPath,
constants.sourceRpmPath,
Build_Config.updatedRpmNoArchPath,
Build_Config.updatedRpmArchPath,
constants.sourcePath,
constants.logPath,
]
for d in stage_dirs:
runShellCmd(f"mkdir -p {d}")
files = ["COPYING", "NOTICE-GPL2.0", "NOTICE-Apachev2", "EULA.txt"]
stagePath = Build_Config.stagePath
for fn in files:
if not os.path.isfile(f"{stagePath}/{fn}"):
runShellCmd(f"install -m 444 {curDir}/{fn} {stagePath}")
check_prerequesite["photon-stage"] = True
"""
class Cleanup does the job of cleaning up the stage directory...
"""
class CleanUp:
def clean():
CleanUp.clean_install()
CleanUp.clean_chroot()
print("Deleting Photon ISO...")
runCommandInShell(f"rm -f {Build_Config.stagePath}/photon-*.iso")
print("Deleting stage dir...")
runCommandInShell(f"rm -rf {Build_Config.stagePath}")
print("Deleting chroot path...")
runCommandInShell(f"rm -rf {constants.buildRootPath}")
print("Deleting tools/bin...")
runCommandInShell("rm -rf tools/bin")
def clean_install():
print("Cleaning installer working directory...")
if os.path.isdir(os.path.join(Build_Config.stagePath, "photon_iso")):
cmd = f"{photonDir}/support/package-builder/clean-up-chroot.py {Build_Config.stagePath}/photon_iso"
if runCommandInShell(cmd):
raise Exception("Not able to clean chroot")
def clean_chroot():
print("Cleaning chroot path...")
if os.path.isdir(constants.buildRootPath):
cmd = f"{photonDir}/support/package-builder/clean-up-chroot.py {constants.buildRootPath}"
if runCommandInShell(cmd):
raise Exception("Not able to clean chroot")
def removeUpwardDeps(pkg, display_option):
specDeps = SpecDependencyGenerator(constants.logPath, constants.logLevel)
isToolChainPkg = specDeps.process("is-toolchain-pkg", pkg, display_option)
if isToolChainPkg:
specDeps.logger.info(
"Removing all staged RPMs since toolchain packages were modified"
)
runCommandInShell(f"rm -rf {constants.rpmPath}")
else:
whoNeedsList = specDeps.process("get-upward-deps", pkg, display_option)
specDeps.logger.info("Removing upward dependencies: " + str(whoNeedsList))
for pkg in whoNeedsList:
package, version = StringUtils.splitPackageNameAndVersion(pkg)
release = SPECS.getData().getRelease(package, version)
for p in SPECS.getData().getPackages(package, version):
buildarch = SPECS.getData().getBuildArch(p, version)
rpmFile = os.path.join(
constants.rpmPath,
buildarch,
f"{p}-{version}-{release}.*{buildarch}.rpm",
)
runCommandInShell(f"rm -f {rpmFile}")
def clean_stage_for_incremental_build():
rpm_path = constants.rpmPath
ph_path = configdict["photon-path"]
basecommit = configdict["photon-build-param"]["base-commit"]
command = (
"cd {} && test -n "
"\"$(git diff --name-only @~1 @ | grep '^support/\(make\|package-builder\|pullpublishrpms\)')\""
" && {{ echo 'Remove all staged RPMs'; rm -rf {}; }} || :"
)
command = command.format(ph_path, rpm_path)
if runCommandInShell(command):
raise Exception("Not able to run clean_stage_for_incremental_build")
if not os.path.exists(rpm_path):
print(f"{rpm_path} is empty, return ...")
return
command = (
"cd {} && echo `git diff --name-only {} | grep '\.spec' | "
"xargs -n1 basename 2>/dev/null` | tr ' ' :"
)
command = command.format(ph_path, basecommit)
with Popen(command, stdout=PIPE, stderr=None, shell=True) as process:
spec_fns = process.communicate()[0].decode("utf-8")
if process.returncode:
raise Exception("Error in clean_stage_for_incremental_build")
if not spec_fns:
print("No spec files were changed in this incremental build")
return
try:
spec_fns = spec_fns.strip("\n")
CleanUp.removeUpwardDeps(spec_fns, "tree")
except Exception as error:
print(f"Error in clean_stage_for_incremental_build: {error}")
"""
class Rpmbuildtarget does the job of building all the RPMs for the SPECS
It uses Builder class in builder.py in order to build packages.
"""
class RpmBuildTarget:
global configdict
global check_prerequesite
def __init__(self):
self.logger = Logger.getLogger("Main", constants.logPath, constants.logLevel)
BuildEnvironmentSetup.photon_stage()
if configdict["additional-path"]["photon-publish-x-rpms-path"] is not None:
BuildEnvironmentSetup.publish_x_rpms_cached()
else:
BuildEnvironmentSetup.publish_x_rpms()
if configdict["additional-path"]["photon-publish-rpms-path"] is not None:
BuildEnvironmentSetup.publish_rpms_cached()
else:
BuildEnvironmentSetup.publish_rpms()
if configdict["additional-path"]["photon-sources-path"] is not None:
BuildEnvironmentSetup.sources_cached()
else:
BuildEnvironmentSetup.sources()
CheckTools.check_spec_files()
Utilities(None).generate_dep_lists()
if constants.buildArch != constants.targetArch:
runCommandInShell(
f"mkdir -p {constants.rpmPath}/{constants.targetArch}"
)
self.logger.debug(f"Source Path : {constants.sourcePath}")
self.logger.debug(f"Spec Path : {constants.specPath}")
self.logger.debug(f"Rpm Path : {constants.rpmPath}")
self.logger.debug(f"Log Path : {constants.logPath}")
self.logger.debug(f"Log Level : {constants.logLevel}")
self.logger.debug(f"Top Dir Path : {constants.topDirPath}")
self.logger.debug(f"Publish RPMS Path : {constants.prevPublishRPMRepo}")
self.logger.debug(f"Publish X RPMS Path : {constants.prevPublishXRPMRepo}")
Builder.get_packages_with_build_options(
configdict["photon-build-param"]["pkg-build-options"]
)
if constants.buildArch != constants.targetArch:
# It is cross compilation
# first build all native packages
Builder.buildPackagesForAllSpecs(
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
# Then do the build to the target
constants.currentArch = constants.targetArch
constants.crossCompiling = True
@staticmethod
def create_repo():
if check_prerequesite["create-repo"]:
return
createrepo_cmd = configdict["createrepo-cmd"]
runShellCmd(f"{createrepo_cmd} --update {constants.rpmPath}")
check_prerequesite["create-repo"] = True
@staticmethod
def ostree_repo():
if check_prerequesite["ostree-repo"]:
return
ph_docker_img = configdict["photon-build-param"]["photon-docker-image"]
if not os.path.isfile(
os.path.join(Build_Config.stagePath, "ostree-repo.tar.gz")
):
print("Creating OSTree repo from local RPMs in ostree-repo.tar.gz...")
RpmBuildTarget.create_repo()
cmd = f"{photonDir}/support/image-builder/ostree-tools/make-ostree-image.sh"
cmd = f"{cmd} {photonDir} {Build_Config.stagePath} {ph_docker_img}"
if runShellCmd(cmd):
raise Exception("Not able to execute make-ostree-image.sh")
else:
print("OSTree repo already exists...")
check_prerequesite["ostree-repo"] = True
def packages(self):
if check_prerequesite["packages"]:
return
if not configdict["additional-path"]["photon-cache-path"]:
Builder.buildPackagesForAllSpecs(
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
RpmBuildTarget.create_repo()
else:
BuildEnvironmentSetup.packages_cached()
check_prerequesite["packages"] = True
def package(self, pkgName):
self.logger.debug(f"Package to build: {pkgName}")
Builder.buildSpecifiedPackages(
[pkgName], Build_Config.buildThreads, Build_Config.pkgBuildType
)
def packages_minimal(self):
if check_prerequesite["packages-minimal"]:
return
if not configdict["additional-path"]["photon-cache-path"]:
Builder.buildPackagesInJson(
os.path.join(Build_Config.dataDir, "packages_minimal.json"),
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
else:
BuildEnvironmentSetup.packages_cached()
check_prerequesite["packages-minimal"] = True
def packages_rt(self):
if check_prerequesite["packages-rt"]:
return
if not configdict["additional-path"]["photon-cache-path"]:
Builder.buildPackagesInJson(
os.path.join(Build_Config.dataDir, "packages_rt.json"),
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
else:
BuildEnvironmentSetup.packages_cached()
check_prerequesite["packages-rt"] = True
def packages_initrd(self):
if check_prerequesite["packages-initrd"]:
return
Builder.buildPackagesInJson(
os.path.join(Build_Config.dataDir, "packages_installer_initrd.json"),
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
check_prerequesite["packages-initrd"] = True
def packages_docker(self):
if check_prerequesite["packages-docker"]:
return
Builder.buildPackagesForAllSpecs(
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
check_prerequesite["packages-docker"] = True
def updated_packages(self):
if check_prerequesite["updated-packages"]:
return
constants.setRpmPath(Build_Config.updatedRpmPath)
Builder.buildPackagesForAllSpecs(
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
check_prerequesite["updated-packages"] = True
def check_packages(self):
if check_prerequesite["check-packages"]:
return
constants.setRPMCheck(True)
constants.setRpmCheckStopOnError(True)
Builder.buildPackagesForAllSpecs(
Build_Config.buildThreads,
Build_Config.pkgBuildType,
Build_Config.pkgInfoFile,
self.logger,
)
check_prerequesite["check-packages"] = True
def distributed_build():
# TODO: should be moved to top
import DistributedBuilder
build_vixdiskutil()
print("Distributed Building using kubernetes ...")
with open(Build_Config.distributedBuildFile, "r") as configFile:
distributedBuildConfig = json.load(configFile)
DistributedBuilder.main(distributedBuildConfig)
def tool_chain_stage1(self):
if check_prerequesite["tool-chain-stage1"]:
return
pkgManager = PackageManager()
pkgManager.buildToolChain()
check_prerequesite["tool-chain-stage1"] = True
def tool_chain_stage2(self):
if check_prerequesite["tool-chain-stage2"]:
return
pkgManager = PackageManager()
pkgManager.buildToolChainPackages(Build_Config.buildThreads)
check_prerequesite["tool-chain-stage2"] = True
def generate_yaml_files(self):
if check_prerequesite["generate-yaml-files"]:
return
print("Generating yaml files for packages...")
BuildEnvironmentSetup.photon_stage()
RpmBuildTarget().packages()
if configdict["photon-build-param"].get("generate-pkg-list", ""):
GenerateOSSFiles.buildPackagesList(
os.path.join(Build_Config.stagePath, "packages_list.csv")
)
else:
blackListPkgs = GenerateOSSFiles.readBlackListPackages(
configdict.get("additional-path", {}).get("pkg-black-list-file", "")
)
logger = Logger.getLogger(
"GenerateYamlFiles", constants.logPath, constants.logLevel
)
GenerateOSSFiles.buildSourcesList(
Build_Config.stagePath, blackListPkgs, logger
)
GenerateOSSFiles.buildSRPMList(
constants.sourceRpmPath,
Build_Config.stagePath,
blackListPkgs,
constants.dist,
logger,
)
check_prerequesite["generate-yaml-files"] = True
"""
class CheckTools does the job of checking weather all the tools required for
starting build process are present on the system
"""
class CheckTools:
global configdict
global check_prerequesite
def check_pre_reqs():
if check_prerequesite["check-pre-reqs"]:
return
CheckTools.check_all_tools()
CheckTools.check_sanity()
CheckTools.check_docker()
CheckTools.create_ph_builder_img()
CheckTools.check_photon_installer()
CheckTools.check_contain()
check_prerequesite["check-pre-reqs"] = True
def create_ph_builder_img():
ph_docker_img = configdict["photon-build-param"]["photon-docker-image"]
ph_docker_img_url = configdict["photon-build-param"]["ph-docker-img-url"]
ph_builder_tag = configdict["photon-build-param"]["ph-builder-tag"]
ph_docker_img_url = ph_docker_img_url.replace("ARCH", constants.currentArch)
cmd = f"{photonDir}/tools/scripts/ph4-docker-img-import.sh {ph_docker_img_url}"
cmd = f"{cmd} {ph_docker_img} {ph_builder_tag}"
runShellCmd(cmd)
def check_contain():
if not os.path.exists(f"{photonDir}/tools/bin"):
cmdUtils.runShellCmd(f"mkdir -p {photonDir}/tools/bin")
if not os.path.exists(f"{photonDir}/tools/bin/contain_unpriv"):
runShellCmd(f"make -C {photonDir}/tools/src/contain install")
def check_all_tools():
tools = ["bison", "g++", "gawk", "makeinfo", "kpartx"]
for tool in tools:
if not shutil.which(tool):
raise Exception(f"{tool} not present")
cmdUtils.runShellCmd("pip3 show pyOpenSSL >/dev/null 2>&1")
createrepo_cmd = ""
for tool in {"createrepo", "createrepo_c"}:
createrepo_cmd = shutil.which(tool)
if createrepo_cmd:
break
if not createrepo_cmd:
raise Exception("createrepo not found")
configdict["createrepo-cmd"] = createrepo_cmd
def check_sanity():
script = f"{photonDir}/tools/scripts/sanity_check.sh"
runShellCmd(script)
def check_docker():
if not glob.glob(Build_Config.dockerEnv) and not shutil.which("docker"):
raise Exception("docker not present")
runShellCmd("systemctl start docker")
if not glob.glob(Build_Config.dockerEnv):
runShellCmd("docker ps >/dev/null 2>&1")
docker_py_ver = "2.3.0"
if not glob.glob(Build_Config.dockerEnv) and docker.__version__ < docker_py_ver:
print(f"\nError: Python3 package docker-{docker_py_ver} not installed.")
print(f"Please use: pip3 install docker=={docker_py_ver}\n")
raise Exception()
def check_spec_files():
if check_prerequesite["check-spec-files"]:
return
command = (
'[ -z "$(git diff --name-only HEAD --)" ] && '
"git diff --name-only @~ || git diff --name-only"
)
if "base-commit" in configdict["photon-build-param"]:
commit_id = str(configdict["photon-build-param"].get("base-commit"))
if commit_id:
command = "git diff --name-only %s" % commit_id
with Popen(command, stdout=PIPE, stderr=None, shell=True) as process:
files = process.communicate()[0].decode("utf-8").splitlines()
if process.returncode:
raise Exception("Something went wrong in check_spec_files")
if check_specs(files):
raise Exception("Spec file check failed")
check_prerequesite["check-spec-files"] = True
def check_photon_installer():
url = "https://github.com/vmware/photon-os-installer.git"
cmd = "pip3 install git+%s" % url
def install_from_url(cmd):
if runCommandInShell(cmd):
raise Exception("Failed to run: %s" % cmd)
print("%s - Success" % cmd)
try:
import photon_installer
except Exception as e:
print("Warning: %s" % e)
install_from_url(cmd)
return