-
Notifications
You must be signed in to change notification settings - Fork 86
/
cli.py
executable file
·2694 lines (2305 loc) · 108 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python -t
# This program 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 2 of the License, or
# (at your option) any later version.
#
# 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 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 2005 Duke University
# Written by Seth Vidal
"""
Command line interface yum class and related.
"""
import os
import re
import sys
import time
import random
import logging
import math
from optparse import OptionParser,OptionGroup,SUPPRESS_HELP
import rpm
import ctypes
import glob
from weakref import proxy as weakref
import output
import shell
import yum
import yum.Errors
import yum.logginglevels
import yum.misc
import yum.plugins
from rpmUtils.arch import isMultiLibArch
from yum import _, P_
from yum.rpmtrans import RPMTransaction
import signal
import yumcommands
from yum.i18n import to_unicode, to_utf8, exception2msg
# This is for yum-utils/yumdownloader in RHEL-5, where it isn't importing this
# directly but did do "from cli import *", and we did have this in 3.2.22. I
# just _love_ how python re-exports these by default.
# pylint: disable-msg=W0611
from yum.packages import parsePackages
# pylint: enable-msg=W0611
def sigquit(signum, frame):
"""SIGQUIT handler for the yum cli. This function will print an
error message and exit the program.
:param signum: unused
:param frame: unused
"""
print >> sys.stderr, "Quit signal sent - exiting immediately"
sys.exit(1)
class CliError(yum.Errors.YumBaseError):
"""Command line interface related Exception."""
def __init__(self, args=''):
yum.Errors.YumBaseError.__init__(self)
self.args = args
def sys_inhibit(what, who, why, mode):
""" Tell systemd to inhibit shutdown, via. dbus. """
try:
import dbus
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.login1',
'/org/freedesktop/login1')
iface = dbus.Interface(proxy, 'org.freedesktop.login1.Manager')
return iface.Inhibit(what, who, why, mode)
except:
return None
class YumBaseCli(yum.YumBase, output.YumOutput):
"""This is the base class for yum cli."""
def __init__(self):
# handle sigquit early on
signal.signal(signal.SIGQUIT, sigquit)
yum.YumBase.__init__(self)
output.YumOutput.__init__(self)
logging.basicConfig()
self.logger = logging.getLogger("yum.cli")
self.verbose_logger = logging.getLogger("yum.verbose.cli")
self.yum_cli_commands = {}
self.use_txmbr_in_callback = True
self.registerCommand(yumcommands.InstallCommand())
self.registerCommand(yumcommands.UpdateCommand())
self.registerCommand(yumcommands.InfoCommand())
self.registerCommand(yumcommands.ListCommand())
self.registerCommand(yumcommands.EraseCommand())
self.registerCommand(yumcommands.AutoremoveCommand())
self.registerCommand(yumcommands.GroupsCommand())
self.registerCommand(yumcommands.MakeCacheCommand())
self.registerCommand(yumcommands.CleanCommand())
self.registerCommand(yumcommands.ProvidesCommand())
self.registerCommand(yumcommands.CheckUpdateCommand())
self.registerCommand(yumcommands.SearchCommand())
self.registerCommand(yumcommands.UpgradeCommand())
self.registerCommand(yumcommands.LocalInstallCommand())
self.registerCommand(yumcommands.ResolveDepCommand())
self.registerCommand(yumcommands.ShellCommand())
self.registerCommand(yumcommands.DepListCommand())
self.registerCommand(yumcommands.RepoListCommand())
self.registerCommand(yumcommands.HelpCommand())
self.registerCommand(yumcommands.ReInstallCommand())
self.registerCommand(yumcommands.DowngradeCommand())
self.registerCommand(yumcommands.VersionCommand())
self.registerCommand(yumcommands.HistoryCommand())
self.registerCommand(yumcommands.CheckRpmdbCommand())
self.registerCommand(yumcommands.DistroSyncCommand())
self.registerCommand(yumcommands.LoadTransactionCommand())
self.registerCommand(yumcommands.SwapCommand())
self.registerCommand(yumcommands.RepoPkgsCommand())
self.registerCommand(yumcommands.UpdateinfoCommand())
self.registerCommand(yumcommands.UpdateMinimalCommand())
self.registerCommand(yumcommands.FSSnapshotCommand())
self.registerCommand(yumcommands.FSCommand())
def registerCommand(self, command):
"""Register a :class:`yumcommands.YumCommand` so that it can be called by
any of the names returned by its
:func:`yumcommands.YumCommand.getNames` method.
:param command: the :class:`yumcommands.YumCommand` to register
"""
for name in command.getNames():
if name in self.yum_cli_commands:
raise yum.Errors.ConfigError(_('Command "%s" already defined') % name)
self.yum_cli_commands[name] = command
def doRepoSetup(self, thisrepo=None, dosack=1):
"""Grab the repomd.xml for each enabled and set up the basics
of the repository.
:param thisrepo: the repository to set up
:param dosack: whether to get the repo sack
"""
if self._repos and thisrepo is None:
return self._repos
if not thisrepo:
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Setting up repositories'))
# Call parent class to do the bulk of work
# (this also ensures that reposetup plugin hook is called)
if thisrepo:
yum.YumBase._getRepos(self, thisrepo=thisrepo, doSetup=True)
else:
yum.YumBase._getRepos(self, thisrepo=thisrepo)
if dosack: # so we can make the dirs and grab the repomd.xml but not import the md
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Reading repository metadata in from local files'))
self._getSacks(thisrepo=thisrepo)
return self._repos
def _makeUsage(self):
"""
Format an attractive usage string for yum, listing subcommand
names and summary usages.
"""
usage = 'yum [options] COMMAND\n\nList of Commands:\n\n'
commands = yum.misc.unique([x for x in self.yum_cli_commands.values()
if not (hasattr(x, 'hidden') and x.hidden)])
commands.sort(key=lambda x: x.getNames()[0])
for command in commands:
# XXX Remove this when getSummary is common in plugins
try:
summary = command.getSummary()
usage += "%-14s %s\n" % (command.getNames()[0], summary)
except (AttributeError, NotImplementedError):
usage += "%s\n" % command.getNames()[0]
return usage
def _parseSetOpts(self, setopts):
"""parse the setopts list handed to us and saves the results as
repo_setopts and main_setopts in the yumbase object"""
repoopts = {}
mainopts = yum.misc.GenericHolder()
mainopts.items = []
bad_setopt_tm = []
bad_setopt_ne = []
for item in setopts:
vals = item.split('=')
if len(vals) > 2:
bad_setopt_tm.append(item)
continue
if len(vals) < 2:
bad_setopt_ne.append(item)
continue
k, v = [i.strip() for i in vals]
period = k.rfind('.')
if period != -1:
repo = k[:period]
k = k[period+1:]
if repo not in repoopts:
repoopts[repo] = yum.misc.GenericHolder()
repoopts[repo].items = []
setattr(repoopts[repo], k, v)
repoopts[repo].items.append(k)
else:
setattr(mainopts, k, v)
mainopts.items.append(k)
self.main_setopts = mainopts
self.repo_setopts = repoopts
return bad_setopt_tm, bad_setopt_ne
def getOptionsConfig(self, args):
"""Parse command line arguments, and set up :attr:`self.conf` and
:attr:`self.cmds`, as well as logger objects in base instance.
:param args: a list of command line arguments
"""
self.optparser = YumOptionParser(base=self, usage=self._makeUsage())
# Parse only command line options that affect basic yum setup
opts = self.optparser.firstParse(args)
# Just print out the version if that's what the user wanted
if opts.version:
print yum.__version__
opts.quiet = True
opts.verbose = False
# go through all the setopts and set the global ones
bad_setopt_tm, bad_setopt_ne = self._parseSetOpts(opts.setopts)
if self.main_setopts:
for opt in self.main_setopts.items:
setattr(opts, opt, getattr(self.main_setopts, opt))
# get the install root to use
root = self.optparser.getRoot(opts)
if opts.quiet:
opts.debuglevel = 0
if opts.verbose:
opts.debuglevel = opts.errorlevel = 6
# Read up configuration options and initialise plugins
try:
pc = self.preconf
pc.fn = opts.conffile
pc.root = root
pc.init_plugins = not opts.noplugins
pc.plugin_types = (yum.plugins.TYPE_CORE,
yum.plugins.TYPE_INTERACTIVE)
pc.optparser = self.optparser
pc.debuglevel = opts.debuglevel
pc.errorlevel = opts.errorlevel
pc.disabled_plugins = self.optparser._splitArg(opts.disableplugins)
pc.enabled_plugins = self.optparser._splitArg(opts.enableplugins)
pc.releasever = opts.releasever
self.conf
for item in bad_setopt_tm:
msg = "Setopt argument has multiple values: %s"
self.logger.warning(msg % item)
for item in bad_setopt_ne:
msg = "Setopt argument has no value: %s"
self.logger.warning(msg % item)
# now set all the non-first-start opts from main from our setopts
if self.main_setopts:
for opt in self.main_setopts.items:
if not hasattr(self.conf, opt):
msg ="Main config did not have a %s attr. before setopt"
self.logger.warning(msg % opt)
setattr(self.conf, opt, getattr(self.main_setopts, opt))
except yum.Errors.ConfigError, e:
self.logger.critical(_('Config error: %s'), e)
sys.exit(1)
except IOError, e:
e = '%s: %s' % (to_unicode(e.args[1]), repr(e.filename))
self.logger.critical(_('Config error: %s'), e)
sys.exit(1)
except ValueError, e:
self.logger.critical(_('Options error: %s'), e)
sys.exit(1)
# update usage in case plugins have added commands
self.optparser.set_usage(self._makeUsage())
self.plugins.run('args', args=args)
# Now parse the command line for real and
# apply some of the options to self.conf
(opts, self.cmds) = self.optparser.setupYumConfig(args=args)
if opts.version:
opts.quiet = True
opts.verbose = False
# Check that firstParse didn't miss anything, and warn the user if it
# did ... because this is really magic, and unexpected.
if opts.quiet:
opts.debuglevel = 0
if opts.verbose:
opts.debuglevel = opts.errorlevel = 6
if opts.debuglevel != pc.debuglevel or opts.errorlevel != pc.errorlevel:
self.logger.warning(_("Ignored option -q, -v, -d or -e (probably due to merging: -yq != -y -q)"))
# getRoot() changes it, but then setupYumConfig() changes it back. So
# don't test for this, if we are using --installroot.
if root == '/' and opts.conffile != pc.fn:
self.logger.warning(_("Ignored option -c (probably due to merging -yc != -y -c)"))
if opts.version:
self.conf.cache = 1
yum_progs = self.run_with_package_names
done = False
def sm_ui_time(x):
return time.strftime("%Y-%m-%d %H:%M", time.gmtime(x))
def sm_ui_date(x): # For changelogs, there is no time
return time.strftime("%Y-%m-%d", time.gmtime(x))
for pkg in sorted(self.rpmdb.returnPackages(patterns=yum_progs)):
# We should only have 1 version of each...
if done: print ""
done = True
if pkg.epoch == '0':
ver = '%s-%s.%s' % (pkg.version, pkg.release, pkg.arch)
else:
ver = '%s:%s-%s.%s' % (pkg.epoch,
pkg.version, pkg.release, pkg.arch)
name = "%s%s%s" % (self.term.MODE['bold'], pkg.name,
self.term.MODE['normal'])
print _(" Installed: %s-%s at %s") %(name, ver,
sm_ui_time(pkg.installtime))
print _(" Built : %s at %s") % (to_unicode(pkg.packager),
sm_ui_time(pkg.buildtime))
print _(" Committed: %s at %s") % (to_unicode(pkg.committer),
sm_ui_date(pkg.committime))
sys.exit(0)
if opts.sleeptime is not None:
sleeptime = random.randrange(opts.sleeptime*60)
else:
sleeptime = 0
# save our original args out
self.args = args
# save out as a nice command string
self.cmdstring = 'yum '
for arg in self.args:
self.cmdstring += '%s ' % arg
try:
self.parseCommands() # before we return check over the base command + args
# make sure they match/make sense
except CliError:
sys.exit(1)
# run the sleep - if it's unchanged then it won't matter
time.sleep(sleeptime)
def parseCommands(self):
"""Read :attr:`self.cmds` and parse them out to make sure that
the requested base command and argument makes any sense at
all. This function will also set :attr:`self.basecmd` and
:attr:`self.extcmds`.
"""
self.verbose_logger.debug('Yum version: %s', yum.__version__)
self.verbose_logger.log(yum.logginglevels.DEBUG_4,
'COMMAND: %s', self.cmdstring)
self.verbose_logger.log(yum.logginglevels.DEBUG_4,
'Installroot: %s', self.conf.installroot)
if len(self.conf.commands) == 0 and len(self.cmds) < 1:
self.cmds = self.conf.commands
else:
self.conf.commands = self.cmds
if len(self.cmds) < 1:
self.logger.critical(_('You need to give some command'))
self.usage()
raise CliError
self.basecmd = self.cmds[0] # our base command
self.extcmds = self.cmds[1:] # out extended arguments/commands
if len(self.extcmds) > 0:
self.verbose_logger.log(yum.logginglevels.DEBUG_4,
'Ext Commands:\n')
for arg in self.extcmds:
self.verbose_logger.log(yum.logginglevels.DEBUG_4, ' %s', arg)
if self.basecmd not in self.yum_cli_commands:
self.logger.critical(_('No such command: %s. Please use %s --help'),
self.basecmd, sys.argv[0])
raise CliError
self._set_repos_cache_req()
self.yum_cli_commands[self.basecmd].doCheck(self, self.basecmd, self.extcmds)
def _set_repos_cache_req(self, warning=True):
""" Set the cacheReq attribute from the commands to the repos. """
cmd = self.yum_cli_commands[self.basecmd]
cacheReq = 'write'
if hasattr(cmd, 'cacheRequirement'):
cacheReq = cmd.cacheRequirement(self, self.basecmd, self.extcmds)
# The main thing we want to do here is that if the user has done a
# "yum makecache fast" or has yum-cron running or something, then try
# not to update the repo. caches ... thus. not turning 0.5s ops. into
# 100x longer ops.
# However if the repos. are not in sync. that's probably not going to
# work well (Eg. user enables updates-testing). Also give a warning if
# they are _really_ old.
ts_min = None
ts_max = None
for repo in self.repos.listEnabled():
try: rts = os.stat(repo.metadata_cookie).st_mtime
except (yum.Errors.RepoError, OSError):
ts_min = None
break
if not ts_min:
ts_min = rts
ts_max = rts
elif rts > ts_max:
ts_max = rts
elif rts < ts_min:
ts_min = rts
if ts_min:
# If caches are within 5 days of each other, they are ok to work
# together (lol, random numbers)...
if (ts_max - ts_min) > (60 * 60 * 24 * 5):
ts_min = None
elif ts_max > time.time():
ts_min = None
if not ts_min:
cacheReq = 'write'
all_obey = True
for repo in self.repos.sort():
repo._metadata_cache_req = cacheReq
if repo._matchExpireFilter():
all_obey = False
if warning and ts_min and (time.time() - ts_max) > (60 * 60 * 24 * 14):
# The warning makes no sense if we're already running a command
# that requires current repodata across all repos (such as "yum
# makecache" or others, depending on metadata_expire_filter), so
# don't give it if that's the case.
if all_obey:
return
self.logger.warning(_("Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast"))
def _shell_history_write(self):
if not hasattr(self, '_shell_history_cmds'):
return
if not self._shell_history_cmds:
return
data = self._shell_history_cmds
# Turn: [["a", "b"], ["c", "d"]] => "a b\nc d\n"
data = [" ".join(cmds) for cmds in data]
data.append('')
data = "\n".join(data)
self.history.write_addon_data('shell-cmds', data)
def doShell(self):
"""Run a shell-like interface for yum commands.
:return: a tuple containing the shell result number, and the
shell result messages
"""
yumshell = shell.YumShell(base=self)
# We share this array...
self._shell_history_cmds = yumshell._shell_history_cmds
if len(self.extcmds) == 0:
yumshell.cmdloop()
else:
yumshell.script()
del self._shell_history_cmds
return yumshell.result, yumshell.resultmsgs
def errorSummary(self, errstring):
"""Parse the error string for 'interesting' errors which can
be grouped, such as disk space issues.
:param errstring: the error string
:return: a string containing a summary of the errors
"""
summary = ''
# do disk space report first
p = re.compile('needs (\d+)(K|M)B on the (\S+) filesystem')
disk = {}
for m in p.finditer(errstring):
size_in_mb = int(m.group(1)) if m.group(2) == 'M' else math.ceil(int(m.group(1))/1024.0)
if m.group(3) not in disk:
disk[m.group(3)] = size_in_mb
if disk[m.group(3)] < size_in_mb:
disk[m.group(3)] = size_in_mb
if disk:
summary += _('Disk Requirements:\n')
for k in disk:
summary += P_(' At least %dMB more space needed on the %s filesystem.\n', ' At least %dMB more space needed on the %s filesystem.\n', disk[k]) % (disk[k], k)
# TODO: simplify the dependency errors?
# Fixup the summary
summary = _('Error Summary\n-------------\n') + summary
return summary
def waitForLock(self):
"""Establish the yum lock. If another process is already
holding the yum lock, by default this method will keep trying
to establish the lock until it is successful. However, if
:attr:`self.conf.exit_on_lock` is set to True, it will
raise a :class:`Errors.YumBaseError`.
"""
lockerr = ""
while True:
try:
self.doLock()
except yum.Errors.LockError, e:
if exception2msg(e) != lockerr:
lockerr = exception2msg(e)
self.logger.critical(lockerr)
if e.errno:
raise yum.Errors.YumBaseError, _("Can't create lock file; exiting")
if not self.conf.exit_on_lock:
self.logger.critical("Another app is currently holding the yum lock; waiting for it to exit...")
import utils
utils.show_lock_owner(e.pid, self.logger)
time.sleep(2)
else:
raise yum.Errors.YumBaseError, _("Another app is currently holding the yum lock; exiting as configured by exit_on_lock")
else:
break
def doCommands(self):
"""Call the base command, and pass it the extended commands or
arguments.
:return: (exit_code, [ errors ])
exit_code is::
0 = we're done, exit
1 = we've errored, exit with error string
2 = we've got work yet to do, onto the next stage
"""
# at this point we know the args are valid - we don't know their meaning
# but we know we're not being sent garbage
# setup our transaction set if the command we're using needs it
# compat with odd modules not subclassing YumCommand
needTs = True
needTsRemove = False
cmd = self.yum_cli_commands[self.basecmd]
if hasattr(cmd, 'needTs'):
needTs = cmd.needTs(self, self.basecmd, self.extcmds)
if not needTs and hasattr(cmd, 'needTsRemove'):
needTsRemove = cmd.needTsRemove(self, self.basecmd, self.extcmds)
if needTs or needTsRemove:
try:
self._getTs(needTsRemove)
except yum.Errors.YumBaseError, e:
return 1, [exception2msg(e)]
# This should already have been done at doCheck() time, but just in
# case repos. got added or something do it again.
self._set_repos_cache_req(warning=False)
return self.yum_cli_commands[self.basecmd].doCommand(self, self.basecmd, self.extcmds)
def doTransaction(self, inhibit={'what' : 'shutdown:idle',
'who' : 'yum API',
'why' : 'Running transaction', # i18n?
'mode' : 'block'}):
"""Take care of package downloading, checking, user
confirmation and actually running the transaction.
:return: a numeric return code, and optionally a list of
errors. A negative return code indicates that errors
occurred in the pre-transaction checks
"""
def _downloadonly_userconfirm(self):
# Note that we shouldn't just remove the 'd' option, or the options
# yum accepts will be different which is bad. So always accept it,
# but change the prompt.
dl_only = {'downloadonly' :
(u'd', _('d'), _('download'),
_('downloadonly'))}
if not stuff_to_download:
ret = self.userconfirm(extra=dl_only)
if ret == 'downloadonly':
ret = None
return ret
return self.userconfirm(prompt=_('Is this ok [y/d/N]: '),
extra=dl_only)
# just make sure there's not, well, nothing to do
if len(self.tsInfo) == 0:
self.verbose_logger.info(_('Trying to run the transaction but nothing to do. Exiting.'))
return -1
# NOTE: In theory we can skip this in -q -y mode, for a slight perf.
# gain. But it's probably doom to have a different code path.
lsts = self.listTransaction()
if self.verbose_logger.isEnabledFor(yum.logginglevels.INFO_1):
self.verbose_logger.log(yum.logginglevels.INFO_1, lsts)
elif self.conf.assumeno or not self.conf.assumeyes:
# If we are in quiet, and assumeyes isn't on we want to output
# at least the transaction list anyway.
self.logger.warn(lsts)
# Check which packages have to be downloaded
downloadpkgs = []
rmpkgs = []
stuff_to_download = False
install_only = True
for txmbr in self.tsInfo.getMembers():
if txmbr.ts_state not in ('i', 'u'):
install_only = False
po = txmbr.po
if po:
rmpkgs.append(po)
else:
stuff_to_download = True
po = txmbr.po
if po:
downloadpkgs.append(po)
# Close the connection to the rpmdb so that rpm doesn't hold the SIGINT
# handler during the downloads. self.ts is reinitialised later in this
# function anyway (initActionTs).
self.ts.close()
# Report the total download size to the user, so he/she can base
# the answer on this info
if not stuff_to_download:
self.reportRemoveSize(rmpkgs)
else:
self.reportDownloadSize(downloadpkgs, install_only)
cfr = self.tsInfo._check_future_rpmdbv
if (cfr is not None and
self.tsInfo.futureRpmDBVersion() != cfr[1]):
msg = _("future rpmdb ver mismatched saved transaction version,")
if cfr[2]:
msg += _(" ignoring, as requested.")
self.logger.critical(_(msg))
else:
msg += _(" aborting.")
raise yum.Errors.YumBaseError(msg)
# confirm with user
if self._promptWanted():
uc = None
if not self.conf.assumeno:
uc = _downloadonly_userconfirm(self)
if not uc:
self.verbose_logger.info(_('Exiting on user command'))
return -1
elif uc == 'downloadonly':
self.conf.downloadonly = True
if self.conf.downloadonly:
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Background downloading packages, then exiting:'))
else:
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Downloading packages:'))
problems = self.downloadPkgs(downloadpkgs, callback_total=self.download_callback_total_cb)
if len(problems) > 0:
errstring = ''
errstring += _('Error downloading packages:\n')
for key in problems:
errors = yum.misc.unique(problems[key])
for error in errors:
errstring += ' %s: %s\n' % (key, error)
raise yum.Errors.YumBaseError, errstring
# Check GPG signatures
if self.gpgsigcheck(downloadpkgs) != 0:
return -1
self.initActionTs()
# save our dsCallback out
dscb = self.dsCallback
self.dsCallback = None # dumb, dumb dumb dumb!
self.populateTs(keepold=0) # sigh
rcd_st = time.time()
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Running transaction check'))
msgs = self._run_rpm_check()
depsolve = False
if msgs:
rpmlib_only = True
for msg in msgs:
if msg.startswith('rpmlib('):
continue
rpmlib_only = False
if rpmlib_only:
print _("ERROR You need to update rpm to handle:")
else:
print _('ERROR with transaction check vs depsolve:')
depsolve = True
for msg in msgs:
print to_utf8(msg)
if rpmlib_only:
return 1, [_('RPM needs to be updated')]
if depsolve:
return 1, []
else:
return 1, [_('Please report this error in %s') % self.conf.bugtracker_url]
self.verbose_logger.debug('Transaction check time: %0.3f' % (time.time() - rcd_st))
tt_st = time.time()
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Running transaction test'))
self.ts.order() # order the transaction
self.ts.clean() # release memory not needed beyond this point
testcb = RPMTransaction(self, test=True)
tserrors = self.ts.test(testcb)
del testcb
if len(tserrors) > 0:
errstring = _('Transaction check error:\n')
for descr in tserrors:
errstring += ' %s\n' % to_unicode(descr)
raise yum.Errors.YumBaseError, errstring + '\n' + \
self.errorSummary(errstring)
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Transaction test succeeded'))
self.verbose_logger.debug('Transaction test time: %0.3f' % (time.time() - tt_st))
# unset the sigquit handler
signal.signal(signal.SIGQUIT, signal.SIG_DFL)
ts_st = time.time()
# Reinstalls broke in: 7115478c527415cb3c8317456cdf50024de89a94 ...
# I assume there's a "better" fix, but this fixes reinstalls and lets
# other options continue as is (and they seem to work).
have_reinstalls = False
for txmbr in self.tsInfo.getMembers():
if txmbr.reinstall:
have_reinstalls = True
break
if have_reinstalls:
self.initActionTs() # make a new, blank ts to populate
self.populateTs(keepold=0) # populate the ts
self.ts.check() #required for ordering
self.ts.order() # order
self.ts.clean() # release memory not needed beyond this point
# put back our depcheck callback
self.dsCallback = dscb
# setup our rpm ts callback
cb = RPMTransaction(self,
display=output.YumCliRPMCallBack(weakref(self)))
if self.conf.debuglevel < 2:
cb.display.output = False
inhibited = False
if inhibit:
fd = sys_inhibit(inhibit['what'], inhibit['who'],
inhibit['why'], inhibit['mode'])
if fd is not None:
msg = _('Running transaction (shutdown inhibited)')
inhibited = True
if not inhibited:
msg = _('Running transaction')
# Whenever we upgrade a shared library (and its dependencies) which the
# yum process itself may dlopen() post-transaction (e.g. in a plugin
# hook), we may end up in a situation where the upgraded library and
# the pre-transaction version of a library it depends on which is ABI
# incompatible are loaded in memory at the same time, leading to
# unpredictable behavior and possibly a crash. Let's avoid that by
# preloading all such dynamically loaded libraries pre-transaction so
# that dlopen(), if called post-transaction, uses those instead of
# loading the newly installed versions.
preload = {
# Loaded by libcurl, see BZ#1458841
'nss-sysinit': ['libnsssysinit.so'],
}
for pkg in preload:
# Only preload the libs if the package is actually installed and we
# are changing it with the transaction
if not self.tsInfo.matchNaevr(name=pkg) or \
not self.rpmdb.searchNevra(name=pkg):
continue
for lib in preload[pkg]:
try:
ctypes.cdll.LoadLibrary(lib)
self.verbose_logger.log(
yum.logginglevels.DEBUG_4,
_('Preloaded shared library %s') % lib
)
except Exception as e:
self.verbose_logger.log(
yum.logginglevels.DEBUG_4,
_('Could not preload shared library %s: %s') % (lib, e)
)
self.verbose_logger.log(yum.logginglevels.INFO_2, msg)
resultobject = self.runTransaction(cb=cb)
# fd is either None or dbus.UnifFD() and the real API to close is thus:
# if fd is not None: os.close(fd.take())
# ...but this is easier, doesn't require a test and works.
del fd
self.verbose_logger.debug('Transaction time: %0.3f' % (time.time() - ts_st))
# close things
self.verbose_logger.log(yum.logginglevels.INFO_1,
self.postTransactionOutput())
# put back the sigquit handler
signal.signal(signal.SIGQUIT, sigquit)
return resultobject.return_code
def gpgsigcheck(self, pkgs):
"""Perform GPG signature verification on the given packages,
installing keys if possible.
:param pkgs: a list of package objects to verify the GPG
signatures of
:return: non-zero if execution should stop due to an error
:raises: Will raise :class:`YumBaseError` if there's a problem
"""
for po in pkgs:
result, errmsg = self.sigCheckPkg(po)
if result == 0:
# Verified ok, or verify not req'd
continue
elif result == 1:
ay = self.conf.assumeyes and not self.conf.assumeno
if not sys.stdin.isatty() and not ay:
raise yum.Errors.YumBaseError, \
_('Refusing to automatically import keys when running ' \
'unattended.\nUse "-y" to override.')
# the callback here expects to be able to take options which
# userconfirm really doesn't... so fake it
self.getKeyForPackage(po, lambda x, y, z: self.userconfirm())
else:
# Fatal error
raise yum.Errors.YumBaseError, errmsg
return 0
def _maybeYouMeant(self, arg):
""" If install argument doesn't match with case, tell the user. """
matches = self.doPackageLists(patterns=[arg], ignore_case=True)
matches = matches.installed + matches.available
matches = set(map(lambda x: x.name, matches))
if matches:
msg = self.fmtKeyValFill(_(' * Maybe you meant: '),
", ".join(matches))
self.verbose_logger.log(yum.logginglevels.INFO_2, to_unicode(msg))
def _checkMaybeYouMeant(self, arg, always_output=True, rpmdb_only=False):
""" If the update/remove argument doesn't match with case, or due
to not being installed, tell the user. """
# always_output is a wart due to update/remove not producing the
# same output.
# if it is a grouppattern then none of this is going to make any sense
# skip it.
if not arg or arg[0] == '@':
return
pkgnarrow='all'
if rpmdb_only:
pkgnarrow='installed'
matches = self.doPackageLists(pkgnarrow=pkgnarrow, patterns=[arg], ignore_case=False)
if (matches.installed or (not matches.available and
self.returnInstalledPackagesByDep(arg))):
return # Found a match so ignore
hibeg = self.term.MODE['bold']
hiend = self.term.MODE['normal']
if matches.available:
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Package(s) %s%s%s available, but not installed.'),
hibeg, arg, hiend)
return
# No package name, so do the maybeYouMeant thing here too
matches = self.doPackageLists(pkgnarrow=pkgnarrow, patterns=[arg], ignore_case=True)
if not matches.installed and matches.available:
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('Package(s) %s%s%s available, but not installed.'),
hibeg, arg, hiend)
return
matches = set(map(lambda x: x.name, matches.installed))
if always_output or matches:
self.verbose_logger.log(yum.logginglevels.INFO_2,
_('No package %s%s%s available.'),
hibeg, arg, hiend)
if matches:
msg = self.fmtKeyValFill(_(' * Maybe you meant: '),
", ".join(matches))
self.verbose_logger.log(yum.logginglevels.INFO_2, msg)
def _install_upgraded_requires(self, txmbrs):
"""Go through the given txmbrs, and for any to be installed packages
look for their installed deps. and try to upgrade them, if the
configuration is set. Returning any new transaction members to be
isntalled.
:param txmbrs: a list of :class:`yum.transactioninfo.TransactionMember` objects
:return: a list of :class:`yum.transactioninfo.TransactionMember` objects
"""
if not self.conf.upgrade_requirements_on_install:
return []
ret = []
done = set()
def _pkg2ups(pkg, reqpo=None):
if pkg.name in done:
return []
if reqpo is None:
reqpo = pkg
done.add(pkg.name)
uret = []
for req in pkg.requires:
for npkg in self.returnInstalledPackagesByDep(req):
if npkg.name in done:
continue
uret += self.update(name=npkg.name, requiringPo=reqpo)
uret += _pkg2ups(npkg, reqpo=reqpo)
return uret
for txmbr in txmbrs:
for rtxmbr, T in txmbr.relatedto:
ret += _pkg2ups(rtxmbr)
ret += _pkg2ups(txmbr.po)
return ret
def installPkgs(self, userlist, basecmd='install', repoid=None):
"""Attempt to take the user specified list of packages or
wildcards and install them, or if they are installed, update
them to a newer version. If a complete version number is
specified, attempt to upgrade (or downgrade if they have been
removed) them to the specified version.
:param userlist: a list of names or wildcards specifying
packages to install
:return: (exit_code, [ errors ])
exit_code is::
0 = we're done, exit
1 = we've errored, exit with error string
2 = we've got work yet to do, onto the next stage