forked from dagwieers/mrepo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmrepo
executable file
·1943 lines (1652 loc) · 70.8 KB
/
mrepo
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/python
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU Library General Public License as published by
### the Free Software Foundation; version 2 only
###
### This program 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 Library General Public License for more details.
###
### You should have received a copy of the GNU Library General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
### Copyright 2004-2007 Dag Wieers <[email protected]>
from __future__ import generators # for Python 2.2
import ConfigParser
import getopt
import glob
import os
import re
import tempfile
# Python >= 2.5
try:
from hashlib import sha1 as sha1hash
# Python <= 2.4
except ImportError:
from sha import new as sha1hash
import shutil
import sys
import time
import types
import urlparse
__version__ = "$Revision$"
# $Source$
VERSION = "0.8.9"
archs = {
'alpha': ('alpha', 'alphaev5', 'alphaev56', 'alphaev6', 'alphaev67'),
'i386': ('i386', 'i486', 'i586', 'i686', 'athlon'),
'ia64': ('i386', 'i686', 'ia64'),
'ppc': ('ppc', ),
'ppc64': ('ppc', 'ppc64', 'ppc64pseries', 'ppc64iseries'),
'x86_64': ('i386', 'i486', 'i586', 'i686', 'athlon', 'x86_64', 'amd64', 'ia32e'),
'sparc64': ('sparc', 'sparcv8', 'sparcv9', 'sparc64'),
'sparc64v': ('sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'),
's390': ('s390', ),
's390x': ('s390', 's390x'),
}
variables = {}
enable = ('yes', 'on', 'true', '1')
disable = ('no', 'off', 'false', '0')
### Register rhn and rhns as a known schemes
for scheme in ('rhn', 'rhns', 'you', 'reposync', 'reposyncs', 'reposyncf'):
urlparse.uses_netloc.insert(0, scheme)
urlparse.uses_query.insert(0, scheme)
class Options:
def __init__(self, args):
self.configfile = '/etc/mrepo.conf'
self.dists = []
self.rhnrelease = None
self.force = False
self.dryrun = False
self.generate = False
self.quiet = False
self.remount = False
self.repos = []
self.types = []
self.umount = False
self.update = False
self.verbose = 1
try:
opts, args = getopt.getopt(args, 'c:d:fghnqr:t:uvx',
('config=', 'dist=', 'dry-run', 'force', 'generate', 'help', 'quiet', 'repo=',
'remount', 'type=', 'umount', 'unmount', 'update', 'verbose', 'version', 'extras'))
except getopt.error, exc:
print 'mrepo: %s, try mrepo -h for a list of all the options' % str(exc)
sys.exit(1)
for opt, arg in opts:
if opt in ('-c', '--config'):
self.configfile = os.path.abspath(arg)
elif opt in ('-d', '--dist'):
print 'mrepo: the use of -d or --dist as an option is deprecated, use the argument list'
self.dists = self.dists + arg.split(',')
elif opt in ('-f', '--force'):
self.force = True
elif opt in ('-g', '--generate'):
self.generate = True
elif opt in ('-h', '--help'):
self.usage()
print
self.help()
sys.exit(0)
elif opt in ('-n', '--dry-run'):
self.dryrun = True
elif opt in ('-q', '--quiet'):
self.quiet = True
elif opt in ('-r', '--repo'):
self.repos = self.repos + arg.split(',')
elif opt in ('--remount', ):
self.remount = True
elif opt in ('-t', '--type'):
self.types = self.types + arg.split(',')
elif opt in ('-u', '--update'):
self.update = True
elif opt in ('--umount', '--unmount'):
self.umount = True
elif opt in ('-v', '--verbose'):
self.verbose = self.verbose + 1
elif opt in ('--version', ):
self.version()
sys.exit(0)
elif opt in ('-x', '--extras'):
print 'mrepo: the use of -x or --extras is deprecated, use -u and -r instead'
self.update = True
if not self.types:
self.types = ['file', 'fish', 'ftp', 'http', 'https', 'mc', 'rhn',
'rhns', 'rsync', 'sftp', 'mrepo', 'you', 'reposync', 'reposyncs',
'reposyncf']
for arg in args:
self.dists = self.dists + arg.split(',')
if self.quiet:
self.verbose = 0
if self.verbose >= 3:
print 'Verbosity set to level %d' % (self.verbose - 1)
print 'Using configfile %s' % self.configfile
def version(self):
print 'mrepo %s' % VERSION
print 'Written by Dag Wieers <[email protected]>'
print 'Homepage at http://dag.wieers.com/home-made/mrepo/'
print
print 'platform %s/%s' % (os.name, sys.platform)
print 'python %s' % sys.version
print
print 'build revision $Rev$'
def usage(self):
print 'usage: mrepo [options] dist1 [dist2-arch ..]'
def help(self):
print '''Set up a distribution server from ISO files
mrepo options:
-c, --config=file specify alternative configfile
-f, --force force repository generation
-g, --generate generate mrepo repositories
-n, --dry-run show what would have been done
-q, --quiet minimal output
-r, --repo=repo1,repo2 restrict action to specific repositories
--remount remount distribution ISOs
-t, --type=type1,type2 mirror types to use. Default: file, fish, ftp, http, https, mc, rhn, rhns, rsync, sftp, mrepo, you
-u, --update fetch OS updates
-v, --verbose increase verbosity
--version print mrepo version information
-vv, -vvv, -vvvv.. increase verbosity more
--unmount unmount distribution ISOs
'''
class Config:
def __init__(self):
self.read(op.configfile)
self.cachedir = self.getoption('main', 'cachedir', '/var/cache/mrepo')
self.lockdir = self.getoption('main', 'lockdir', '/var/cache/mrepo')
self.confdir = self.getoption('main', 'confdir', '/etc/mrepo.conf.d')
self.htmldir = self.getoption('main', 'htmldir', '/usr/share/mrepo/html')
self.pxelinux = self.getoption('main', 'pxelinux', '/usr/lib/syslinux/pxelinux.0')
self.srcdir = self.getoption('main', 'srcdir', '/var/mrepo')
self.tftpdir = self.getoption('main', 'tftpdir', '/tftpboot/mrepo')
self.wwwdir = self.getoption('main', 'wwwdir', '/var/www/mrepo')
self.logfile = self.getoption('main', 'logfile', '/var/log/mrepo.log')
self.mailto = self.getoption('main', 'mailto', None)
self.mailfrom = self.getoption('main', 'mailfrom', 'mrepo@%s' % os.uname()[1])
self.smtpserver = self.getoption('main', 'smtp-server', 'localhost')
self.arch = self.getoption('main', 'arch', 'i386')
self.metadata = self.getoption('main', 'metadata', 'repomd repoview')
self.shareiso = self.getoption('main', 'shareiso', 'yes') not in disable
self.quiet = self.getoption('main', 'quiet', 'no') not in disable
if op.verbose == 1 and self.quiet:
op.verbose = 0
self.hardlink = self.getoption('main', 'hardlink', 'no') not in disable
### FIXME: See if fuse module is loaded
self.fuseiso = self.getoption('main', 'fuseiso', 'yes') not in disable
self.unionfs = self.getoption('main', 'unionfs', 'yes') not in disable
self.no_proxy = self.getoption('main', 'no_proxy', None)
self.ftp_proxy = self.getoption('main', 'ftp_proxy', None)
self.http_proxy = self.getoption('main', 'http_proxy', None)
self.https_proxy = self.getoption('main', 'https_proxy', None)
self.RSYNC_PROXY = self.getoption('main', 'RSYNC_PROXY', None)
self.cmd = {}
self.cmd['createrepo'] = self.getoption('main', 'createrepocmd', '/usr/bin/createrepo')
self.cmd['fuseiso'] = self.getoption('main', 'fuseisocmd', '/usr/bin/fuseiso')
self.cmd['genbasedir'] = self.getoption('main', 'genbasedircmd', '/usr/bin/genbasedir')
self.cmd['hardlink'] = self.getoption('main', 'hardlinkcmd', '/usr/sbin/hardlink')
self.cmd['hardlink++'] = self.getoption('main', 'hardlinkcppcmd', '/usr/bin/hardlink++')
self.cmd['hardlinkpy'] = self.getoption('main', 'hardlinkpycmd', '/usr/bin/hardlinkpy')
self.cmd['lftp'] = self.getoption('main', 'lftpcmd', '/usr/bin/lftp')
self.cmd['mirrordir'] = self.getoption('main', 'mirrordircmd', '/usr/bin/mirrordir')
self.cmd['mount'] = self.getoption('main', 'mountcmd', '/bin/mount')
self.cmd['repoview'] = self.getoption('main', 'repoviewcmd', '/usr/bin/repoview')
self.cmd['reposync'] = self.getoption('main', 'reposynccmd', '/usr/bin/reposync')
self.cmd['rhnget'] = self.getoption('main', 'rhngetcmd', '/usr/bin/rhnget')
self.cmd['rsync'] = self.getoption('main', 'rsynccmd', '/usr/bin/rsync')
self.cmd['unionfs'] = self.getoption('main', 'unionfscmd', '/usr/bin/unionfs')
self.cmd['umount'] = self.getoption('main', 'umountcmd', '/bin/umount')
self.cmd['youget'] = self.getoption('main', 'yougetcmd', '/usr/bin/youget')
self.cmd['yumarch'] = self.getoption('main', 'yumarchcmd', '/usr/bin/yum-arch')
self.createrepooptions = self.getoption('main', 'createrepo-options', '--pretty --database --update')
self.lftpbwlimit = self.getoption('main', 'lftp-bandwidth-limit', None)
self.lftpcleanup = self.getoption('main', 'lftp-cleanup', 'yes') not in disable
self.lftpexcldebug = self.getoption('main', 'lftp-exclude-debug', 'yes') not in disable
self.lftpexclsrpm = self.getoption('main', 'lftp-exclude-srpm', 'yes') not in disable
self.lftpoptions = self.getoption('main', 'lftp-options', '')
self.lftpcommands = self.getoption('main', 'lftp-commands', '')
self.lftpmirroroptions = self.getoption('main', 'lftp-mirror-options', '-c')
self.lftptimeout = self.getoption('main', 'lftp-timeout', None)
self.mirrordircleanup = self.getoption('main', 'mirrordir-cleanup', 'yes') not in disable
self.mirrordirexcldebug = self.getoption('main', 'mirrordir-exclude-debug', 'yes') not in disable
self.mirrordirexclsrpm = self.getoption('main', 'mirrordir-exclude-srpm', 'yes') not in disable
self.mirrordiroptions = self.getoption('main', 'mirrordir-options', '')
self.reposyncoptions = self.getoption('main', 'reposync-options', '')
self.reposynccleanup = self.getoption('main', 'reposync-cleanup', 'yes') not in disable
self.reposyncnewestonly = self.getoption('main', 'reposync-newest-only', 'no') not in disable
self.reposyncexcldebug = self.getoption('main','reposync-exclude-debug', 'yes') not in disable
self.reposyncnorepopath = self.getoption('main','reposync-no-repopath', 'yes') not in disable
self.reposynctimeout = self.getoption('main','reposync-timeout', '90')
self.reposyncminrate = self.getoption('main','reposync-minrate', '250')
self.rhnlogin = self.getoption('main', 'rhnlogin', None)
self.rhngetoptions = self.getoption('main', 'rhnget-options', '')
self.rhngetcleanup = self.getoption('main', 'rhnget-cleanup', 'yes') not in disable
self.rhngetdownloadall = self.getoption('main', 'rhnget-download-all', 'no') not in disable
self.rsyncbwlimit = self.getoption('main', 'rsync-bandwidth-limit', None)
self.rsynccleanup = self.getoption('main', 'rsync-cleanup', 'yes') not in disable
self.rsyncexcldebug = self.getoption('main', 'rsync-exclude-debug', 'yes') not in disable
self.rsyncexclsrpm = self.getoption('main', 'rsync-exclude-srpm', 'yes') not in disable
self.rsyncoptions = self.getoption('main', 'rsync-options', '-rtHL --partial')
self.rsynctimeout = self.getoption('main', 'rsync-timeout', None)
self.repoviewoptions = self.getoption('main', 'repoview-options', '')
self.alldists = []
self.dists = []
self.update(op.configfile)
def read(self, configfile):
self.cfg = ConfigParser.ConfigParser()
info(4, 'Reading config file %s' % (configfile))
(s, b, p, q, f, o) = urlparse.urlparse(configfile)
if s in ('http', 'ftp', 'file'):
configfh = urllib.urlopen(configfile)
try:
self.cfg.readfp(configfh)
except ConfigParser.MissingSectionHeaderError, e:
die(6, 'Error accessing URL: %s' % configfile)
else:
if os.access(configfile, os.R_OK):
try:
self.cfg.read(configfile)
except:
die(7, 'Syntax error reading file: %s' % configfile)
else:
die(6, 'Error accessing file: %s' % configfile)
def update(self, configfile):
for section in ('variables', 'vars', 'DEFAULT'):
if section in self.cfg.sections():
for option in self.cfg.options(section):
variables[option] = self.cfg.get(section, option)
for section in self.cfg.sections():
if section in ('main', 'repos', 'variables', 'vars', 'DEFAULT'):
continue
else:
### Check if section has appended arch
for arch in archs.keys():
if section.endswith('-%s' % arch):
archlist = (arch,)
distname = section.split('-%s' % arch)[0]
break
else:
archlist = self.getoption(section, 'arch', self.arch).split()
distname = section
### Add a distribution for each arch
for arch in archlist:
dist = Dist(distname, arch, self)
dist.arch = arch
dist.metadata = self.metadata.split()
dist.enabled = True
dist.promoteepoch = True
dist.fuseiso = True
dist.unionfs = True
dist.systemid = None
for option in self.cfg.options(section):
if option in ('iso', 'name', 'release', 'repo', 'rhnrelease'):
setattr(dist, option, self.cfg.get(section, option))
elif option in ('arch', 'dist'):
pass
elif option in ('disabled',):
dist.enabled = self.cfg.get(section, option) in disable
elif option in ('fuseiso',):
dist.fuseiso = self.cfg.get(section, option) not in disable
elif option in ('unionfs',):
dist.unionfs = self.cfg.get(section, option) not in disable
elif option in ('metadata',):
setattr(dist, option, self.cfg.get(section, option).split())
elif option in ('promoteepoch',):
dist.promoteepoch = self.cfg.get(section, option) not in disable
elif option in ('systemid',):
dist.systemid = self.cfg.get(section, option)
elif option in ('sslcert',):
dist.sslcert = self.cfg.get(section, option)
elif option in ('sslkey',):
dist.sslkey = self.cfg.get(section, option)
elif option in ('sslca',):
dist.sslca = self.cfg.get(section, option)
else:
dist.repos.append(Repo(option, self.cfg.get(section, option), dist, self))
dist.repos.sort(reposort)
dist.rewrite()
self.alldists.append(dist)
if dist.enabled:
self.dists.append(dist)
else:
info(5, '%s: %s is disabled' % (dist.nick, dist.name))
self.alldists.sort(distsort)
self.dists.sort(distsort)
def getoption(self, section, option, var):
"Get an option from a section from configfile"
try:
var = self.cfg.get(section, option)
info(3, 'Setting option %s in section [%s] to: %s' % (option, section, var))
except ConfigParser.NoSectionError, e:
error(5, 'Failed to find section [%s]' % section)
except ConfigParser.NoOptionError, e:
# error(4, 'Failed to find option %s in [%s], set to default: %s' % (option, section, var))
info(5, 'Setting option %s in section [%s] to: %s (default)' % (option, section, var))
return var
class Dist:
def __init__(self, dist, arch, cf):
self.arch = arch
self.dist = dist
self.nick = dist + '-' + arch
if arch == 'none':
self.nick = dist
self.name = dist
self.dir = os.path.join(cf.wwwdir, self.nick)
self.iso = None
self.release = None
self.repos = []
self.rhnrelease = None
self.srcdir = cf.srcdir
self.discs = ()
self.isos = []
self.disabled = False
self.sslcert = None
self.sslkey = None
self.sslca = None
# def __repr__(self):
# for key, value in vars(self).iteritems():
# if isinstance(value, types.StringType):
# print key, '->', value
def rewrite(self):
"Rewrite (string) attributes to replace variables by other (string) attributes"
varlist = variables
varlist.update({'arch': self.arch,
'nick': self.nick,
'dist': self.dist,
'release': self.release,
'rhnrelease': self.rhnrelease})
for key, value in vars(self).iteritems():
if isinstance(value, types.StringType):
setattr(self, key, substitute(value, varlist))
for repo in self.repos:
varlist['repo'] = repo.name
repo.url = substitute(repo.url, varlist)
def findisos(self):
"Return a list of existing ISO files"
if not self.iso:
return
if not self.isos:
for file in self.iso.split(' '):
file = os.path.basename(file)
absfile = file
if not os.path.isabs(file):
absfile = os.path.join(cf.srcdir, self.nick, file)
info(6, '%s: Looking for ISO files matching %s' % (self.nick, absfile))
filelist = glob.glob(absfile)
if not filelist:
absfile = os.path.join(cf.srcdir, self.dist, file)
info(6, '%s: Looking for ISO files matching %s' % (self.nick, absfile))
filelist = glob.glob(absfile)
if not filelist:
absfile = os.path.join(cf.srcdir, 'iso', file)
info(6, '%s: Looking for ISO files matching %s' % (self.nick, absfile))
filelist = glob.glob(absfile)
if not filelist:
absfile = os.path.join(cf.srcdir, file)
info(6, '%s: Looking for ISO files matching %s' % (self.nick, absfile))
filelist = glob.glob(absfile)
filelist.sort()
for iso in filelist:
if os.path.isfile(iso) and iso not in self.isos:
self.isos.append(iso)
if self.isos:
info(5, '%s: Found %d ISO files at %s' % (self.nick, len(self.isos), absfile))
self.repos.append(Repo('os', '', self, cf))
self.repos.sort(reposort)
else:
info(4, '%s: No ISO files found !' % self.nick)
def listrepos(self, names=None):
ret = []
if names:
return [repo for repo in self.repos if repo.name in names]
else:
return self.repos
def genmetadata(self):
allsrcdirs = []
pathjoin = os.path.join
for repo in self.listrepos(op.repos):
if not repo.lock('generate'):
continue
if repo.name in ('os', 'core') and self.isos:
repo.url = None
srcdirs = [pathjoin(self.dir, disc) for disc in self.discs]
self.linksync(repo, srcdirs)
allsrcdirs.extend(srcdirs)
os_components = (
glob.glob(pathjoin(self.dir + '/disc1/*/base/comps.xml')) + # RHEL 4
glob.glob(pathjoin(self.dir + '/disc1/*/repodata/comps-*-core.xml')) + # RHEL 5
glob.glob(pathjoin(self.dir + '/disc1/repodata/*-comps*.xml')) + # RHEL 6
glob.glob(pathjoin(self.dir + '/disc1/repodata/*-comps.xml')) + # CentOS 6
glob.glob(pathjoin(self.dir + '/disc1/repodata/comps.xml')) # Scientific Linux 6
)
for file in os_components:
if not os.path.exists(pathjoin(self.srcdir, self.nick, 'os-comps.xml')):
copy(file, pathjoin(self.srcdir, self.nick, 'os-comps.xml'))
else:
self.linksync(repo, [repo.srcdir, repo.allsrcdir])
allsrcdirs.append(repo.srcdir)
allsrcdirs.append(repo.allsrcdir)
repo.check()
repo.createmd()
### After generation, write a sha1sum
repo.writesha1()
repo.unlock('generate')
# Finally generate 'all' repsitory
for repo in (Repo('all', '', self, cf),):
if not repo.lock('generate'):
continue
### Link all srcdirs from other repositories
self.linksync(Repo('all', '', self, cf), allsrcdirs)
repo.check()
repo.createmd()
### After generation, write a sha1sum
repo.writesha1()
repo.unlock('generate')
def linksync(self, repo, srcdirs=None):
if not srcdirs:
srcdirs = [repo.srcdir]
destdir = repo.wwwdir
srcfiles = listrpms(srcdirs, relative=destdir)
# srcfiles = [ (basename, relpath), ... ]
srcfiles.sort()
# uniq basenames
srcfiles = [f for i, f in enumerate(srcfiles)
if not i or f[0] != srcfiles[i - 1][0]]
info(5, '%s: Symlink %s packages from %s to %s' % (repo.dist.nick, repo.name, srcdirs, destdir))
mkdir(destdir)
destfiles = listrpmlinks(destdir)
# destfiles is a list of (link_target_base, link_target_dir) tuples
destfiles.sort()
pathjoin = os.path.join
def keyfunc(x):
# compare the basenames
return x[0]
changed = False
for srcfile, destfile in synciter(srcfiles, destfiles, key=keyfunc):
if srcfile is None:
# delete the link
base, targetdir = destfile
linkname = pathjoin(destdir, base)
info(5, 'Remove link: %s' % (linkname,))
if not op.dryrun:
os.unlink(linkname)
changed = True
elif destfile is None:
base, srcdir = srcfile
# create a new link
linkname = pathjoin(destdir, base)
target = pathjoin(srcdir, base)
info(5, 'New link: %s -> %s' % (linkname, target))
if not op.dryrun:
os.symlink(target, linkname)
changed = True
else:
# same bases
base, srcdir = srcfile
base2, curtarget = destfile
target = pathjoin(srcdir, base)
if target != curtarget:
info(5, 'Changed link %s: current: %s, should be: %s' % (base, curtarget, target))
linkname = pathjoin(destdir, base)
if not op.dryrun:
os.unlink(linkname)
os.symlink(target, linkname)
changed = True
if changed:
repo.changed = True
def mount(self):
"Loopback mount all ISOs"
discs = []
mountpoints = []
discnr = 0
if cf.shareiso:
mkdir(os.path.join(self.dir, 'iso'))
else:
remove(os.path.join(self.dir, 'iso'))
regexp = re.compile('.+[_-]CD[0-9]?\..+')
### FIXME: See if fuse module is loaded
if cf.cmd['fuseiso'] and cf.fuseiso and self.fuseiso:
opts = '-n'
extra_opts = '-oallow_other'
mount_cmd = cf.cmd['fuseiso']
else:
opts = '-o loop,ro'
extra_opts = ''
mount_cmd = cf.cmd['mount']
if readfile('/selinux/enforce') == '1':
opts = opts + ',context=system_u:object_r:httpd_sys_content_t:s0'
for iso in self.isos:
if cf.shareiso:
symlink(iso, os.path.join(self.dir, 'iso'))
discnr = discnr + 1
discstr = 'disc'
if regexp.match(iso, 1):
discstr = 'CD'
disc = '%s%s' % (discstr, discnr)
discs.append(disc)
mount = os.path.join(self.dir, disc)
if not os.path.isfile(cf.cmd['mount']):
die(4, 'mount command not %s' % cf.cmd['mount'])
mount2 = mountpoint(iso)
if not mount2:
if os.path.exists(mount) and not os.path.isdir(mount):
os.rename(mount, os.tempnam(os.path.dirname(mount), 'bak-'))
mkdir(mount)
if not os.path.ismount(mount):
info(2, '%s: Mount ISO %s to %s' % (self.nick, os.path.basename(iso), mount))
run('%s %s %s %s %s' % (mount_cmd, opts, iso, mount, extra_opts))
mountpoints.append(mount)
else:
if mount2 != mount:
# if os.path.exists(mount):
# remove(mount)
info(5, '%s: %s already mounted, symlink ISO to %s' % (self.nick, os.path.basename(iso), mount))
symlink(mount2, mount)
if cf.cmd['unionfs'] and cf.unionfs and self.unionfs:
### This will be the name of our filesystem (first column of /etc/mtab)
unionfs_name = "%s-%s-fuse" % (self.dist, self.arch)
### We need to make sure that our directory isn't already mounted (in the case of mrepo -g)
if not mountpoint(unionfs_name):
### Create the 'os' directory for the merged trees.
unionfs_mountpoint = os.path.join(self.dir, 'os')
mkdir(unionfs_mountpoint)
info(2, "%s -o allow_other,fsname=%s %s %s" %
(cf.cmd['unionfs'], unionfs_name,
':'.join(mountpoints), unionfs_mountpoint))
run("%s -o allow_other,fsname=%s %s %s" %
(cf.cmd['unionfs'], unionfs_name,
':'.join(mountpoints), unionfs_mountpoint))
return discs
def umount(self):
"Umount all mounted ISOs"
discnr = 0
regexp = re.compile('.+[_-]CD[0-9]?\..+')
### Remove any unionfs mounted directories first.
if os.path.ismount(os.path.join(self.dir, 'os')):
umount_cmd = 'fusermount -u'
info(2, '%s %s' % (umount_cmd, os.path.join(self.dir, 'os')))
run('%s %s' % (umount_cmd, os.path.join(self.dir, 'os')))
for iso in self.isos:
discnr = discnr + 1
discstr = 'disc'
if regexp.match(iso, 1):
discstr = 'CD'
mount = os.path.join(self.dir, discstr + str(discnr))
if not os.path.isfile(cf.cmd['umount']):
die(5, 'umount command not %s' % cf.cmd['umount'])
if os.path.ismount(mount):
if mountpoint(mount):
info(2, '%s: Unmount ISO %s from %s' % (self.nick, os.path.basename(iso), mount))
run('%s %s' % (cf.cmd['umount'], mount))
else:
info(2, '%s: Unmount ISO %s from %s' % (self.nick, os.path.basename(iso), mount))
run('%s %s' % ('fusermount -u', mount))
def pxe(self):
"Create PXE boot setup"
tftpbootdir = os.path.dirname(cf.tftpdir)
if cf.tftpdir and tftpbootdir and os.path.isdir(cf.tftpdir):
tftpdir = os.path.join(cf.tftpdir, self.nick)
mkdir(tftpdir)
info(1, '%s: Symlink pxe boot files to %s ' % (self.nick, tftpdir))
mkdir(os.path.join(tftpdir, 'pxelinux.cfg'))
### For Red Hat
for file in glob.glob(self.dir + '/disc1/images/pxeboot/initrd*.img'):
copy(file, tftpdir)
for file in glob.glob(self.dir + '/disc1/images/pxeboot/vmlinuz'):
copy(file, tftpdir)
if cf.pxelinux:
copy(cf.pxelinux, tftpdir)
def html(self):
"Put html information in repository"
mkdir(self.dir)
if not op.dryrun:
open(os.path.join(self.dir, '.title'), 'w').write(self.name)
symlink(os.path.join(cf.htmldir, 'HEADER.repo.shtml'), os.path.join(self.dir, 'HEADER.shtml'))
symlink(os.path.join(cf.htmldir, 'README.repo.shtml'), os.path.join(self.dir, 'README.shtml'))
class Repo:
def __init__(self, name, url, dist, cf):
self.name = name
self.url = url
self.dist = dist
self.srcdir = os.path.join(cf.srcdir, dist.nick, self.name)
self.allsrcdir = os.path.join(cf.srcdir, 'all', self.name)
self.wwwdir = os.path.join(dist.dir, 'RPMS.' + self.name)
self.changed = False
self.oldlist = set()
self.newlist = set()
def __repr__(self):
# return "%s/%s" % (self.dist.nick, self.name)
return self.name
def mirror(self):
"Check URL and pass on to mirror-functions."
global exitcode
### Do not mirror for repository 'all'
if self.name == 'all':
return
### Make a snapshot of the directory
self.oldlist = self.rpmlist()
self.newlist = self.oldlist
for url in self.url.split():
try:
info(2, '%s: Mirror packages from %s to %s' % (self.dist.nick, url, self.srcdir))
s, l, p, q, f, o = urlparse.urlparse(url)
if s not in op.types:
info(4, 'Ignoring mirror action for type %s' % s)
continue
if s in ('rsync', ):
mirrorrsync(url, self.srcdir)
elif s in ('ftp', ):
if cf.cmd['mirrordir']:
mirrormirrordir(url, self.srcdir)
else:
mirrorlftp(url, self.srcdir, self.dist)
elif s in ('fish', 'http', 'https', 'sftp'):
mirrorlftp(url, self.srcdir, self.dist)
elif s in ('file', ''):
mirrorfile(url, self.srcdir)
elif s in ('mrepo', ):
mirrormrepo(url, self.srcdir)
elif s in ('mc', ):
mirrormirrordir(url, self.srcdir)
elif s in ('rhn', 'rhns'):
mirrorrhnget(url, self.srcdir, self.dist)
elif s in ('you', ):
mirroryouget(url, self.srcdir, self.dist)
elif s in ('reposync', 'reposyncs', 'reposyncf'):
mirrorreposync(url, self.srcdir, '%s-%s' % (self.dist.nick, self.name), self.dist)
else:
error(2, 'Scheme %s:// not implemented yet (in %s)' % (s, url))
except mrepoMirrorException, e:
error(0, 'Mirroring failed for %s with message:\n %s' % (url, e.value))
exitcode = 2
if not self.url:
### Create directory in case no URL is given
mkdir(self.srcdir)
### Make a snapshot of the directory
self.newlist = self.rpmlist()
def rpmlist(self):
"Capture a list of packages in the repository"
filelist = set()
### os.walk() is a python 2.4 feature
# for root, dirs, files in os.walk(self.srcdir):
# for file in files:
# if os.path.exists(file) and file.endswith('.rpm'):
# size = os.stat(os.path.join(root, file)).st_size
# filelist.add( (file, size) )
### os.path.walk() goes back further
def addfile((filelist, ), path, files):
for file in files:
if os.path.exists(os.path.join(path, file)) and file.endswith('.rpm'):
size = os.stat(os.path.join(path, file)).st_size
filelist.add((file, size))
os.path.walk(self.srcdir, addfile, (filelist,))
return filelist
def check(self):
"Return what repositories require an update and write .newsha1sum"
if not os.path.isdir(self.wwwdir):
return
sha1file = os.path.join(self.wwwdir, '.sha1sum')
remove(sha1file + '.tmp')
cursha1 = sha1dir(self.wwwdir)
if op.force:
pass
elif os.path.isfile(sha1file):
oldsha1 = open(sha1file).read()
if cursha1 != oldsha1:
info(2, '%s: Repository %s has new packages.' % (self.dist.nick, self.name))
else:
info(5, '%s: Repository %s has not changed. Skipping.' % (self.dist.nick, self.name))
return
else:
info(5, '%s: New repository %s detected.' % (self.dist.nick, self.name))
writesha1(sha1file + '.tmp', cursha1)
self.changed = True
def writesha1(self):
"Verify .newsha1sum and write a .sha1sum file per repository"
### FIXME: Repository 'all' got lost when introducing Repo class
sha1file = os.path.join(self.wwwdir, '.sha1sum')
if os.path.isfile(sha1file + '.tmp'):
cursha1 = sha1dir(self.wwwdir)
tmpsha1 = open(sha1file + '.tmp').read()
remove(sha1file + '.tmp')
if cursha1 == tmpsha1:
writesha1(sha1file, cursha1)
else:
info(5, '%s: Checksum is different. expect: %s, got: %s' % (self.dist.nick, cursha1, tmpsha1))
info(1, '%s: Directory changed during generating %s repo, please generate again.' % (self.dist.nick, self.name))
def lock(self, action):
if op.dryrun:
return True
lockfile = os.path.join(cf.lockdir, self.dist.nick, action + '-' + self.name + '.lock')
mkdir(os.path.dirname(lockfile))
try:
fd = os.open(lockfile, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600)
info(6, '%s: Setting lock %s' % (self.dist.nick, lockfile))
os.write(fd, '%d' % os.getpid())
os.close(fd)
return True
except:
if os.path.exists(lockfile):
pid = open(lockfile).read()
if os.path.exists('/proc/%s' % pid):
error(0, '%s: Found existing lock %s owned by pid %s' % (self.dist.nick, lockfile, pid))
else:
info(6, '%s: Removing stale lock %s' % (self.dist.nick, lockfile))
os.unlink(lockfile)
self.lock(action)
return True
else:
error(0, '%s: Lockfile %s does not exist. Cannot lock. Parallel universe ?' % (self.dist.nick, lockfile))
return False
def unlock(self, action):
if op.dryrun:
return True
lockfile = os.path.join(cf.lockdir, self.dist.nick, action + '-' + self.name + '.lock')
info(6, '%s: Removing lock %s' % (self.dist.nick, lockfile))
if os.path.exists(lockfile):
pid = open(lockfile).read()
if pid == '%s' % os.getpid():
os.unlink(lockfile)
else:
error(0, '%s: Existing lock %s found owned by another process with pid %s. This should NOT happen.' % (self.dist.nick, lockfile, pid))
else:
error(0, '%s: Lockfile %s does not exist. Cannot unlock. Something fishy here ?' % (self.dist.nick, lockfile))
def createmd(self):
metadata = ('apt', 'createrepo', 'repomd', 'repoview', 'yum')
index = ('repoview',)
if not self.changed and not op.force:
return
try:
### Generate repository metadata
for md in self.dist.metadata:
if md in ('createrepo', 'repomd'):
self.repomd()
elif md in ('yum',):
self.yum()
elif md in ('apt',):
self.apt()
elif md not in index:
error(0, 'The %s metadata is unknown.' % md)
### Generate repository index
for md in self.dist.metadata:
if md in ('repoview',):
self.repoview()
elif md not in metadata:
error(0, 'The %s index is unknown.' % md)
except mrepoGenerateException, e:
error(0, 'Generating repo failed for %s with message:\n %s' % (self.name, e.value))
exitcode = 2
def repomd(self):
"Create a repomd repository"
if not cf.cmd['createrepo']:
raise mrepoGenerateException('Command createrepo is not found. Skipping.')
### Find the createrepo version we are using (due to groupfile usage changes)
createrepo_version = None
groupfilename = 'comps.xml'
sys.path.append("/usr/share/createrepo")
try:
try:
import createrepo
createrepo_version = createrepo.__version__
del createrepo
except ImportError:
import genpkgmetadata
createrepo_version = genpkgmetadata.__version__
del genpkgmetadata
except ImportError:
pass
sys.path.remove("/usr/share/createrepo")
### If version < 0.4.6, then use the old createrepo behaviour
if not createrepo_version:
error(0, '%s: Version of createrepo could not be found. Assuming newer than 0.4.6.' % self.dist.nick)
elif vercmp(createrepo_version, '0.4.6') < 0:
groupfilename = 'RPMS.%s/comps.xml' % self.name
opts = ' ' + cf.createrepooptions
if op.force:
opts = ' --pretty' + opts
if op.verbose <= 2:
opts = ' --quiet' + opts
elif op.verbose >= 4:
opts = ' -v' + opts
if not self.dist.promoteepoch:
opts = opts + ' -n'
if os.path.isdir(self.wwwdir):
repoopts = opts
if cf.cachedir:
cachedir = os.path.join(cf.cachedir, self.dist.nick, self.name)
mkdir(cachedir)
repoopts = repoopts + ' --cachedir "%s"' % cachedir
if os.path.isdir(os.path.join(self.wwwdir, '.olddata')):
remove(os.path.join(self.wwwdir, '.olddata'))
groupfile = os.path.join(cf.srcdir, self.dist.nick, self.name + '-comps.xml')
if os.path.isfile(groupfile):
symlink(groupfile, os.path.join(self.wwwdir, 'comps.xml'))
repoopts = repoopts + ' --groupfile "%s"' % groupfile
info(2, '%s: Create repomd repository for %s' % (self.dist.nick, self.name))
ret = run('%s %s %s' % (cf.cmd['createrepo'], repoopts, self.wwwdir))
if ret:
raise(mrepoGenerateException('%s failed with return code: %s' % (cf.cmd['createrepo'], ret)))
def yum(self):
"Create a (old-style) yum repository"
if not cf.cmd['yumarch']:
return
opts = ''
if op.verbose <= 2:
opts = ' -q' + opts
elif op.verbose == 4:
opts = ' -v' + opts
elif op.verbose >= 5:
opts = ' -vv' + opts
if op.dryrun:
opts = opts + ' -n'
if os.path.exists(self.wwwdir):
if os.path.isdir(os.path.join(self.wwwdir, '.oldheaders')):
remove(os.path.join(self.wwwdir, '.oldheaders'))
info(2, '%s: Create (old-style) yum repository for %s' % (self.dist.nick, self.name))
ret = run('%s %s -l %s' % (cf.cmd['yumarch'], opts, self.wwwdir))
if ret:
raise(mrepoGenerateException('%s failed with return code: %s' % (cf.cmd['yumarch'], ret)))
def apt(self):
"Create an (old-style) apt repository"
if not cf.cmd['genbasedir']:
return
opts = ''
if op.verbose >= 3:
opts = ' --progress' + opts
mkdir(os.path.join(self.dist.dir, 'base'))
### Write out /srcdir/nick/base/release
# TODO: should not be done per repository
releasefile = os.path.join(self.dist.dir, 'base', 'release')
if not os.path.exists(releasefile):
open(releasefile, 'w').write(
'Origin: %s\n'\
'Label: %s\n'\
'Suite: Unknown\n'\
'Codename: %s\n'\
'Date: unknown\n'\
'Architectures: %s\n'\
'Components: \n'\
'Description: %s\n'\
'MD5Sum:\n'\
% (os.uname()[1], self.dist.name, self.dist.nick, self.dist.arch, self.dist.name))
### Write out /srcdir/nick/base/release.repo
releasefile = os.path.join(self.dist.dir, 'base', 'release.' + self.name)
if not os.path.exists(releasefile):
open(releasefile, 'w').write(
'Archive: %s\n'\
'Component: %s\n'\
'Version: %s\n'\
'Origin: %s\n'\
'Label: Repository %s for %s\n'\