forked from rpm-py-installer/rpm-py-installer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.py
2211 lines (1846 loc) · 74.7 KB
/
install.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
"""Classes for all of install.
Import only standard modules to run install.py directly.
"""
import contextlib
import fnmatch
import glob
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from distutils.spawn import find_executable
from distutils.sysconfig import get_python_lib
class Application(object):
"""A class for main applicaton logic."""
def __init__(self):
"""Initialize this class."""
self._load_options_from_env()
def run(self):
"""Run install process."""
try:
self.linux.verify_system_status()
except InstallSkipError:
Log.info('Install skipped.')
return
work_dir = tempfile.mkdtemp(suffix='-rpm-py-installer')
Log.info("Created working directory '{0}'".format(work_dir))
with Cmd.pushd(work_dir):
self.rpm_py.download_and_install()
if not self.python.is_python_binding_installed():
message = (
'RPM Python binding failed to install '
'with unknown reason.'
)
raise InstallError(message)
# TODO: Print installed module name and version as INFO.
if self.is_work_dir_removed:
shutil.rmtree(work_dir)
Log.info("Removed working directory '{0}'".format(work_dir))
else:
Log.info("Saved working directory '{0}'".format(work_dir))
def _load_options_from_env(self):
verbose = os.environ.get('RPM_PY_VERBOSE') == 'true'
# Set it as early as possible for other functions.
self.verbose = verbose
Log.verbose = verbose
# Install RPM Python binding from binary package?
is_installed_from_bin = False
if os.environ.get('RPM_PY_INSTALL_BIN') == 'true':
is_installed_from_bin = True
# Install the Python binding on the system Python?
# Default: false
sys_installed = False
if 'RPM_PY_SYS' in os.environ:
sys_installed = os.environ.get('RPM_PY_SYS') == 'true'
# Python's path that the module is installed on.
python = Python()
# Linked rpm's path. Default: rpm.
rpm_path = os.environ.get('RPM_PY_RPM_BIN', 'rpm')
rpm_path = Cmd.which(rpm_path)
if not rpm_path:
raise InstallError('rpm command not found. Install rpm.')
if not rpm_path.endswith('rpm'):
raise InstallError('Invalid rpm_path: {0}'.format(rpm_path))
linux = Linux.get_instance(python=python, rpm_path=rpm_path,
sys_installed=sys_installed)
# Installed RPM Python module's version.
# Default: Same version with rpm.
rpm_py_version_str = None
if 'RPM_PY_VERSION' in os.environ:
rpm_py_version_str = os.environ.get('RPM_PY_VERSION')
else:
rpm_py_version_str = linux.rpm.version
# Git branch name. Default: None
git_branch = None
if 'RPM_PY_GIT_BRANCH' in os.environ:
git_branch = os.environ.get('RPM_PY_GIT_BRANCH')
# Use optimized setup.py?
# Default: true
optimized = True
if 'RPM_PY_OPTM' in os.environ:
optimized = os.environ.get('RPM_PY_OPTM') == 'true'
is_work_dir_removed = True
if 'RPM_PY_WORK_DIR_REMOVED' in os.environ:
is_work_dir_removed = \
os.environ.get('RPM_PY_WORK_DIR_REMOVED') == 'true'
self.python = python
self.linux = linux
self.rpm_py = RpmPy(rpm_py_version_str, python, linux,
is_installed_from_bin=is_installed_from_bin,
git_branch=git_branch,
optimized=optimized,
verbose=verbose)
self.is_work_dir_removed = is_work_dir_removed
class RpmPy(object):
"""A class for RPM Python binding."""
def __init__(self, version, python, linux, **kwargs):
"""Initialize this class."""
if not version:
raise ValueError('version required.')
if not python:
raise ValueError('python required.')
if not linux:
raise ValueError('linux required.')
if not isinstance(version, str):
ValueError('version invalid instance.')
if not isinstance(python, Python):
ValueError('python invalid instance.')
if not isinstance(linux, Linux):
ValueError('linux invalid instance.')
is_installed_from_bin = kwargs.get('is_installed_from_bin', False)
git_branch = kwargs.get('git_branch')
optimized = kwargs.get('optimized', True)
verbose = kwargs.get('verbose', False)
rpm_py_version = RpmPyVersion(version)
self.version = rpm_py_version
self.is_installed_from_bin = is_installed_from_bin
self.downloader = Downloader(rpm_py_version, git_branch=git_branch)
self.installer = linux.create_installer(rpm_py_version,
optimized=optimized,
verbose=verbose)
def download_and_install(self):
"""Download and install RPM Python binding."""
if self.is_installed_from_bin:
try:
self.installer.install_from_rpm_py_package()
return
except RpmPyPackageNotFoundError as exc:
Log.warn('RPM Py Package not found. reason: {0}'.format(exc))
# Download and install from the source.
top_dir_name = self.downloader.download_and_expand()
rpm_py_dir = os.path.join(top_dir_name, 'python')
setup_py_in_found = False
with Cmd.pushd(rpm_py_dir):
if self.installer.setup_py.exists_in_path():
setup_py_in_found = True
self.installer.run()
if not setup_py_in_found:
self.installer.install_from_rpm_py_package()
class RpmPyVersion(object):
"""A class to manage RPM Python binding version."""
def __init__(self, version, **kwargs):
"""Initialize this class."""
if not version:
ValueError('version required.')
if not isinstance(version, str):
ValueError('version invalid instance.')
self.version = version
def __str__(self):
"""Return the string expression of this class."""
return self.version
@property
def info(self):
"""RPM Python binding's version info."""
version_str = self.version
return Utils.version_str2tuple(version_str)
@property
def is_release(self):
"""Release version or not."""
# version string: N.N.N.N is for release.
return bool(re.match(r'^[\d.]+$', self.version))
@property
def git_branch(self):
"""Git branch name."""
info = self.info
return 'rpm-{major}.{minor}.x'.format(
major=info[0], minor=info[1])
class SetupPy(object):
"""A class for the RPM Python binding's setup.py file.
It does parsing and patching for setup.py file.
"""
PATCHES_DEFAULT = [
# Use setuptools to prevent deprecation message when uninstalling.
# https://github.com/rpm-software-management/rpm/pull/323
{
'src': r'\nfrom distutils.core import setup, Extension *?\n',
'dest': '''
import sys
if sys.version_info >= (3, 0):
try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
else:
from distutils.core import setup, Extension
''',
'required': True,
},
# Support Python 2.6. subprocess.check_output is new in Python 2.7.
{
'src': r'\n pcout = subprocess\.check_output\(cmd.split\(\)\)\.decode\(\) *?\n', # NOQA
'dest': '''
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
pcout, _ = p.communicate()
pcout = pcout.decode()
''',
'required': True,
},
]
# RPM version < 4.12
# https://github.com/rpm-software-management/rpm/commit/f996665
PATCHS_ADD_EXTRA_LINK_ARGS = [
{
'src': r'\nimport subprocess\n',
'dest': '''
import subprocess
import os
'''
},
{
'src': r'\ncflags = \[.*\]\n',
'dest': '''
cflags = ['-std=c99']
additional_link_args = []
# See if we're building in-tree
if os.access('Makefile.am', os.F_OK):
cflags.append('-I../include')
additional_link_args.extend(['-Wl,-L../rpmio/.libs',
'-Wl,-L../lib/.libs',
'-Wl,-L../build/.libs',
'-Wl,-L../sign/.libs'])
os.environ['PKG_CONFIG_PATH'] = '..'
'''
},
{
'src': r'''
extra_compile_args = cflags
''',
'dest': '''
extra_compile_args = cflags,
extra_link_args = additional_link_args
'''
},
]
IN_PATH = 'setup.py.in'
OUT_PATH = 'setup.py'
def __init__(self, version, **kwargs):
"""Initialize this class."""
if not version:
ValueError('version required.')
if not isinstance(version, RpmPyVersion):
ValueError('version invalid instance.')
self.version = version
self.replaced_word_dict = {
'@PACKAGE_NAME@': 'rpm',
'@VERSION@': version.version,
'@PACKAGE_BUGREPORT@': '[email protected]',
}
optimized = kwargs.get('optimized', True)
patches = []
if optimized:
patches = self.PATCHES_DEFAULT
if version.info < (4, 12):
patches.extend(self.PATCHS_ADD_EXTRA_LINK_ARGS)
self.patches = patches
def exists_in_path(self):
"""Return if setup.py.in exists.
If RPM version >= 4.10.0-beta1, setup.py.in exist.
otherwise RPM version <= 4.9.x, setup.py.in does not exist.
"""
return os.path.isfile(self.IN_PATH)
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir):
"""Add patches to remove pkg-config command and rpm.pc part.
Replace with given library_path: lib_dir and include_path: include_dir
without rpm.pc file.
"""
additional_patches = [
{
'src': r"pkgconfig\('--libs-only-L'\)",
'dest': "['{0}']".format(lib_dir),
},
# Considering -libs-only-l and -libs-only-L
# https://github.com/rpm-software-management/rpm/pull/327
{
'src': r"pkgconfig\('--libs(-only-l)?'\)",
'dest': "['rpm', 'rpmio']",
'required': True,
},
{
'src': r"pkgconfig\('--cflags'\)",
'dest': "['{0}']".format(include_dir),
'required': True,
},
]
self.patches.extend(additional_patches)
def apply_and_save(self):
"""Apply replaced words and patches, and save setup.py file."""
patches = self.patches
content = None
with open(self.IN_PATH) as f_in:
# As setup.py.in file size is 2.4 KByte.
# it's fine to read entire content.
content = f_in.read()
# Replace words.
for key in self.replaced_word_dict:
content = content.replace(key, self.replaced_word_dict[key])
# Apply patches.
out_patches = []
for patch in patches:
pattern = re.compile(patch['src'], re.MULTILINE)
(content, subs_num) = re.subn(pattern, patch['dest'],
content)
if subs_num > 0:
patch['applied'] = True
out_patches.append(patch)
for patch in out_patches:
if patch.get('required') and not patch.get('applied'):
Log.warn('Patch not applied {0}'.format(patch['src']))
with open(self.OUT_PATH, 'w') as f_out:
f_out.write(content)
self.patches = out_patches
# Release content data to make it released by GC quickly.
content = None
class Downloader(object):
"""A class to download RPM Python binding."""
# rpm.org
RPM_ORG_BASE_URL = 'http://ftp.rpm.org/releases'
RPM_ORG_ARCHIVE_URL_FORMAT = (
RPM_ORG_BASE_URL + '/{branch_name}/rpm-{version}.tar.gz'
)
RPM_ORG_ARCHIVE_TOP_DIR_NAME_FORMAT = 'rpm-{version}'
# github
RPM_GIT_HUB_BASE_URL = 'https://github.com/rpm-software-management/rpm'
RPM_GIT_HUB_REPO_URL = '{0}.git'.format(RPM_GIT_HUB_BASE_URL)
RPM_GIT_HUB_ARCHIVE_URL_FORMAT = (
RPM_GIT_HUB_BASE_URL + '/archive/{tag_name}.tar.gz'
)
RPM_GIT_HUB_ARCHIVE_TOP_DIR_NAME_FORMAT = 'rpm-{tag_name}'
def __init__(self, rpm_py_version, **kwargs):
"""Initialize this class."""
if not rpm_py_version:
ValueError('rpm_py_version required.')
if not isinstance(rpm_py_version, RpmPyVersion):
ValueError('rpm_py_version invalid instance.')
self.rpm_py_version = rpm_py_version
self.git_branch = kwargs.get('git_branch')
def download_and_expand(self):
"""Download and expand RPM Python binding."""
top_dir_name = None
if self.git_branch:
# Download a source by git clone.
top_dir_name = self._download_and_expand_by_git()
else:
# Download a source from the arcihve URL.
# Downloading the compressed archive is better than "git clone",
# because it is faster.
# If download failed due to URL not found, try "git clone".
try:
top_dir_name = self._download_and_expand_from_archive_url()
except RemoteFileNotFoundError:
Log.info('Try to download by git clone.')
top_dir_name = self._download_and_expand_by_git()
return top_dir_name
def _download_and_expand_from_archive_url(self):
archive_dicts = self._get_candidate_archive_dicts()
max_num = len(archive_dicts)
found_index = None
for index, archive_dict in enumerate(archive_dicts):
url = archive_dict['url']
Log.info("Downloading archive. '{0}'.".format(url))
try:
Cmd.curl_remote_name(url)
except RemoteFileNotFoundError as exc:
Log.info('Archive not found. URL: {0}'.format(url))
if index + 1 < max_num:
Log.info('Try to download next candidate URL.')
else:
raise exc
else:
found_index = index
break
found_archive_dict = archive_dicts[found_index]
archive_file_name = os.path.basename(found_archive_dict['url'])
Cmd.tar_extract(archive_file_name)
return found_archive_dict['top_dir_name']
def _get_candidate_archive_dicts(self):
archive_dicts = []
tag_names = self._predict_candidate_git_tag_names()
for tag_name in tag_names:
url = self._get_git_hub_archive_url(tag_name)
top_dir_name = self._get_git_hub_archive_top_dir_name(tag_name)
archive_dicts.append({
'site': 'github',
'url': url,
'top_dir_name': top_dir_name,
})
# Set rpm.org server as a secondary server, because it takes long time
# to download an archive. GitHub is better to download the archive.
if self.rpm_py_version.is_release:
url = self._get_rpm_org_archive_url()
top_dir_name = self._get_rpm_org_archive_top_dir_name()
archive_dicts.append({
'site': 'rpm.org',
'url': url,
'top_dir_name': top_dir_name,
})
return archive_dicts
def _get_rpm_org_archive_url(self):
url = self.RPM_ORG_ARCHIVE_URL_FORMAT.format(
branch_name=self.rpm_py_version.git_branch,
version=self.rpm_py_version.version,
)
return url
def _get_rpm_org_archive_top_dir_name(self):
top_dir_name = self.RPM_ORG_ARCHIVE_TOP_DIR_NAME_FORMAT.format(
version=self.rpm_py_version.version
)
return top_dir_name
def _get_git_hub_archive_url(self, tag_name):
url = self.RPM_GIT_HUB_ARCHIVE_URL_FORMAT.format(
tag_name=tag_name
)
return url
def _get_git_hub_archive_top_dir_name(self, tag_name):
top_dir_name = self.RPM_GIT_HUB_ARCHIVE_TOP_DIR_NAME_FORMAT.format(
tag_name=tag_name
)
return top_dir_name
def _download_and_expand_by_git(self):
self._do_git_clone()
return 'rpm'
def _predict_candidate_git_tag_names(self):
version = self.rpm_py_version.version
name_release = 'rpm-{0}-release'.format(version)
name_non_release = 'rpm-{0}'.format(version)
tag_names = None
if self.rpm_py_version.is_release:
tag_names = [
name_release,
name_non_release,
]
else:
tag_names = [
name_non_release,
name_release,
]
return tag_names
def _do_git_clone(self):
if not Cmd.which('git'):
raise InstallError('git command not found. Install git.')
branch = None
if self.git_branch:
branch = self.git_branch
else:
branch = self._predict_git_branch()
git_clone_cmd = 'git clone -b {branch} --depth=1 {repo_url}'.format(
branch=branch,
repo_url=self.RPM_GIT_HUB_REPO_URL,
)
Log.info("Downloading source by git clone. 'branch: {0}'".format(
branch))
_, stderr = Cmd.sh_e(git_clone_cmd)
# Verify stderr message in addition.
# Old git (at least v1.7.1) does not return non zero exist status,
# when running "git clone -b branch" and the branch is not found.
# https://github.com/git/git/tree/master/Documentation/RelNotes
if re.match(r'warning: Remote branch [^ ]+ not found', stderr,
re.MULTILINE):
message_format = (
'fatal: Remote branch {0} not '
'found in upstream origin.'
)
raise InstallError(message_format.format(branch))
def _predict_git_branch(self):
git_branch = None
version_info = self.rpm_py_version.info
stable_branch = 'rpm-{major}.{minor}.x'.format(
major=version_info[0],
minor=version_info[1],
)
git_ls_remote_cmd = 'git ls-remote --heads {repo_url} {branch}'.format(
repo_url=self.RPM_GIT_HUB_REPO_URL,
branch=stable_branch,
)
stdout = Cmd.sh_e_out(git_ls_remote_cmd)
if stable_branch in stdout:
git_branch = stable_branch
else:
git_branch = 'master'
return git_branch
class Installer(object):
"""A class to install RPM Python binding."""
def __init__(self, rpm_py_version, python, rpm, **kwargs):
"""Initialize this class."""
if not rpm_py_version:
ValueError('rpm_py_version required.')
if not python:
ValueError('python required.')
if not rpm:
ValueError('rpm required.')
if not isinstance(rpm_py_version, RpmPyVersion):
ValueError('rpm_py_version invalid instance.')
if not isinstance(python, Python):
ValueError('python invalid instance.')
if not isinstance(rpm, Rpm):
ValueError('rpm invalid instance.')
optimized = kwargs.get('optimized', True)
verbose = kwargs.get('verbose', False)
self.rpm_py_version = rpm_py_version
self.python = python
self.rpm = rpm
self.setup_py = SetupPy(rpm_py_version, optimized=optimized)
self.setup_py_opts = '-v' if verbose else '-q'
self.optimized = optimized
# Implement these variables on sub class.
self.package_sys_name = None
self.package_popt_name = None
self.package_popt_devel_name = None
def run(self):
"""Run install main logic."""
self._make_lib_file_symbolic_links()
self._copy_each_include_files_to_include_dir()
self._make_dep_lib_file_sym_links_and_copy_include_files()
self.setup_py.add_patchs_to_build_without_pkg_config(
self.rpm.lib_dir, self.rpm.include_dir
)
self.setup_py.apply_and_save()
self._build_and_install()
def install_from_rpm_py_package(self):
"""Run install from RPM Python binding system package.
It is run when RPM does not have setup.py.in in the source
such as the RPM source is old.
"""
raise NotImplementedError('Implement this method.')
def _make_lib_file_symbolic_links(self):
"""Make symbolic links for lib files.
Make symbolic links from system library files or downloaded lib files
to downloaded source library files.
For example, case: Fedora x86_64
Make symbolic links
from
a. /usr/lib64/librpmio.so* (one of them)
b. /usr/lib64/librpm.so* (one of them)
c. If rpm-build-libs package is installed,
/usr/lib64/librpmbuild.so* (one of them)
otherwise, downloaded and extracted rpm-build-libs.
./usr/lib64/librpmbuild.so* (one of them)
c. If rpm-build-libs package is installed,
/usr/lib64/librpmsign.so* (one of them)
otherwise, downloaded and extracted rpm-build-libs.
./usr/lib64/librpmsign.so* (one of them)
to
a. rpm/rpmio/.libs/librpmio.so
b. rpm/lib/.libs/librpm.so
c. rpm/build/.libs/librpmbuild.so
d. rpm/sign/.libs/librpmsign.so
.
This is a status after running "make" on actual rpm build process.
"""
so_file_dict = {
'rpmio': {
'sym_src_dir': self.rpm.lib_dir,
'sym_dst_dir': 'rpmio/.libs',
'require': True,
},
'rpm': {
'sym_src_dir': self.rpm.lib_dir,
'sym_dst_dir': 'lib/.libs',
'require': True,
},
'rpmbuild': {
'sym_src_dir': self.rpm.lib_dir,
'sym_dst_dir': 'build/.libs',
'require': True,
},
'rpmsign': {
'sym_src_dir': self.rpm.lib_dir,
'sym_dst_dir': 'sign/.libs',
},
}
self._update_sym_src_dirs_conditionally(so_file_dict)
for name in so_file_dict:
so_dict = so_file_dict[name]
pattern = 'lib{0}.so*'.format(name)
so_files = Cmd.find(so_dict['sym_src_dir'], pattern)
if not so_files:
is_required = so_dict.get('require', False)
if not is_required:
message_format = (
"Skip creating symbolic link of "
"not existing so file '{0}'"
)
Log.debug(message_format.format(name))
continue
message = 'so file pattern {0} not found at {1}'.format(
pattern, so_dict['sym_src_dir']
)
raise InstallError(message)
sym_dst_dir = os.path.abspath('../{0}'.format(
so_dict['sym_dst_dir']))
if not os.path.isdir(sym_dst_dir):
Cmd.mkdir_p(sym_dst_dir)
cmd = 'ln -sf {0} {1}/lib{2}.so'.format(so_files[0],
sym_dst_dir,
name)
Cmd.sh_e(cmd)
def _update_sym_src_dirs_conditionally(self, so_file_dict):
pass
def _copy_each_include_files_to_include_dir(self):
"""Copy include header files for each directory to include directory.
Copy include header files
from
rpm/
rpmio/*.h
lib/*.h
build/*.h
sign/*.h
to
rpm/
include/
rpm/*.h
.
This is a status after running "make" on actual rpm build process.
"""
src_header_dirs = [
'rpmio',
'lib',
'build',
'sign',
]
with Cmd.pushd('..'):
src_include_dir = os.path.abspath('./include')
for header_dir in src_header_dirs:
if not os.path.isdir(header_dir):
message_format = "Skip not existing header directory '{0}'"
Log.debug(message_format.format(header_dir))
continue
header_files = Cmd.find(header_dir, '*.h')
for header_file in header_files:
pattern = '^{0}/'.format(header_dir)
(dst_header_file, subs_num) = re.subn(pattern,
'', header_file)
if subs_num == 0:
message = 'Failed to replace header_file: {0}'.format(
header_file)
raise ValueError(message)
dst_header_file = os.path.abspath(
os.path.join(src_include_dir, 'rpm', dst_header_file)
)
dst_dir = os.path.dirname(dst_header_file)
if not os.path.isdir(dst_dir):
Cmd.mkdir_p(dst_dir)
shutil.copyfile(header_file, dst_header_file)
def _make_dep_lib_file_sym_links_and_copy_include_files(self):
"""Make symbolick links for lib files and copy include files.
Do below steps for a dependency packages.
Dependency packages
- popt-devel
Steps
1. Make symbolic links from system library files or downloaded lib
files to downloaded source library files.
2. Copy include header files to include directory.
"""
if not self._rpm_py_has_popt_devel_dep():
message = (
'The RPM Python binding does not have popt-devel dependency'
)
Log.debug(message)
return
if self._is_popt_devel_installed():
message = '{0} package is installed.'.format(
self.package_popt_devel_name)
Log.debug(message)
return
if not self._is_package_downloadable():
message = '''
Install a {0} download plugin or
install the {0} package [{1}].
'''.format(self.package_sys_name, self.package_popt_devel_name)
raise InstallError(message)
if not self._is_popt_installed():
message = '''
Required {0} not installed: [{1}],
Install the {0} package.
'''.format(self.package_sys_name, self.package_popt_name)
raise InstallError(message)
self._download_and_extract_popt_devel()
# Copy libpopt.so to rpm_root/lib/.libs/.
popt_lib_dirs = [
self.rpm.lib_dir,
# /lib64/libpopt.so* installed at popt-1.13-7.el6.x86_64.
'/lib64',
# /lib/*/libpopt.so* installed at libpopt0-1.16-8ubuntu1
'/lib',
]
pattern = 'libpopt.so*'
popt_so_file = None
for popt_lib_dir in popt_lib_dirs:
so_files = Cmd.find(popt_lib_dir, pattern)
if so_files:
popt_so_file = so_files[0]
break
if not popt_so_file:
message = 'so file pattern {0} not found at {1}'.format(
pattern, str(popt_lib_dirs)
)
raise InstallError(message)
cmd = 'ln -sf {0} ../lib/.libs/libpopt.so'.format(
popt_so_file)
Cmd.sh_e(cmd)
# Copy popt.h to rpm_root/include
shutil.copy('./usr/include/popt.h', '../include')
def _build_and_install(self):
python_path = self.python.python_path
Cmd.sh_e('{0} setup.py {1} build'.format(python_path,
self.setup_py_opts))
Cmd.sh_e('{0} setup.py {1} install'.format(python_path,
self.setup_py_opts))
def _rpm_py_has_popt_devel_dep(self):
"""Check if the RPM Python binding has a depndency to popt-devel.
Search include header files in the source code to check it.
popt.h in rpmlib.h was dropped from rpm-4.15.0-alpha in rpmlib.h.
https://github.com/rpm-software-management/rpm/commit/74033a3
popt.h in rpmcli.h was still available from rpm-4.6.0-rc1.
https://github.com/rpm-software-management/rpm/commit/99faa27
"""
found = False
header_files = [
'../include/rpm/rpmcli.h',
'../include/rpm/rpmlib.h',
]
for header_file in header_files:
if not os.path.isfile(header_file):
continue
with open(header_file) as f_in:
for line in f_in:
if re.match(r'^#include .*popt.h.*$', line):
found = True
break
if found:
break
return found
def _is_package_downloadable(self):
"""Check if the package system is downlodable."""
raise NotImplementedError('Implement this method.')
def _is_popt_installed(self):
"""Check if the popt package is installed."""
raise NotImplementedError('Implement this method.')
def _is_popt_devel_installed(self):
"""Check if the popt devel package is installed."""
raise NotImplementedError('Implement this method.')
def _download_and_extract_popt_devel(self):
"""Download and extract popt devel package."""
raise NotImplementedError('Implement this method.')
class NativeRpmInstaller(Installer):
"""A class to install RPM python bindings on OS with native RPM."""
def __init__(self, rpm_py_version, python, rpm, **kwargs):
"""Initialize this class."""
Installer.__init__(self, rpm_py_version, python, rpm, **kwargs)
self.package_sys_name = 'RPM'
self.package_popt_name = 'popt'
self.package_popt_devel_name = 'popt-devel'
def _is_popt_devel_installed(self):
# overrided method.
return self.rpm.is_package_installed(self.package_popt_devel_name)
def _download_and_extract_popt_devel(self):
# overrided method.
self.rpm.download_and_extract(self.package_popt_devel_name)
def _is_package_downloadable(self):
# overrided method.
return self.rpm.is_downloadable()
class SuseInstaller(NativeRpmInstaller):
"""A class to install RPM Python bindings on SUSE based OS."""
def install_from_rpm_py_package(self):
"""Run install from the RPM Python binding RPM package."""
message = '''
Can not install RPM Python binding from the package,
because these must be already present on the system.
'''
raise RpmPyPackageNotFoundError(message)
def _is_popt_installed(self):
"""Return whether a package provides 'popt'.
This *should* always return True on SUSE based distributions, as zypper
and libsolv depend on popt. Nevertheless, we rather check this via rpm.
"""
try:
Cmd.sh_e('{0} --query --whatprovides {1} --quiet'
.format(self.rpm.rpm_path, self.package_popt_name))
return True
except CmdError:
return False
class FedoraInstaller(NativeRpmInstaller):
"""A class to install RPM Python binding on Fedora base OS."""
def __init__(self, rpm_py_version, python, rpm, **kwargs):
"""Initialize this class."""
NativeRpmInstaller.__init__(
self, rpm_py_version, python, rpm, **kwargs)
def run(self):
"""Run install main logic."""
try:
if not self._is_rpm_all_lib_include_files_installed():
self._make_lib_file_symbolic_links()
self._copy_each_include_files_to_include_dir()
self._make_dep_lib_file_sym_links_and_copy_include_files()
self.setup_py.add_patchs_to_build_without_pkg_config(
self.rpm.lib_dir, self.rpm.include_dir
)
self.setup_py.apply_and_save()
self._build_and_install()
except InstallError as exc:
if not self._is_rpm_all_lib_include_files_installed():
org_message = str(exc)
message = '''
Install failed without rpm-devel package by below reason.
Can you install the RPM package, and run this installer again?
'''
message += org_message
raise InstallError(message)
def install_from_rpm_py_package(self):
"""Run install from RPM Python binding RPM package."""
self._download_and_extract_rpm_py_package()
# Find ./usr/lib64/pythonN.N/site-packages/rpm directory.
# A binary built by same version Python with used Python is target
# for the safe installation.
if self.rpm.has_set_up_py_in():
# If RPM has setup.py.in, this strict check is okay.
# Because we can still install from the source.
py_dir_name = 'python{0}.{1}'.format(
sys.version_info[0], sys.version_info[1])
else:
# If RPM does not have setup.py.in such as CentOS6,
# Only way to install is by different Python's RPM package.
py_dir_name = '*'
python_lib_dir_pattern = os.path.join(
'usr', '*', py_dir_name, 'site-packages')
rpm_dir_pattern = os.path.join(python_lib_dir_pattern, 'rpm')
downloaded_rpm_dirs = glob.glob(rpm_dir_pattern)
if not downloaded_rpm_dirs:
message = 'Directory with a pattern: {0} not found.'.format(
rpm_dir_pattern)
raise RpmPyPackageNotFoundError(message)
src_rpm_dir = downloaded_rpm_dirs[0]
# Remove rpm directory for the possible installed directories.
for rpm_dir in self.python.python_lib_rpm_dirs:
if os.path.isdir(rpm_dir):
Log.debug("Remove existing rpm directory {0}".format(rpm_dir))
shutil.rmtree(rpm_dir)
dst_rpm_dir = self.python.python_lib_rpm_dir
Log.debug("Copy directory from '{0}' to '{1}'".format(
src_rpm_dir, dst_rpm_dir))
shutil.copytree(src_rpm_dir, dst_rpm_dir)
file_name_pattern = 'rpm-*.egg-info'
rpm_egg_info_pattern = os.path.join(
python_lib_dir_pattern, file_name_pattern)
downloaded_rpm_egg_infos = glob.glob(rpm_egg_info_pattern)
if downloaded_rpm_egg_infos:
existing_rpm_egg_info_pattern = os.path.join(
self.python.python_lib_dir, file_name_pattern)
existing_rpm_egg_infos = glob.glob(existing_rpm_egg_info_pattern)
for existing_rpm_egg_info in existing_rpm_egg_infos:
Log.debug("Remove existing rpm egg info file '{0}'".format(
existing_rpm_egg_info))
os.remove(existing_rpm_egg_info)
Log.debug("Copy file from '{0}' to '{1}'".format(
downloaded_rpm_egg_infos[0], self.python.python_lib_dir))
shutil.copy2(downloaded_rpm_egg_infos[0],