-
Notifications
You must be signed in to change notification settings - Fork 0
/
imagebuild.py
executable file
·799 lines (645 loc) · 24.9 KB
/
imagebuild.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
#!/usr/bin/env python3
# Under alpine
# apk update
# apk add python3
# pip3 install pyyaml
# under Fedora
# dnf install -y python3-pyyaml
import os
import yaml
import sys
import re
import subprocess
import errno
import glob
import configparser
import datetime
import argparse
from distutils.version import LooseVersion
class ShellConfig:
def __init__(self):
self.pattern = r'[ |\t]*([a-zA-Z_][a-zA-Z0-9_]*)=("([^\\"]|.*)"|([^# \t]*)).*[\r]*\n'
self.prog = re.compile(self.pattern)
def parse_lines(self, lines, dict):
for line in lines:
result = self.prog.match(line)
if not result is None:
name = result.groups()[0]
if result.groups()[2] is None:
value= result.groups()[3]
else:
value= result.groups()[2]
dict[name]=value
return dict
def read_shell_config(self, filename, dict=None):
if dict is None:
dict={}
try:
with open(filename) as f:
lines = f.readlines()
self.parse_lines(lines, dict)
except IOError:
pass
return dict
class OsRelease(ShellConfig):
def __init__(self, filename='/etc/os-release'):
ShellConfig.__init__(self)
self.read_shell_config(filename,self.__dict__)
class Locale(ShellConfig):
def __init__(self, filename='/etc/locale.conf', LANG='en_US.UTF-8'):
self.LANG=LANG
ShellConfig.__init__(self)
self.read_shell_config(filename,self.__dict__)
class DictToObject:
def __init__(self, dict):
self.__dict__.update(dict)
class PackageManagerBase:
def __init__(self):
pass
def is_version_lt_or_eq(self, a , b ):
if a == "rawhide":
a == sys.maxsize
if b == "rawhide":
b == sys.maxsize
return (LooseVersion(str(a)) <= LooseVersion(str(b)))
def pick_entry(self, table, os_name, os_version):
for entry in table:
if entry[0] == os_name:
# we have a version limit, check it
if len(entry) == 3:
if self.is_version_lt_or_eq(os_version, entry[2]):
return entry[1]
else:
return entry[1]
return ""
def determine_package_manager(self, os_name, os_version):
# With the third optional column you can limit the version
# This requires that smaller version are in sequence in the table.
table = [
[ 'fedora', 'yum', 21 ],
[ 'fedora', 'dnf'],
[ 'centos', 'yum'],
[ 'rhel', 'yum'],
[ 'debian', 'apt-get'],
[ 'alpine', 'apk'],
]
return self.pick_entry(table,os_name,os_version)
def package_list(self, os_name, os_version):
# With the third optional column you can limit the version
# This requires that smaller version are in sequence in the table.
table = [
[ 'fedora', 'bash rootfiles vim-minimal sssd-client e2fsprogs yum fedora-release', 21 ],
[ 'fedora', 'bash rootfiles vim-minimal sssd-client e2fsprogs dnf dnf-yum fedora-release'],
[ 'centos', 'bash rootfiles vim-minimal sssd-client e2fsprogs yum systemd centos-release'],
[ 'rhel', 'bash rootfiles vim-minimal sssd-client e2fsprogs yum rhel-release'],
[ 'debian', 'FIXME'],
[ 'ubuntu', 'FIXME'],
[ 'alpine', 'alpine-base'],
]
package_list = self.pick_entry(table,os_name,os_version)
return package_list.split()
def package_list_add(self, os_name, os_version):
table = [
['fedora', 'procps-ng'],
['centos', ''],
['rhel' , '']
]
package_list = self.pick_entry(table,os_name,os_version)
return package_list.split()
def get_repository_list(self, os_name, os_version):
if os_name == "fedora":
list = [os_name,"updates"]
elif os_name == "centos":
list = [os_name+"-"+"base",os_name +"-" "updates"]
elif os_name == "alpine":
list = [ "http://dl-cdn.alpinelinux.org/alpine/v3.5/main" ]
else:
list = []
return list
def mkdir_p(self,path):
# print(path)
try:
os.makedirs(path)
# print("success")
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def symlink(self,src,dst):
try:
os.symlink(src,dst)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else:
raise
def execute2(self, cmd, home_dir):
my_env = os.environ.copy()
# this setting is importent to get the ".rpmmacro" from a "home" directory of our choice
my_env["HOME"] = home_dir
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=my_env)
while True:
out = process.stdout.readline()
if out == b'' and process.poll() != None:
break
if out != b'':
print(out.decode('utf-8'), end="")
return process.returncode
class AlpinePackageManager(PackageManagerBase):
def __init__(self):
pass
class RedhatPackageManager(PackageManagerBase):
def __init__(self):
self.test = ""
def install_distribution(self):
self.test = ""
def create_package_manager_conf_file(self, package_manager, build_dir, http_proxy='', nodocs=''):
array=[]
array.append("[main]")
array.append("gpgcheck=1")
array.append("installonly_limit=3")
array.append("clean_requirements_on_remove=true")
# cachedir will be used when already running the "chroot" environment
# thereforee there MUST NOT be a "build_dir" prefix
array.append("cachedir=/var/cache/"+package_manager+"/$basearch/$releasever")
array.append("reposdir="+build_dir+"/etc/yum.repos.d")
array.append("pluginconfpath="+build_dir+"/etc/"+package_manager+"/plugins")
if nodocs == 1:
array.append("tsflags=nodocs")
if len(http_proxy) > 0:
array.append("proxy="+http_proxy)
array.append('')
result = "\n".join(array)
return result
def create_nodocs_plugin(self, target_lang, package_manager):
array=[]
array.append("[main]")
array.append("# all installed "+package_manager+" plugins are enabled by default")
array.append("# to disable this plugin use \"--disableplugin=langpacks\" to "+package_manager+" command.")
array.append("")
array.append("# langpacks plugin is used when any of following is available:")
array.append("# - any previously installed langpacks (stored in /var/lib/dnf/plugins/installed_langpacks)")
array.append("# - any languages specified by $LANGUAGE")
array.append("# - any langpacks listed in langpack_locales below")
array.append("# -- if this variable is empty, the value of $LANG is considered")
array.append("")
array.append("#langpack_locales = ja, zh_CN, cs, pt_BR, mr")
array.append("# Added by Anaconda")
array.append("langpack_locales="+target_lang)
array.append("enabled=1")
array.append('')
result = "\n".join(array)
# print(result)
return result
def rpm_target_lang(self, target_lang):
if isinstance(target_lang, list):
new_list=[]
for item in target_lang:
new_list.append(item.replace('.UTF-8','.utf8'))
target_lang=':'.join(new_list)
#print(target_lang)
else:
target_lang = target_lang.replace('.UTF-8','.utf8')
array=[]
array.append('# A colon separated list of desired locales to be installed;')
array.append('# "all" means install all locale specific files.')
array.append('# Example: %_install_langs cs_CZ.utf8:cs_CZ:cs:en_US.utf8:en_US:en')
array.append('')
array.append("%_install_langs\t"+target_lang)
array.append('')
result = "\n".join(array)
#print(result)
#sys.exit(0)
return result
def install_distribution(self, package_manager, target_os_version, install_root, repo_list, package_list, build_dir):
self.test=""
array=[]
array.append(package_manager)
array.append("-y")
array.append("-c")
array.append(build_dir+"/etc/"+package_manager+".conf")
array.append("--releasever="+str(target_os_version))
array.append("--nogpg")
array.append("--installroot="+install_root)
array.append("--disablerepo=*")
array.extend(["--enablerepo="+repo for repo in repo_list])
array.append("install")
array.extend(package_list)
return array
def create_repo_url(self,repo_var,baseurl):
if baseurl != "":
return baseurl
return "metalink=https://mirrors.fedoraproject.org/metalink?repo="+repo_var+"$releasever&arch=$basearch"
def install_yum_repo(self,repo_short_name, baseurl=""):
if repo_short_name == "fedora":
repo_name = "Fedora $releasever - $basearch"
baseurl = self.create_repo_url("fedora-", baseurl)
if repo_short_name == "updates":
repo_name = "Fedora $releasever - $basearch - Updates"
baseurl = self.create_repo_url("updates-released-f", baseurl)
if repo_short_name == "updates-testing":
repo_name = "Fedora $releasever - $basearch - Test Updates"
baseurl = self.create_repo_url("updates-testing-f",baseurl)
array=[]
array.append("["+repo_short_name+"]")
array.append("name="+repo_name)
array.append("failovermethod=priority")
array.append(baseurl)
array.append("enabled=1")
array.append("metadata_expire=1h")
array.append("gpgcheck=1")
array.append("gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-$releasever-$basearch")
array.append("skip_if_unavailable=False")
result = "\n".join(array)
return result
def install_yum_repo_centos(self):
result = """
[centos-base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0
#released updates
[centos-updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0
#additional packages that may be useful
[centos-extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0
#additional packages that extend functionality of existing packages
[centos-centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
"""
return result
def execute(self, cmd):
# print("HERE!")
# print(cmd)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
out = process.stdout.readline()
if out == b'' and process.poll() != None:
break
if out != b'':
print(out.decode('utf-8'), end="")
def current_dir(self):
return os.getcwd()
def tofile(self, content, filename):
with open(filename, "w") as f:
f.write(content)
def copy(self, wildcard, dest_dir):
# print(wildcard)
for file in glob.glob(wildcard):
# print("File: "+file)
shutil.copy(file, dest_dir)
def merge_recursive(target, source):
for key in source:
value = source[key]
# Dictionaries in dictionaries need special treatment
if key in target and isinstance(value, dict):
tmp_target = target[key]
merge_recursive(tmp_target,value)
target[key] = tmp_target
else:
target[key] = value
def merge_config(filename, configuration):
if os.path.exists(filename):
f = open(filename, 'r')
y = yaml.load(f)
f.close()
merge_recursive(configuration, y)
class Patch:
def __init__(self):
pass
def apply(self, target_lang, target_package_manager, install_dir, nodocs, proxy_url):
self.install_dir = install_dir
self.target_lang = target_lang
if target_package_manager == "dnf":
self.dnf_conf(nodocs,proxy_url)
elif target_package_manager == "yum":
self.yum_conf(nodocs,proxy_url)
content = self.locale_content()
# print(content)
content = self.adjtime_content()
# print(content)
self.locale_conf()
self.adjtime()
self.clean(install_dir, target_package_manager)
def locale_conf(self, filename="/etc/locale.conf"):
print("Patching /etc/locale.conf")
content = self.locale_content()
self.tofile(content, self.install_dir + filename)
def adjtime(self, filename="/etc/adjtime"):
print("Patching /etc/adjtime")
content = self.adjtime_content()
self.tofile(content, self.install_dir + filename)
def dnf_conf(self, nodocs, proxy, filename="etc/dnf/dnf.conf"):
print("Patching /etc/dnf/dnf.conf")
configParser = configparser.ConfigParser()
fullpath = os.path.join(self.install_dir, filename)
if not os.path.isfile(fullpath):
return
configParser.read(fullpath)
if nodocs == 1:
configParser.set('main', 'tsflags', 'nodocs')
if len(proxy) > 0:
configParser.set('main', 'proxy', proxy)
out = open(fullpath, 'w')
configParser.write(out, space_around_delimiters=False)
out.close()
def yum_conf(self, nodocs, proxy, filename="etc/yum.conf"):
print("Patching /"+filename)
configParser = configparser.ConfigParser()
fullpath = os.path.join(self.install_dir, filename)
print(fullpath)
configParser.read(fullpath)
if nodocs == 1:
configParser.set('main', 'tsflags', 'nodocs')
if len(proxy) > 0:
configParser.set('main', 'proxy', proxy)
out = open(fullpath, 'w')
configParser.write(out, space_around_delimiters=False)
out.close()
def tofile(self, content, filename):
with open(filename, "w") as f:
f.write(content)
def locale_content(self):
if isinstance(self.target_lang, list):
# Policy: Pick first language
return "LANG=\""+self.target_lang[0]+"\"\n"
else:
return "LANG=\""+self.target_lang+"\"\n"
def adjtime_content(self):
return "0.0 0 0.0\n0\nUTC\n"
def clean(self,install_root, package_manager):
self.test=""
array = ['find', install_root+'/var/lib/'+package_manager+'/history', '-type' , 'f', '-exec', 'rm', '{}', ';']
print(array)
subprocess.call(array)
array = ['find', install_root+'/var/lib/'+package_manager+'/yumdb', '-mindepth','2', '-maxdepth','2', '-type' , 'd', '-exec', 'rm', '-rf', '{}', ';']
print(array)
subprocess.call(array)
array = ['find', install_root+'/var/cache/'+package_manager, '-type' , 'f', '-exec', 'rm', '{}', ';']
print(array)
subprocess.call(array)
log_dir_wildcard = install_root+"/var/log/"+package_manager+"*.log"
for file in glob.glob(log_dir_wildcard):
print(file)
os.remove(file)
log_dir_wildcard = install_root+"/var/log/hawkey.log"
for file in glob.glob(log_dir_wildcard):
print(file)
os.remove(file)
log_dir_wildcard = install_root+"/var/log/lastlog"
for file in glob.glob(log_dir_wildcard):
print(file)
os.remove(file)
subprocess.call(['touch', log_dir_wildcard])
class Installer:
# def __init__(self, default_configuration):
# pass
def prepare_redhat_distribution(self,configuration, work,target,os_name,os_version):
rpm = RedhatPackageManager()
yum_repos_dir = os.path.join(work.build_dir, "etc", "yum.repos.d")
repo_conf_file = os.path.join(work.build_dir, "etc", target.package_manager+".conf")
home_dir = os.path.join(work.build_dir, "root")
rpm_build_file = os.path.join(home_dir, ".rpmmacros")
rpm_dir = os.path.join(work.install_dir, "etc", "rpm")
rpm_conf_file = os.path.join(work.install_dir, "etc", "rpm", "image-language.conf")
for dir in [ work.install_dir, yum_repos_dir, home_dir, rpm_dir]:
print(dir)
rpm.mkdir_p(dir)
print(repo_conf_file)
print(rpm_build_file)
print(rpm_conf_file)
#rpm.mkdir_p(yum_repos_dir)
# FIXME need to create all of the configs
#print(work.http_proxy)
#sys.exit(0)
content = rpm.create_package_manager_conf_file(target.package_manager, work.build_dir, work.http_proxy, target.nodocs)
#print(content)
#exit(1)
rpm.tofile(content, repo_conf_file)
repo_url = {}
if "repo_url" in configuration["target"]:
repo_url = configuration["target"]["repo_url"]
if os_name == "fedora":
for repo_name in target.repo_list:
url=""
if repo_name in repo_url:
url="baseurl="+repo_url[repo_name]
#print(url)
content = rpm.install_yum_repo(repo_name, url)
rpm.tofile(content, os.path.join(yum_repos_dir, repo_name+".repo" ))
elif os_name == "centos":
content = rpm.install_yum_repo_centos()
rpm.tofile(content, os.path.join(yum_repos_dir, "fedora-updates-testing.repo"))
# lang_all = 0 (FALSE) --> install only specific languages
if target.lang_all == 0:
rpm.mkdir_p(rpm_dir)
rpm.mkdir_p(home_dir)
content = rpm.rpm_target_lang(target.lang)
rpm.tofile(content, os.path.join(rpm_dir ,"macros.image-language.conf"))
rpm.tofile(content, os.path.join(home_dir,".rpmmacros"))
cmd = rpm.install_distribution(
target.package_manager,
target.os_version,
work.install_dir,
target.repo_list,
target.package_list,
work.build_dir
)
return cmd
def prepare_alpine_distribution(self, configuration, work, target):
apm = AlpinePackageManager()
array = ['apk']
for repo in target.repo_list:
array.extend(["--repository", repo])
array.extend([ '--root', work.install_dir , '--allow-untrusted', '--update-cache' , '--initdb', '--no-progress', 'add', 'alpine-base' ])
cmd=array
return cmd
def populate_build_version(self, build_version_format, work,os_name,os_version):
build_version_format = build_version_format.replace("%build_datetime%", work['build_datetime'])
build_version_format = build_version_format.replace("%os_name%", os_name )
build_version_format = build_version_format.replace("%os_version%", str(os_version))
return build_version_format
def create_dirs(self, pmb, install_dir, dirs):
if not "dirs" in dirs:
return
for dir in dirs["dirs"]:
if dir[0] == '/':
dir = dir[1:]
target_dir = os.path.join(install_dir,dir)
print(target_dir)
pmb.mkdir_p(target_dir)
def create_symlinks(self, pmb, install_dir, dirs):
if not "symlinks" in dirs:
return
for symlink in dirs["symlinks"]:
for link in dirs["symlinks"][symlink]:
if link[0] == '/':
link = link[1:]
target = os.path.join(install_dir,link)
print(target)
pmb.symlink(symlink,target)
def main(self, default_configuration, config_file=""):
configuration = default_configuration.copy()
osrelease = OsRelease()
locale = Locale()
pmb = PackageManagerBase()
package_manager = pmb.determine_package_manager(osrelease.ID, osrelease.VERSION_ID)
host_configuration = {
"host" : {
"os_name" : osrelease.ID,
"os_version" : osrelease.VERSION_ID,
"lang" : locale.LANG,
"package_manager" : package_manager,
},
"target" : {
"os_name" : osrelease.ID,
"os_version" : osrelease.VERSION_ID,
"package_manager" : package_manager,
},
"work": {
# "build_root" : "/var/lib/build",
"build_datetime" : "%Y%m%d%H%M",
"http_proxy" : '',
}
}
merge_recursive(configuration, host_configuration)
filename = "image.yaml"
# Merge configs found in "/etc" local or in "etc", "." relative to the script directory
for dir_prefix in [ "/etc" , os.path.join(sys.path[0], "etc"), sys.path[0] ]:
fullpath = os.path.join(dir_prefix, filename)
merge_config(fullpath, configuration)
if config_file != "":
fullpath = os.path.abspath(config_file)
merge_config(fullpath, configuration)
target = configuration['target']
os_name = target['os_name']
os_version = target['os_version']
if not 'repo_list' in target:
target['repo_list'] = pmb.get_repository_list(os_name,os_version)
if not 'repo_list_add' in target:
pass # FIXME
if not 'package_list' in target:
target['package_list'] = pmb.package_list(os_name,os_version)
if not 'package_list_add' in target:
target['package_list_add'] = pmb.package_list_add(os_name,os_version)
configuration['target']=target
target = DictToObject(configuration['target'])
work = configuration['work']
work['build_dir'] = os.path.join(configuration['work']['build_root'], target.os_name +"-" + str(target.os_version), target.profile)
work['install_dir'] = os.path.join(work['build_dir'],"install")
work['build_datetime'] = datetime.datetime.today().strftime(work['build_datetime'])
configuration['work']= work
if "docker" in configuration:
image_name=configuration["docker"]["image"]
image_name = image_name.replace("%os_name%", os_name)
image_name = image_name.replace("%os_version%", str(os_version))
image_name = image_name.replace("%profile%", target.profile)
image_name = image_name.replace("%build_version%", self.populate_build_version("%os_name%-%os_version%-%build_datetime%",work,os_name,os_version))
image_name = image_name.replace("%build_datetime%", work['build_datetime'])
configuration["docker"]["image"] = image_name
val=yaml.dump(configuration, explicit_start=True,indent=2, default_flow_style=False)
print(val)
work = DictToObject(configuration['work'])
pmb.mkdir_p(work.install_dir)
dirs = { "target" : {
"dirs": {
"/bin": {
"mode": "0666",
"owner": "root",
"group": "root"
},
"/ftp": {
"mode": "0666",
"owner": "root",
"group": "root"
}
}}}
#sys.exit(0)
if os_name == "alpine":
cmd = self.prepare_alpine_distribution(configuration,work,target)
else:
cmd = self.prepare_redhat_distribution(configuration,work,target,os_name,os_version)
print(cmd)
return_code = pmb.execute2(cmd, work.build_dir+"/root")
if return_code != 0:
sys.exit(1)
Patch().apply(target.lang, target.package_manager,work.install_dir,target.nodocs, target.proxy)
self.create_dirs(pmb, work.install_dir,configuration['target'])
self.create_symlinks(pmb, work.install_dir,configuration['target'])
if os_name == "fedora":
cmd = [ 'chroot', work.install_dir, 'rpm', '--import', '/etc/pki/rpm-gpg/RPM-GPG-KEY-'+os_name+'-'+str(os_version)+'-primary' ]
print(" ".join(cmd))
return_code = pmb.execute2(cmd, "/root")
print(return_code)
if "docker" in configuration:
image_name=configuration["docker"]["image"]
print("Creating image: "+image_name)
#a="cd \"" + work.install_dir + "\" && tar -c . |docker import - \""+image_name+"\""
#subprocess.call(a, shell=True)
cmd="tar -c . |docker import - \""+image_name+"\""
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT, cwd=work.install_dir)
output = ps.communicate()[0]
output = output.decode('utf-8').rstrip()
if ps.returncode != 0:
sys.exit(10)
#digest, image_id = output.split(':')
#print(image_id)
print(output)
image_prefix = image_name.split(':')[0]
cmd = 'docker tag ' + image_name + ' ' + image_prefix + ':latest'
print(cmd)
subprocess.call(cmd, shell=True)
def parse_cmdline():
parser = argparse.ArgumentParser("imagebuild")
parser.add_argument('argv', metavar='argv', nargs='*', help='file')
parser.add_argument('--build-root', metavar='build_root', default='/var/lib/build', help='build_root')
parsed_args = parser.parse_args()
return parsed_args
default_configuration = {
"version": "1.0",
"target": {
"lang": 'en_US.UTF-8',
"lang_all": 0,
"nodocs": 1,
"profile": "default",
"lang": "en_US.UTF-8",
"lang_all": 0,
"profile": 'full',
"proxy": "",
},
"work": {
"build_root" : "/var/lib/build",
}
}
if __name__ == "__main__":
if os.geteuid() != 0:
exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
parsed_args = parse_cmdline()
#print(parsed_args)
if parsed_args.build_root:
default_configuration['work']['build_root']=parsed_args.build_root
install=Installer()
if len(parsed_args.argv) > 0:
install.main(default_configuration, parsed_args.argv[0])
else:
install.main(default_configuration, "")