-
Notifications
You must be signed in to change notification settings - Fork 133
/
_mirror.py
1229 lines (1082 loc) · 48.3 KB
/
_mirror.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
# coding: utf-8
# OceanBase Deploy.
# Copyright (C) 2021 OceanBase
#
# This file is part of OceanBase Deploy.
#
# OceanBase Deploy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OceanBase Deploy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OceanBase Deploy. If not, see <https://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
import re
import os
import sys
import tempfile
import time
import pickle
import string
import fcntl
import requests
from glob import glob
from enum import Enum
from copy import deepcopy
from xml.etree import cElementTree
from _stdio import SafeStdio
from ssh import LocalClient
try:
from ConfigParser import ConfigParser
except:
from configparser import ConfigParser
from _arch import getArchList, getBaseArch
from _rpm import Version, Package, PackageInfo
from tool import ConfigUtil, FileUtil, var_replace
from _manager import Manager
from tool import timeout
_ARCH = getArchList()
_NO_LSE = 'amd64' in _ARCH and LocalClient.execute_command("grep atomics /proc/cpuinfo").stdout.strip() == ''
def get_use_centos_release(stdio=None):
_RELEASE = None
SUP_MAP = {
'ubuntu': {'16': 7},
'debian': {'9': 7},
'opensuse-leap': {'15': 7},
'sles': {'15.2': 7},
'fedora': {'33': 7},
'uos': {'20': 8},
'anolis': {'23': 7},
'openEuler': {'22.03': 7},
'kylin': {'V10': 8},
'alinux': {'2': 7, '3': 8}
}
_SERVER_VARS = {
'basearch': getBaseArch(),
}
with FileUtil.open('/etc/os-release') as f:
for line in f.readlines():
line = line.strip()
if not line:
continue
try:
k, v = line.split('=', 1)
_SERVER_VARS[k] = v.strip('"').strip("'")
except:
pass
if 'VERSION_ID' in _SERVER_VARS:
m = re.match('\d+', _SERVER_VARS['VERSION_ID'])
if m:
_RELEASE = m.group(0)
_SERVER_VARS['releasever'] = _RELEASE
server_vars = deepcopy(_SERVER_VARS)
linux_id = server_vars.get('ID')
if linux_id in SUP_MAP:
version_id = server_vars.get('VERSION_ID', '')
sorted_versions = sorted([Version(key) for key in SUP_MAP[linux_id]], reverse=True)
for version in sorted_versions:
if Version(version_id) >= version:
server_vars['releasever'] = SUP_MAP[linux_id][str(version)]
break
else:
server_vars['releasever'] = SUP_MAP[linux_id][str(version)]
stdio and getattr(stdio, 'warn', print)('Use centos %s remote mirror repository for %s %s' % (server_vars['releasever'], linux_id, server_vars.get('VERSION_ID')))
use_release = server_vars.get('releasever')
return use_release, server_vars
class MirrorRepositoryType(Enum):
LOCAL = 'local'
REMOTE = 'remote'
class MirrorRepository(SafeStdio):
MIRROR_TYPE = None
__VERSION_KEY__ = '__version__'
def __init__(self, mirror_path, stdio=None):
self.stdio = stdio
self.mirror_path = mirror_path
self.name = os.path.split(mirror_path)[1]
self.section_name = self.name
self._str = '%s mirror %s' % (self.mirror_type, self.name)
def __str__(self):
return self._str
@property
def mirror_type(self):
return self.MIRROR_TYPE
def get_all_pkg_info(self):
return []
def get_best_pkg(self, **pattern):
info = self.get_best_pkg_info(**pattern)
return self.get_rpm_pkg_by_info(info) if info else None
def get_exact_pkg(self, **pattern):
info = self.get_exact_pkg_info(**pattern)
return self.get_rpm_pkg_by_info(info) if info else None
def _pattern_check(self, pkg, **pattern):
for key in ['md5', 'name', 'version', 'release', 'arch']:
if pattern.get(key) is not None and getattr(pkg, key) != pattern[key]:
self.stdio and getattr(self.stdio, 'verbose', print)('pkg %s is %s, but %s is required' % (key, getattr(pkg, key), pattern[key]))
return None
return pkg
def get_rpm_pkg_by_info(self, pkg_info):
return None
def get_pkgs_info(self, **pattern):
return []
def get_best_pkg_info(self, **pattern):
return None
def get_exact_pkg_info(self, **pattern):
return None
def get_pkgs_info_with_score(self, **pattern):
return []
def get_all_rpm_pkgs(self):
pkgs = set()
for file_path in glob(os.path.join(self.mirror_path, '*.rpm')):
try:
pkgs.add(Package(file_path))
except:
self.stdio.exception()
self.stdio.verbose("Failed to open rpm file: %s" % file_path)
return pkgs
class RemotePackageInfo(PackageInfo):
def __init__(self, elem):
self.epoch = None
self.location = (None, None)
self.checksum = (None,None) # type,value
self.openchecksum = (None,None) # type,value
self.time = (None, None)
self.package_size = None
super(RemotePackageInfo, self).__init__(None, None, None, None, None, None)
self._parser(elem)
@property
def md5(self):
return self.checksum[1]
@md5.setter
def md5(self, value):
self.checksum = (self.checksum[0], value)
def __str__(self):
url = self.location[1]
if self.location[0]:
url = self.location[0] + url
return url
def _parser(self, elem):
tags = self.__dict__.keys()
for child in elem:
child_name = RemoteMirrorRepository.ns_cleanup(child.tag)
if child_name == 'location':
relative = child.attrib.get('href')
base = child.attrib.get('base')
self.location = (base, relative)
elif child_name == 'checksum':
csum_value = child.text
csum_type = child.attrib.get('type')
self.checksum = (csum_type,csum_value)
elif child_name == 'open-checksum':
csum_value = child.text
csum_type = child.attrib.get('type')
self.openchecksum = (csum_type, csum_value)
elif child_name == 'version':
self.epoch = child.attrib.get('epoch')
self.set_version(child.attrib.get('ver'))
self.set_release(child.attrib.get('rel'))
elif child_name == 'time':
build = child.attrib.get('build')
_file = child.attrib.get('file')
self.time = (int(_file), int(build))
elif child_name == 'arch':
self.arch = child.text
elif child_name == 'name':
self.name = child.text
elif child_name == 'size':
self.size = int(child.attrib.get('installed'))
self.package_size = int(child.attrib.get('package'))
class RemoteMirrorRepository(MirrorRepository):
class RepoData(object):
def __init__(self, elem):
self.type = None
self.type = elem.attrib.get('type')
self.location = (None, None)
self.checksum = (None,None) # type,value
self.openchecksum = (None,None) # type,value
self.timestamp = None
self.dbversion = None
self.size = None
self.opensize = None
self.deltas = []
self._parser(elem)
def _parser(self, elem):
for child in elem:
child_name = RemoteMirrorRepository.ns_cleanup(child.tag)
if child_name == 'location':
relative = child.attrib.get('href')
base = child.attrib.get('base')
self.location = (base, relative)
elif child_name == 'checksum':
csum_value = child.text
csum_type = child.attrib.get('type')
self.checksum = (csum_type,csum_value)
elif child_name == 'open-checksum':
csum_value = child.text
csum_type = child.attrib.get('type')
self.openchecksum = (csum_type, csum_value)
elif child_name == 'timestamp':
self.timestamp = child.text
elif child_name == 'database_version':
self.dbversion = child.text
elif child_name == 'size':
self.size = child.text
elif child_name == 'open-size':
self.opensize = child.text
elif child_name == 'delta':
delta = RemoteMirrorRepository.RepoData(child)
delta.type = self.type
self.deltas.append(delta)
MIRROR_TYPE = MirrorRepositoryType.REMOTE
REMOTE_REPOMD_FILE = '/repodata/repomd.xml'
REPOMD_FILE = 'repomd.xml'
OTHER_DB_FILE = 'other_db.xml'
REPO_AGE_FILE = '.rege_age'
DB_CACHE_FILE = '.db'
PRIMARY_REPOMD_TYPE = 'primary'
__VERSION__ = Version("1.0")
def __init__(self, mirror_path, meta_data, stdio=None):
self.baseurl = None
self.repomd_age = 0
self.repo_age = 0
self.priority = 1
self.gpgcheck = False
self._db = None
self._repomds = None
self._available = None
super(RemoteMirrorRepository, self).__init__(mirror_path, stdio=stdio)
self.section_name = meta_data['section_name']
self.baseurl = meta_data['baseurl']
self.enabled = meta_data['enabled'] == '1'
self.gpgcheck = ConfigUtil.get_value_from_dict(meta_data, 'gpgcheck', 0, int) > 0
self.priority = 100 - ConfigUtil.get_value_from_dict(meta_data, 'priority', 99, int)
if os.path.exists(mirror_path):
self._load_repo_age()
if self.enabled:
repo_age = ConfigUtil.get_value_from_dict(meta_data, 'repo_age', 0, int)
if (repo_age > self.repo_age or int(time.time()) - 86400 > self.repo_age) and self.available:
if self.update_mirror():
self.repo_age = repo_age
@property
def available(self):
if not self.enabled:
return False
if self._available is None:
try:
with timeout(5):
req = requests.request('get', self.baseurl)
self._available = req.status_code < 400
except Exception:
self.stdio and getattr(self.stdio, 'exception', print)('')
self._available = False
return self._available
@property
def db(self):
if self._db is not None:
return self._db
primary_repomd = self._get_repomd_by_type(self.PRIMARY_REPOMD_TYPE)
if not primary_repomd:
return []
file_path = self._get_repomd_data_file(primary_repomd)
if not file_path:
return []
self._load_db_cache(file_path)
if self._db is None:
fp = FileUtil.unzip(file_path, stdio=self.stdio)
if not fp:
FileUtil.rm(file_path, stdio=self.stdio)
return []
self._db = {}
try:
parser = cElementTree.iterparse(fp)
for event, elem in parser:
if RemoteMirrorRepository.ns_cleanup(elem.tag) == 'package' and elem.attrib.get('type') == 'rpm':
info = RemotePackageInfo(elem)
self._db[info.md5] = info
self._dump_db_cache()
except:
FileUtil.rm(file_path, stdio=self.stdio)
self.stdio and self.stdio.critical('failed to parse file %s, please retry later.' % file_path)
return []
return self._db
def _load_db_cache(self, path):
try:
db_cacahe_path = self.get_db_cache_file(self.mirror_path)
repomd_time = os.stat(path)[8]
cache_time = os.stat(db_cacahe_path)[8]
if cache_time > repomd_time:
self.stdio and getattr(self.stdio, 'verbose', print)('load %s' % db_cacahe_path)
with open(db_cacahe_path, 'rb') as f:
self._db = pickle.load(f)
if self.__VERSION__ > Version(self.db.get(self.__VERSION_KEY__, '0')):
self._db = None
else:
del self._db[self.__VERSION_KEY__]
except:
pass
def _dump_db_cache(self):
if self._db:
data = deepcopy(self.db)
data[self.__VERSION_KEY__] = self.__VERSION__
try:
db_cacahe_path = self.get_db_cache_file(self.mirror_path)
self.stdio and getattr(self.stdio, 'verbose', print)('dump %s' % db_cacahe_path)
with open(db_cacahe_path, 'wb') as f:
pickle.dump(data, f)
return True
except:
self.stdio.exception('')
pass
return False
@staticmethod
def ns_cleanup(qn):
return qn if qn.find('}') == -1 else qn.split('}')[1]
@staticmethod
def get_repo_age_file(mirror_path):
return os.path.join(mirror_path, RemoteMirrorRepository.REPO_AGE_FILE)
@staticmethod
def get_repomd_file(mirror_path):
return os.path.join(mirror_path, RemoteMirrorRepository.REPOMD_FILE)
@staticmethod
def get_other_db_file(mirror_path):
return os.path.join(mirror_path, RemoteMirrorRepository.OTHER_DB_FILE)
@staticmethod
def get_db_cache_file(mirror_path):
return os.path.join(mirror_path, RemoteMirrorRepository.DB_CACHE_FILE)
def _load_repo_age(self):
try:
with open(self.get_repo_age_file(self.mirror_path), 'r') as f:
self.repo_age = int(f.read())
except:
pass
def _dump_repo_age_data(self):
try:
with open(self.get_repo_age_file(self.mirror_path), 'w') as f:
f.write(str(self.repo_age))
return True
except:
pass
return False
def _get_repomd_by_type(self, repomd_type):
repodmds = self.get_repomds()
for repodmd in repodmds:
if repodmd.type == repomd_type:
return repodmd
def _get_repomd_data_file(self, repomd):
file_name = repomd.location[1]
repomd_name = file_name.split('-')[-1]
file_path = os.path.join(self.mirror_path, file_name)
if os.path.exists(file_path):
return file_path
base_url = repomd.location[0] if repomd.location[0] else self.baseurl
url = '%s/%s' % (base_url, repomd.location[1])
if self.download_file(url, file_path, self.stdio):
return file_path
def update_mirror(self):
self.stdio and getattr(self.stdio, 'start_loading')('Update %s' % self.name)
self.get_repomds(True)
primary_repomd = self._get_repomd_by_type(self.PRIMARY_REPOMD_TYPE)
if not primary_repomd:
self._available = False
self.stdio and getattr(self.stdio, 'stop_loading')('fail')
return False
file_path = self._get_repomd_data_file(primary_repomd)
if not file_path:
self._available = False
self.stdio and getattr(self.stdio, 'stop_loading')('fail')
return False
self._db = None
self.repo_age = int(time.time())
self._dump_repo_age_data()
self.stdio and getattr(self.stdio, 'stop_loading')('succeed')
self._available = True
return True
def get_repomds(self, update=False):
path = self.get_repomd_file(self.mirror_path)
if update or not os.path.exists(path):
url = '%s/%s' % (self.baseurl, self.REMOTE_REPOMD_FILE)
self.download_file(url, path, self.stdio)
self._repomds = None
if self._repomds is None:
self._repomds = []
try:
parser = cElementTree.iterparse(path)
for event, elem in parser:
if RemoteMirrorRepository.ns_cleanup(elem.tag) == 'data':
repod = RemoteMirrorRepository.RepoData(elem)
self._repomds.append(repod)
except:
pass
return self._repomds
def get_all_pkg_info(self):
return [self.db[key] for key in self.db]
def get_rpm_info_by_md5(self, md5, **pattern):
if md5 in self.db:
return self._pattern_check(self.db[md5], **pattern)
for key in self.db:
info = self.db[key]
if info.md5 == md5:
self.stdio and getattr(self.stdio, 'verbose', print)('%s translate info %s' % (md5, info.md5))
return self._pattern_check(info, **pattern)
return None
def get_rpm_pkg_by_info(self, pkg_info):
file_name = pkg_info.location[1]
file_path = os.path.join(self.mirror_path, file_name)
self.stdio and getattr(self.stdio, 'verbose', print)('get RPM package by %s' % pkg_info)
if not os.path.exists(file_path) or os.stat(file_path)[8] < pkg_info.time[1] or os.path.getsize(file_path) != pkg_info.package_size:
base_url = pkg_info.location[0] if pkg_info.location[0] else self.baseurl
url = '%s/%s' % (base_url, pkg_info.location[1])
if not self.download_file(url, file_path, self.stdio):
return None
return Package(file_path)
def get_pkgs_info(self, **pattern):
matchs = self.get_pkgs_info_with_score(**pattern)
if matchs:
return [info[0] for info in sorted(matchs, key=lambda x: x[1], reverse=True)]
return matchs
def get_best_pkg_info(self, **pattern):
matchs = self.get_pkgs_info_with_score(**pattern)
if matchs:
return Package(max(matchs, key=lambda x: x[1])[0].path)
return None
def get_exact_pkg_info(self, **pattern):
if 'md5' in pattern and pattern['md5']:
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is %s' % pattern['md5'])
return self.get_rpm_info_by_md5(**pattern)
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is None')
if 'name' not in pattern and not pattern['name']:
self.stdio and getattr(self.stdio, 'verbose', print)('name is None')
return None
name = pattern['name']
self.stdio and getattr(self.stdio, 'verbose', print)('name is %s' % name)
arch = getArchList(pattern['arch']) if 'arch' in pattern and pattern['arch'] else _ARCH
self.stdio and getattr(self.stdio, 'verbose', print)('arch is %s' % arch)
release = pattern['release'] if 'release' in pattern else None
self.stdio and getattr(self.stdio, 'verbose', print)('release is %s' % release)
version = ConfigUtil.get_value_from_dict(pattern, 'version', transform_func=Version)
self.stdio and getattr(self.stdio, 'verbose', print)('version is %s' % version)
min_version = ConfigUtil.get_value_from_dict(pattern, 'min_version', transform_func=Version)
self.stdio and getattr(self.stdio, 'verbose', print)('min_version is %s' % min_version)
max_version = ConfigUtil.get_value_from_dict(pattern, 'max_version', transform_func=Version)
self.stdio and getattr(self.stdio, 'verbose', print)('max_version is %s' % max_version)
only_download = pattern['only_download'] if 'only_download' in pattern else False
self.stdio and getattr(self.stdio, 'verbose', print)('only_download is %s' % only_download)
pkgs = []
for key in self.db:
info = self.db[key]
if info.name != name:
continue
if info.arch not in arch:
continue
if release and info.release != release:
continue
if version and version != info.version:
continue
if min_version and min_version > info.version:
continue
if max_version and max_version <= info.version:
continue
if only_download and not self.is_download(info):
continue
pkgs.append(info)
if pkgs:
pkgs.sort()
return pkgs[-1]
else:
return None
def get_best_pkg_info_with_score(self, **pattern):
matchs = self.get_pkgs_info_with_score(**pattern)
if matchs:
return [info[0] for info in sorted(matchs, key=lambda x: x[1], reverse=True)]
return None
def get_pkgs_info_with_score(self, **pattern):
matchs = []
if 'md5' in pattern and pattern['md5']:
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is %s' % pattern['md5'])
info = None
if pattern['md5'] in self.db:
info = self._pattern_check(self.db[pattern['md5']], **pattern)
return [info, (0xfffffffff, )] if info else matchs
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is None')
if 'name' not in pattern and not pattern['name']:
self.stdio and getattr(self.stdio, 'verbose', print)('name is None')
return matchs
self.stdio and getattr(self.stdio, 'verbose', print)('name is %s' % pattern['name'])
if 'arch' in pattern and pattern['arch']:
pattern['arch'] = getArchList(pattern['arch'])
else:
pattern['arch'] = _ARCH
self.stdio and getattr(self.stdio, 'verbose', print)('arch is %s' % pattern['arch'])
release = pattern['release'] if 'release' in pattern else None
self.stdio and getattr(self.stdio, 'verbose', print)('release is %s' % release)
if 'version' in pattern and pattern['version']:
pattern['version'] += '.'
else:
pattern['version'] = None
self.stdio and getattr(self.stdio, 'verbose', print)('version is %s' % pattern['version'])
for key in self.db:
info = self.db[key]
if pattern['name'] in info.name:
score = self.match_score(info, **pattern)
if score[0]:
matchs.append([info, score])
return matchs
def match_score(self, info, name, arch, version=None, min_version=None, max_version=None, release=None):
if info.arch not in arch:
return [0, ]
info_version = '%s.' % info.version
if version and info_version.find(version) != 0:
return [0 ,]
if min_version and Version(info_version) <= Version(min_version):
return [0 ,]
if max_version and Version(info_version) > Version(max_version):
return [0 ,]
if release and info.release != release:
return [0 ,]
if _NO_LSE:
lse_score = 'nonlse' in info.release
else:
lse_score = True
c = [len(name) / len(info.name), lse_score, info]
return c
def is_download(self, pkg_info):
file_name = pkg_info.location[1]
file_path = os.path.join(self.mirror_path, file_name)
return os.path.exists(file_path)
@staticmethod
def validate_repoid(repoid):
"""Return the first invalid char found in the repoid, or None."""
allowed_chars = string.ascii_letters + string.digits + '-_.:'
for char in repoid:
if char not in allowed_chars:
return char
else:
return None
@staticmethod
def download_file(url, save_path, stdio=None):
try:
with requests.get(url, stream=True) as fget:
file_size = int(fget.headers["Content-Length"])
if stdio:
print_bar = True
for func in ['start_progressbar', 'update_progressbar', 'finish_progressbar']:
if getattr(stdio, func, False) is False:
print_bar = False
break
else:
print_bar = False
if print_bar:
_, fine_name = os.path.split(save_path)
units = {"B": 1, "K": 1<<10, "M": 1<<20, "G": 1<<30, "T": 1<<40}
for unit in units:
num = file_size / units[unit]
if num < 1024:
break
stdio.start_progressbar('Download %s (%.2f %s)' % (fine_name, num, unit), file_size)
chunk_size = 512
file_done = 0
with FileUtil.open(save_path, "wb", stdio=stdio) as fw:
for chunk in fget.iter_content(chunk_size):
fw.write(chunk)
file_done = file_done + chunk_size
if print_bar and file_done <= file_size:
stdio.update_progressbar(file_done)
print_bar and stdio.finish_progressbar()
return True
except:
FileUtil.rm(save_path)
stdio and getattr(stdio, 'warn', print)('Failed to download %s to %s' % (url, save_path))
stdio and getattr(stdio, 'exception', print)('')
return False
class LocalMirrorRepository(MirrorRepository):
MIRROR_TYPE = MirrorRepositoryType.LOCAL
_DB_FILE = '.db'
__VERSION__ = Version("1.0")
def __init__(self, mirror_path, stdio=None):
super(LocalMirrorRepository, self).__init__(mirror_path, stdio=stdio)
self.db = {}
self.db_path = os.path.join(mirror_path, self._DB_FILE)
self.enabled = '-'
self.available = True
self._load_db()
@property
def repo_age(self):
return int(time.time())
def _load_db(self):
try:
if os.path.isfile(self.db_path):
with open(self.db_path, 'rb') as f:
db = pickle.load(f)
self._flush_db(db)
except:
self.stdio.exception('')
pass
def _flush_db(self, db):
need_flush = self.__VERSION__ > Version(db.get(self.__VERSION_KEY__, '0'))
for key in db:
data = db[key]
path = getattr(data, 'path', False)
if not path or not os.path.exists(path):
continue
if need_flush:
data = Package(path)
self.db[key] = data
if need_flush:
self._dump_db()
def _dump_db(self):
# 所有 dump方案都为临时
try:
data = deepcopy(self.db)
data[self.__VERSION_KEY__] = self.__VERSION__
with open(self.db_path, 'wb') as f:
pickle.dump(data, f)
return True
except:
self.stdio.exception('')
pass
return False
def exist_pkg(self, pkg):
return pkg.md5 in self.db
def add_pkg(self, pkg):
target_path = os.path.join(self.mirror_path, pkg.file_name)
try:
src_path = pkg.path
self.stdio and getattr(self.stdio, 'verbose', print)('RPM hash check')
if target_path != src_path:
if pkg.md5 in self.db:
t_info = self.db[pkg.md5]
self.stdio and getattr(self.stdio, 'verbose', print)('copy %s to %s' % (src_path, target_path))
if t_info.path == target_path:
del self.db[t_info.md5]
FileUtil.copy(src_path, target_path)
else:
FileUtil.copy(src_path, target_path)
try:
self.stdio and getattr(self.stdio, 'verbose', print)('remove %s' % t_info.path)
os.remove(t_info.path)
except:
pass
else:
FileUtil.copy(src_path, target_path)
pkg.path = target_path
else:
self.stdio and getattr(self.stdio, 'error', print)('same file')
return None
self.db[pkg.md5] = pkg
self.stdio and getattr(self.stdio, 'verbose', print)('dump PackageInfo')
if self._dump_db():
self.stdio and getattr(self.stdio, 'print', print)('add %s to local mirror', src_path)
return pkg
except IOError:
self.stdio and getattr(self.stdio, 'exception', print)('')
self.stdio and getattr(self.stdio, 'error', print)('Set local mirror failed. %s IO Error' % pkg.file_name)
except:
self.stdio and getattr(self.stdio, 'exception', print)('')
self.stdio and getattr(self.stdio, 'error', print)('Unable to add %s as local mirror' % pkg.file_name)
return None
def get_all_pkg_info(self):
return [self.db[key] for key in self.db]
def get_rpm_pkg_by_info(self, pkg_info):
self.stdio and getattr(self.stdio, 'verbose', print)('get RPM package by %s' % pkg_info)
return Package(pkg_info.path)
def get_pkgs_info(self, **pattern):
matchs = self.get_pkgs_info_with_score(**pattern)
if matchs:
return [info[0] for info in sorted(matchs, key=lambda x: x[1], reverse=True)]
return matchs
def get_best_pkg_info(self, **pattern):
matchs = self.get_pkgs_info_with_score(**pattern)
if matchs:
return Package(max(matchs, key=lambda x: x[1])[0].path)
return None
def get_exact_pkg_info(self, **pattern):
if 'md5' in pattern and pattern['md5']:
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is %s' % pattern['md5'])
info = None
if pattern['md5'] in self.db:
info = self._pattern_check(self.db[pattern['md5']], **pattern)
return info
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is None')
if 'name' not in pattern and not pattern['name']:
self.stdio and getattr(self.stdio, 'verbose', print)('name is None')
return None
name = pattern['name']
self.stdio and getattr(self.stdio, 'verbose', print)('name is %s' % name)
arch = getArchList(pattern['arch']) if 'arch' in pattern and pattern['arch'] else _ARCH
self.stdio and getattr(self.stdio, 'verbose', print)('arch is %s' % arch)
release = pattern['release'] if 'release' in pattern else None
self.stdio and getattr(self.stdio, 'verbose', print)('release is %s' % release)
version = ConfigUtil.get_value_from_dict(pattern, 'version', transform_func=Version)
self.stdio and getattr(self.stdio, 'verbose', print)('version is %s' % version)
min_version = ConfigUtil.get_value_from_dict(pattern, 'min_version', transform_func=Version)
self.stdio and getattr(self.stdio, 'verbose', print)('min_version is %s' % min_version)
max_version = ConfigUtil.get_value_from_dict(pattern, 'max_version', transform_func=Version)
self.stdio and getattr(self.stdio, 'verbose', print)('max_version is %s' % max_version)
pkgs = []
for key in self.db:
info = self.db[key]
if info.name != name:
continue
if info.arch not in arch:
continue
if release and info.release != release:
continue
if version and version != info.version:
continue
if min_version and min_version > info.version:
continue
if max_version and max_version <= info.version:
continue
pkgs.append(info)
if pkgs:
pkgs.sort()
return pkgs[-1]
else:
return None
def get_best_pkg_info_with_score(self, **pattern):
matchs = self.get_pkgs_info_with_score(**pattern)
if matchs:
return max(matchs, key=lambda x: x[1])
return None
def get_pkgs_info_with_score(self, **pattern):
matchs = []
if 'md5' in pattern and pattern['md5']:
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is %s' % pattern['md5'])
info = None
if pattern['md5'] in self.db:
info = self._pattern_check(self.db[pattern['md5']], **pattern)
return [info, (0xfffffffff, )] if info else matchs
self.stdio and getattr(self.stdio, 'verbose', print)('md5 is None')
if 'name' not in pattern and not pattern['name']:
return matchs
self.stdio and getattr(self.stdio, 'verbose', print)('name is %s' % pattern['name'])
if 'arch' in pattern and pattern['arch']:
pattern['arch'] = getArchList(pattern['arch'])
else:
pattern['arch'] = _ARCH
self.stdio and getattr(self.stdio, 'verbose', print)('arch is %s' % pattern['arch'])
release = pattern['release'] if 'release' in pattern else None
self.stdio and getattr(self.stdio, 'verbose', print)('release is %s' % release)
if 'version' in pattern and pattern['version']:
pattern['version'] += '.'
else:
pattern['version'] = None
self.stdio and getattr(self.stdio, 'verbose', print)('version is %s' % pattern['version'])
for key in self.db:
info = self.db[key]
if pattern['name'] in info.name:
score = self.match_score(info, **pattern)
if score[0]:
matchs.append([info, score])
return matchs
def match_score(self, info, name, arch, version=None, min_version=None, max_version=None, release=None):
if info.arch not in arch:
return [0, ]
info_version = '%s.' % info.version
if version and info_version.find(version) != 0:
return [0 ,]
if min_version and Version(info_version) <= Version(min_version):
return [0 ,]
if max_version and Version(info_version) > Version(max_version):
return [0 ,]
if release and info.release != release:
return [0 ,]
c = [len(name) / len(info.name), info]
return c
def get_info_list(self):
return [self.db[key] for key in self.db]
class MirrorRepositoryConfig(object):
def __init__(self, path, parser, repo_age):
self.path = path
self.parser = parser
self.repo_age = repo_age
self.sections = {}
def add_section(self, section):
self.sections[section.section_name] = section
def __eq__(self, o):
return self.repo_age == o.repo_age
def __le__(self, o):
return self.repo_age < o.repo_age
def __gt__(self, o):
return self.repo_age > o.repo_age
class MirrorRepositorySection(object):
def __init__(self, section_name, meta_data, remote_path):
self.section_name = section_name
self.meta_data = meta_data
self.remote_path = remote_path
def get_mirror(self, server_vars, stdio=None):
meta_data = self.meta_data
meta_data['name'] = var_replace(meta_data['name'], server_vars)
meta_data['baseurl'] = var_replace(meta_data['baseurl'], server_vars)
mirror_path = os.path.join(self.remote_path, meta_data['name'])
mirror = RemoteMirrorRepository(mirror_path, meta_data, stdio)
return mirror
@property
def is_enabled(self):
return self.meta_data.get('enabled', '1') == '1'
class MirrorRepositoryManager(Manager):
RELATIVE_PATH = 'mirror'
def __init__(self, home_path, lock_manager=None, stdio=None):
super(MirrorRepositoryManager, self).__init__(home_path, stdio=stdio)
self.remote_path = os.path.join(self.path, 'remote') # rpm remote mirror cache
self.local_path = os.path.join(self.path, 'local')
self.is_init = self.is_init and self._mkdir(self.remote_path) and self._mkdir(self.local_path)
self._local_mirror = None
self.lock_manager = lock_manager
self._cache_path_repo_config = {}
self._cache_section_repo_config = {}
def _lock(self, read_only=False):
if self.lock_manager:
if read_only:
return self.lock_manager.mirror_and_repo_sh_lock()
else:
return self.lock_manager.mirror_and_repo_ex_lock()
return True
@property
def local_mirror(self):
self._lock()
if self._local_mirror is None:
self._local_mirror = LocalMirrorRepository(self.local_path, self.stdio)
return self._local_mirror
def _get_repo_config(self, path):
self.stdio and getattr(self.stdio, 'verbose', print)('load repo config: %s' % path)
repo_conf = self._cache_path_repo_config.get(path)
repo_age = os.stat(path)[8]
if not repo_conf or repo_age != repo_conf.repo_age:
with FileUtil.open(path, 'r', stdio=self.stdio) as confpp_obj:
parser = ConfigParser()
parser.readfp(confpp_obj)
repo_conf = MirrorRepositoryConfig(path, parser, repo_age)
self._cache_path_repo_config[path] = repo_conf
return self._cache_path_repo_config[path]
def _get_repo_config_by_section(self, section_name):
return self._cache_section_repo_config.get(section_name)
def _remove_cache(self, section_name):
repo_conf = self._cache_section_repo_config[section_name]
del self._cache_path_repo_config[repo_conf.path]
del self._cache_section_repo_config[section_name]
def _scan_repo_configs(self):
cached_sections = list(self._cache_section_repo_config.keys())
for path in glob(os.path.join(self.remote_path, '*.repo')):
repo_conf = self._get_repo_config(path)
for section in repo_conf.parser.sections():
if section in ['main', 'installed']:
continue
if section in ['local', 'remote']:
self.stdio and getattr(self.stdio, 'warn', print)('%s is system keyword.' % section)
continue
bad = RemoteMirrorRepository.validate_repoid(section)
if bad:
continue
meta_data = {'section_name': section}
for attr in repo_conf.parser.options(section):