forked from vmware/photon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
executable file
·1596 lines (1299 loc) · 53.6 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 shutil
import traceback
from argparse import ArgumentParser
from pathlib import PurePath
from urllib.parse import urlparse
# photon imports
sys.path.append(
f"{os.path.dirname(os.path.realpath(__file__))}/support/package-builder"
)
sys.path.append(
f"{os.path.dirname(os.path.realpath(__file__))}/support/image-builder",
)
sys.path.append(
f"{os.path.dirname(os.path.realpath(__file__))}/support/spec-checker",
)
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 check_spec import check_specs
from utils import Utils
targetDict = {
"image": [
"iso",
"ami",
"gce",
"azure",
"rpi",
"ova",
"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()
runBashCmd = cmdUtils.runBashCmd
curDir = os.getcwd()
photonDir = os.path.dirname(os.path.realpath(__file__))
def build_vixdiskutil():
if not os.path.exists(f"{photonDir}/tools/bin/vixdiskutil"):
runBashCmd(f"bash {photonDir}/tools/src/vixDiskUtil/make.sh")
def url_validator(url):
try:
res = urlparse(url)
return all([res.scheme, res.netloc])
except:
return False
class Build_Config:
buildThreads = 1
stagePath = ""
pkgJsonInput = None
rpmNoArchPath = ""
chrootPath = ""
generatedDataPath = ""
pullPublishRPMSDir = ""
pullPublishRPMS = ""
pullPublishRPMSCached = ""
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 setPullPublishRPMS(pullPublishRPMS):
Build_Config.pullPublishRPMS = pullPublishRPMS
@staticmethod
def setPullPublishRPMSCached(pullPublishRPMSCached):
Build_Config.pullPublishRPMSCached = pullPublishRPMSCached
"""
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):
runBashCmd(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:
runBashCmd(
f"cp {Build_Config.dataDir}/build_install_options_all.json"
f" {Build_Config.dataDir}/build_install_options_minimal.json"
f" {Build_Config.dataDir}/build_install_options_rt.json"
f" {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")
runBashCmd(
f"rm -rf {Build_Config.rpmNoArchPath}/* {Build_Config.rpmArchPath}/*"
)
runBashCmd(
"cp -rf "
+ configdict["additional-path"]["photon-cache-path"]
+ f"/RPMS/noarch/* {Build_Config.rpmNoArchPath}"
)
runBashCmd(
"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...")
runBashCmd(
"ln -sf "
+ configdict["additional-path"]["photon-sources-path"]
+ " "
+ constants.sourcePath
)
check_prerequesite["sources-cached"] = True
def pull_publish_rpms():
if check_prerequesite["publish-rpms"]:
return
if not configdict["additional-path"]["photon-publish-rpms-path"]:
print("Pulling toolchain RPMS...")
cmd = f"cd {Build_Config.pullPublishRPMSDir} && {Build_Config.pullPublishRPMS}"
cmd = f"{cmd} {constants.prevPublishRPMRepo} {constants.publishrpmurl} rpmfilelist"
runBashCmd(cmd)
else:
BuildEnvironmentSetup.publish_rpms_cached()
check_prerequesite["publish-rpms"] = True
def pull_publish_x_rpms():
if check_prerequesite["publish-x-rpms"]:
return
if not configdict["additional-path"]["photon-publish-x-rpms-path"]:
print("Pulling toolchain XRPMS...")
cmd = f"cd {Build_Config.pullPublishRPMSDir} && {Build_Config.pullPublishRPMS}"
cmd = f"{cmd} {constants.prevPublishXRPMRepo} {constants.publishXrpmurl} xrpmfilelist"
runBashCmd(cmd)
else:
BuildEnvironmentSetup.publish_x_rpms_cached()
check_prerequesite["publish-x-rpms"] = True
def publish_rpms_cached():
if check_prerequesite["publish-rpms-cached"]:
return
cmd = f"cd {Build_Config.pullPublishRPMSDir} &&"
cmd = f"{cmd} {Build_Config.pullPublishRPMSCached} {constants.prevPublishRPMRepo} "
cmd += (
configdict["additional-path"]["photon-publish-rpms-path"] + " rpmfilelist"
)
runBashCmd(cmd)
check_prerequesite["publish-rpms-cached"] = True
def publish_x_rpms_cached():
if check_prerequesite["publish-x-rpms-cached"]:
return
cmd = f"cd {Build_Config.pullPublishRPMSDir} &&"
cmd = f"{cmd} {Build_Config.pullPublishRPMSCached} {constants.prevPublishXRPMRepo} "
cmd += (
configdict["additional-path"]["photon-publish-x-rpms-path"]
+ " xrpmfilelist"
)
runBashCmd(cmd)
check_prerequesite["publish-x-rpms-cached"] = True
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,
constants.inputRPMSPath,
]
runBashCmd(f"mkdir -p " + " ".join(stage_dirs))
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}"):
runBashCmd(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...")
runBashCmd(f"rm -f {Build_Config.stagePath}/photon-*.iso")
print("Deleting stage dir...")
runBashCmd(f"rm -rf {Build_Config.stagePath}")
print("Deleting chroot path...")
runBashCmd(f"rm -rf {constants.buildRootPath}")
print("Deleting tools/bin...")
runBashCmd("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"
runBashCmd(cmd)
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}"
runBashCmd(cmd)
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"
)
runBashCmd(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",
)
runBashCmd(f"rm -f {rpmFile}")
def clean_stage_for_incremental_build():
rpm_path = constants.rpmPath
ph_path = configdict["photon-path"]
cmd = (
f"cd {ph_path} && test -n "
f"\"$(git diff --name-only @~1 @ | grep '^support/\(package-builder\|pullpublishrpms\)')\""
f" && {{ echo 'Remove all staged RPMs'; rm -rf {rpm_path}; }} || :"
)
runBashCmd(cmd)
if not os.path.exists(rpm_path):
print(f"{rpm_path} is empty, return ...")
return
basecommit = ""
if "base-commit" in configdict["photon-build-param"]:
basecommit = str(configdict["photon-build-param"].get("base-commit"))
if not basecommit:
return
cmd = (
f"cd {ph_path} && echo `git diff --name-only {basecommit} | grep '\.spec'"
f" | xargs -n1 basename 2>/dev/null` | tr ' ' :"
)
spec_fns, _, _ = runBashCmd(cmd, capture=True)
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.pull_publish_x_rpms()
if configdict["additional-path"]["photon-publish-rpms-path"] is not None:
BuildEnvironmentSetup.publish_rpms_cached()
else:
BuildEnvironmentSetup.pull_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:
runBashCmd(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"]
runBashCmd(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"
f" {photonDir} {Build_Config.stagePath} {constants.releaseVersion} {ph_docker_img}"
)
runBashCmd(cmd)
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()
CheckTools.check_git_hooks()
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/ph-docker-img-import.sh {ph_docker_img_url}"
f" {ph_docker_img} {ph_builder_tag}"
)
runBashCmd(cmd)
def check_git_hooks():
if not os.path.exists(f"{photonDir}/.git"):
print("Not building Photon from a git repo, return ...")
return
git_hooks_path = f"{photonDir}/.git/hooks"
hook_scripts_path = f"{photonDir}/tools/scripts"
for fn in {"commit-msg", "pre-push"}:
if not os.path.exists(f"{git_hooks_path}/{fn}"):
print(f"{hook_scripts_path}/{fn} doesn't exist, create ...")
runBashCmd(f"ln -srv {hook_scripts_path}/{fn} {git_hooks_path}/{fn}")
def check_contain():
if not os.path.exists(f"{photonDir}/tools/bin/contain_unpriv"):
runBashCmd(f"bash {photonDir}/tools/src/contain/make.sh")
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")
runBashCmd("pip3 show pyOpenSSL &>/dev/null")
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"
runBashCmd(script)
def check_docker():
if not glob.glob(Build_Config.dockerEnv) and not shutil.which("docker"):
raise Exception("docker not present")
runBashCmd("systemctl start docker")
if not glob.glob(Build_Config.dockerEnv):
runBashCmd("docker ps &>/dev/null")
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
cmd = f"{photonDir}/tools/scripts/get_modified_files.sh"
if "base-commit" in configdict["photon-build-param"]:
commit_id = str(configdict["photon-build-param"].get("base-commit"))
if commit_id:
cmd = f"git diff --name-only {commit_id}"
files, _, _ = runBashCmd(cmd, capture=True)
files = files.splitlines()
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"
install_cmd = f"pip3 install git+{url}"
def install_from_url(cmd):
runBashCmd(cmd)
try:
import photon_installer
except Exception as e:
print("Warning: %s" % e)
install_from_url(install_cmd)
return
key = "SKIP_INSTALLER_UPDATE"
if key in os.environ and cmdUtils.strtobool(os.environ[key]):
print("%s is enabled, not checking for updates" % key)