forked from rpm-software-management/yum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yum-updatesd.py
executable file
·882 lines (717 loc) · 30.5 KB
/
yum-updatesd.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
#!/usr/bin/python -tt
# 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 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.
# (c)2006 Duke University, Red Hat, Inc.
# Seth Vidal <[email protected]>
# Jeremy Katz <[email protected]>
#TODO:
# - clean up config and work on man page for docs
# - need to be able to cancel downloads. requires some work in urlgrabber
# - what to do if we're asked to exit while updates are being applied?
# - what to do with the lock around downloads/updates
# since it takes me time every time to figure this out again, here's how to
# queue a check with dbus-send. adjust appropriately for other methods
# $ dbus-send --system --print-reply --type=method_call \
# --dest=edu.duke.linux.yum /Updatesd edu.duke.linux.yum.CheckNow
"""
Daemon to periodically check for updates to installed packages, and
associated classes and methods.
"""
import os
import sys
import time
import gzip
import dbus
import dbus.service
import dbus.glib
import gobject
import smtplib
import threading
from optparse import OptionParser
from email.mime.text import MIMEText
import yum
import yum.Errors
import syslog
from yum.config import BaseConfig, Option, IntOption, ListOption, BoolOption
from yum.parser import ConfigPreProcessor
from ConfigParser import ConfigParser, ParsingError
from yum.constants import *
from yum.update_md import UpdateMetadata
# FIXME: is it really sane to use this from here?
sys.path.append('/usr/share/yum-cli')
import callback
config_file = '/etc/yum/yum-updatesd.conf'
initial_directory = os.getcwd()
class UpdateEmitter(object):
"""Abstract class for implementing different types of
emitters.
"""
def __init__(self):
pass
def updatesAvailable(self, updateInfo):
"""Emitted when there are updates available to be installed.
If not doing the download here, then called immediately on finding
new updates. If we do the download here, then called after the
updates have been downloaded.
:param updateInfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
pass
def updatesDownloading(self, updateInfo):
"""Emitted to give feedback of update download starting.
:param updateInfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
pass
def updatesApplied(self, updateInfo):
"""Emitted on successful installation of updates.
:param updateInfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
pass
def updatesFailed(self, errmsgs):
"""Emitted when an update has failed to install.
:param errmsgs: a list of error messages
"""
pass
def checkFailed(self, error):
"""Emitted when checking for updates failed.
:param error: an error message
"""
pass
def setupFailed(self, error, translation_domain):
"""Emitted when plugin initialization failed.
:param error: an error message
:param translation_domain: the translation domain supplied by
the plugin
"""
pass
class SyslogUpdateEmitter(UpdateEmitter):
"""Emitter class to send messages to syslog."""
def __init__(self, syslog_facility, ident = "yum-updatesd",
level = "WARN"):
UpdateEmitter.__init__(self)
syslog.openlog(ident, 0, self._facilityMap(syslog_facility))
self.level = level
def updatesAvailable(self, updateInfo):
"""Emit a message stating that updates are available.
:param updateInfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
num = len(updateInfo)
level = self.level
if num > 1:
msg = "%d updates available" %(num,)
elif num == 1:
msg = "1 update available"
else:
msg = "No updates available"
level = syslog.LOG_DEBUG
syslog.syslog(self._levelMap(level), msg)
def _levelMap(self, lvl):
level_map = { "EMERG": syslog.LOG_EMERG,
"ALERT": syslog.LOG_ALERT,
"CRIT": syslog.LOG_CRIT,
"ERR": syslog.LOG_ERR,
"WARN": syslog.LOG_WARNING,
"NOTICE": syslog.LOG_NOTICE,
"INFO": syslog.LOG_INFO,
"DEBUG": syslog.LOG_DEBUG }
if type(lvl) == int:
return lvl
return level_map.get(lvl.upper(), syslog.LOG_INFO)
def _facilityMap(self, facility):
facility_map = { "KERN": syslog.LOG_KERN,
"USER": syslog.LOG_USER,
"MAIL": syslog.LOG_MAIL,
"DAEMON": syslog.LOG_DAEMON,
"AUTH": syslog.LOG_AUTH,
"LPR": syslog.LOG_LPR,
"NEWS": syslog.LOG_NEWS,
"UUCP": syslog.LOG_UUCP,
"CRON": syslog.LOG_CRON,
"LOCAL0": syslog.LOG_LOCAL0,
"LOCAL1": syslog.LOG_LOCAL1,
"LOCAL2": syslog.LOG_LOCAL2,
"LOCAL3": syslog.LOG_LOCAL3,
"LOCAL4": syslog.LOG_LOCAL4,
"LOCAL5": syslog.LOG_LOCAL5,
"LOCAL6": syslog.LOG_LOCAL6,
"LOCAL7": syslog.LOG_LOCAL7,}
if type(facility) == int:
return facility
return facility_map.get(facility.upper(), syslog.LOG_DAEMON)
class EmailUpdateEmitter(UpdateEmitter):
"""Emitter class to send messages via email."""
def __init__(self, sender, rcpt):
UpdateEmitter.__init__(self)
self.sender = sender
self.rcpt = rcpt
def updatesAvailable(self, updateInfo):
"""Emit a message stating that updates are available.
:param updateInfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
num = len(updateInfo)
if num < 1:
return
output = """
Hi,
There are %d package updates available. Please run the system
updater.
Thank You,
Your Computer
""" % num
msg = MIMEText(output)
msg['Subject'] = "%d Updates Available" %(num,)
msg['From'] = self.sender
msg['To'] = ",".join(self.rcpt)
s = smtplib.SMTP()
s.connect()
s.sendmail(self.sender, self.rcpt, msg.as_string())
s.close()
class DbusUpdateEmitter(UpdateEmitter):
"""Emitter class to send messages to the dbus message system."""
def __init__(self):
UpdateEmitter.__init__(self)
bus = dbus.SystemBus()
name = dbus.service.BusName('edu.duke.linux.yum', bus = bus)
yum_dbus = YumDbusInterface(name)
self.dbusintf = yum_dbus
def updatesAvailable(self, updateInfo):
"""Emit a message stating that updates are available.
:param updateInfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
num = len(updateInfo)
msg = "%d" %(num,)
if num > 0:
self.dbusintf.UpdatesAvailableSignal(msg)
else:
self.dbusintf.NoUpdatesAvailableSignal(msg)
def updatesFailed(self, errmsgs):
"""Emit a message stating that an update has failed to install.
:param errmsgs: a list of error messages
"""
self.dbusintf.UpdatesFailedSignal(errmsgs)
def updatesApplied(self, updinfo):
"""Emit a message stating that updates were installed
successfully.
:param updinfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
self.dbusintf.UpdatesAppliedSignal(updinfo)
def checkFailed(self, error):
"""Emit a message stating that checking for updates failed.
:param error: an error message
"""
self.dbusintf.CheckFailedSignal(error)
def setupFailed(self, error, translation_domain):
"""Emit a message stating that plugin initialization failed.
:param error: an error message
:param translation_domain: the translation domain supplied by
the plugin
"""
self.dbusintf.SetupFailedSignal(error, translation_domain)
class YumDbusInterface(dbus.service.Object):
"""Interface class for sending signals to the dbus."""
def __init__(self, bus_name, object_path='/UpdatesAvail'):
dbus.service.Object.__init__(self, bus_name, object_path)
@dbus.service.signal('edu.duke.linux.yum')
def UpdatesAvailableSignal(self, message):
"""Send a signal stating that updates are available.
:param message: the message to send in the signal
"""
pass
@dbus.service.signal('edu.duke.linux.yum')
def NoUpdatesAvailableSignal(self, message):
"""Send a signal stating that no updates are available.
:param message: the message to send in the signal
"""
pass
@dbus.service.signal('edu.duke.linux.yum')
def UpdatesFailedSignal(self, errmsgs):
"""Send a signal stating that the update has failed.
:param errmsgs: a list of error messages
"""
pass
@dbus.service.signal('edu.duke.linux.yum')
def UpdatesAppliedSignal(self, updinfo):
"""Send a signal stating that updates were applied
successfully.
:param updinfo: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
pass
@dbus.service.signal('edu.duke.linux.yum')
def CheckFailedSignal(self, message):
"""Send a signal stating that checking for updates failed.
:param message: the message to send in the signal
"""
pass
@dbus.service.signal('edu.duke.linux.yum')
def SetupFailedSignal(self, message, translation_domain=""):
"""Send a signal stating that plugin initialization failed.
:param message: the message to send in the signal
:param translation_domain: the translation domain supplied by
the plugin
"""
pass
class UDConfig(BaseConfig):
"""Config format for the daemon"""
run_interval = IntOption(3600)
nonroot_workdir = Option("/var/tmp/yum-updatesd")
emit_via = ListOption(['dbus', 'email', 'syslog'])
email_to = ListOption(["root"])
email_from = Option("root")
dbus_listener = BoolOption(True)
do_update = BoolOption(False)
do_download = BoolOption(False)
do_download_deps = BoolOption(False)
updaterefresh = IntOption(3600)
syslog_facility = Option("DAEMON")
syslog_level = Option("WARN")
syslog_ident = Option("yum-updatesd")
yum_config = Option("/etc/yum/yum.conf")
class UpdateBuildTransactionThread(threading.Thread):
"""Class to build the update transaction in a new thread."""
def __init__(self, updd, name):
self.updd = updd
threading.Thread.__init__(self, name=name)
def run(self):
"""Build the transaction, and download the packages to be
updated. Finally, call self.processPkgs. This method must be
provided by a subclass, and will determine what, if any,
action is taken with the packages after they are downloaded.
"""
self.updd.tsInfo.makelists()
try:
(result, msgs) = self.updd.buildTransaction()
except yum.Errors.RepoError, errmsg: # error downloading hdrs
msgs = ["Error downloading headers"]
self.updd.emitUpdateFailed(msgs)
return
dlpkgs = map(lambda x: x.po, filter(lambda txmbr:
txmbr.ts_state in ("i", "u"),
self.updd.tsInfo.getMembers()))
self.updd.downloadPkgs(dlpkgs)
self.processPkgs(dlpkgs)
class UpdateDownloadThread(UpdateBuildTransactionThread):
"""Class to download the packages in the update in a new thread."""
def __init__(self, updd):
UpdateBuildTransactionThread.__init__(self, updd,
name="UpdateDownloadThread")
def processPkgs(self, dlpkgs):
"""Output that there are updates available via the emitters,
and release the yum locks.
:param dlpkgs: unused
"""
self.updd.emitAvailable()
self.updd.releaseLocks()
class UpdateInstallThread(UpdateBuildTransactionThread):
"""Class to install updates in a new thread."""
def __init__(self, updd):
UpdateBuildTransactionThread.__init__(self, updd,
name="UpdateInstallThread")
def failed(self, msgs):
"""Output that the update failed via the emitters.
:param msgs: a list or error messages to emit
"""
self.updd.emitUpdateFailed(msgs)
self.updd.releaseLocks()
def success(self):
"""Output that the update has completed successfully via the
emitters, and perform clean up.
"""
self.updd.emitUpdateApplied()
self.updd.releaseLocks()
self.updd.updateInfo = None
self.updd.updateInfoTime = None
def processPkgs(self, dlpkgs):
"""Apply the available updates.
:param dlpkgs: a list of package objecs to update
"""
for po in dlpkgs:
result, err = self.updd.sigCheckPkg(po)
if result == 0:
continue
elif result == 1:
try:
self.updd.getKeyForPackage(po)
except yum.Errors.YumBaseError, errmsg:
self.failed([str(errmsg)])
del self.updd.ts
self.updd.initActionTs() # make a new, blank ts to populate
self.updd.populateTs(keepold=0)
self.updd.ts.check() #required for ordering
self.updd.ts.order() # order
cb = callback.RPMInstallCallback(output = 0)
cb.filelog = True
cb.tsInfo = self.updd.tsInfo
try:
self.updd.runTransaction(cb=cb)
except yum.Errors.YumBaseError, err:
self.failed([str(err)])
self.success()
class UpdatesDaemon(yum.YumBase):
"""Class to implement the update checking daemon."""
def __init__(self, opts):
yum.YumBase.__init__(self)
self.opts = opts
self.didSetup = False
self.emitters = []
if 'dbus' in self.opts.emit_via:
self.emitters.append(DbusUpdateEmitter())
if 'email' in self.opts.emit_via:
self.emitters.append(EmailUpdateEmitter(self.opts.email_from,
self.opts.email_to))
if 'syslog' in self.opts.emit_via:
self.emitters.append(SyslogUpdateEmitter(self.opts.syslog_facility,
self.opts.syslog_ident,
self.opts.syslog_level))
self.updateInfo = []
self.updateInfoTime = None
def doSetup(self):
"""Perform set up, including setting up directories and
parsing options.
"""
# if we are not root do the special subdir thing
if os.geteuid() != 0:
if not os.path.exists(self.opts.nonroot_workdir):
os.makedirs(self.opts.nonroot_workdir)
self.repos.setCacheDir(self.opts.nonroot_workdir)
self.doConfigSetup(fn=self.opts.yum_config)
def refreshUpdates(self):
"""Retrieve information about what updates are available."""
self.doLock()
try:
self.doRepoSetup()
self.doSackSetup()
self.updateCheckSetup()
except Exception, e:
syslog.syslog(syslog.LOG_WARNING,
"error getting update info: %s" %(e,))
self.emitCheckFailed("%s" %(e,))
self.doUnlock()
return False
return True
def populateUpdateMetadata(self):
"""Populate the metadata for the packages in the update."""
self.updateMetadata = UpdateMetadata()
repos = []
for (new, old) in self.up.getUpdatesTuples():
pkg = self.getPackageObject(new)
if pkg.repoid not in repos:
repo = self.repos.getRepo(pkg.repoid)
repos.append(repo.id)
try: # grab the updateinfo.xml.gz from the repodata
md = repo.retrieveMD('updateinfo')
except Exception: # can't find any; silently move on
continue
md = gzip.open(md)
self.updateMetadata.add(md)
md.close()
def populateUpdates(self):
"""Retrieve and set up information about the updates available
for installed packages.
"""
def getDbusPackageDict(pkg):
"""Returns a dictionary corresponding to the package object
in the form that we can send over the wire for dbus."""
pkgDict = {
"name": pkg.name,
"version": pkg.version,
"release": pkg.release,
"epoch": pkg.epoch,
"arch": pkg.arch,
"sourcerpm": pkg.sourcerpm,
"summary": pkg.summary or "",
}
# check if any updateinfo is available
md = self.updateMetadata.get_notice((pkg.name, pkg.ver, pkg.rel))
if md:
# right now we only want to know if it is a security update
pkgDict['type'] = md['type']
return pkgDict
if self.up is None:
# we're _only_ called after updates are setup
return
self.populateUpdateMetadata()
self.updateInfo = []
for (new, old) in self.up.getUpdatesTuples():
n = getDbusPackageDict(self.getPackageObject(new))
o = getDbusPackageDict(self.rpmdb.searchPkgTuple(old)[0])
self.updateInfo.append((n, o))
if self.conf.obsoletes:
for (obs, inst) in self.up.getObsoletesTuples():
n = getDbusPackageDict(self.getPackageObject(obs))
o = getDbusPackageDict(self.rpmdb.searchPkgTuple(inst)[0])
self.updateInfo.append((n, o))
self.updateInfoTime = time.time()
def populateTsInfo(self):
"""Set up information about the update in the tsInfo object."""
# figure out the updates
for (new, old) in self.up.getUpdatesTuples():
updating = self.getPackageObject(new)
updated = self.rpmdb.searchPkgTuple(old)[0]
self.tsInfo.addUpdate(updating, updated)
# and the obsoletes
if self.conf.obsoletes:
for (obs, inst) in self.up.getObsoletesTuples():
obsoleting = self.getPackageObject(obs)
installed = self.rpmdb.searchPkgTuple(inst)[0]
self.tsInfo.addObsoleting(obsoleting, installed)
self.tsInfo.addObsoleted(installed, obsoleting)
def updatesCheck(self):
"""Check to see whether updates are available for any
installed packages. If updates are available, install them,
download them, or just emit a message, depending on what
options are selected in the configuration file.
:return: whether the daemon should continue looping
"""
if not self.didSetup:
try:
self.doSetup()
except Exception, e:
syslog.syslog(syslog.LOG_WARNING,
"error initializing: %s" % e)
if isinstance(e, yum.plugins.PluginYumExit):
self.emitSetupFailed(e.value, e.translation_domain)
else:
# if we don't know where the string is from, then assume
# it's not marked for translation (versus sending
# gettext.textdomain() and assuming it's from the default
# domain for this app)
self.emitSetupFailed(str(e))
# Setup failed, let's restart and try again after the update
# interval
restart()
else:
self.didSetup = True
try:
if not self.refreshUpdates():
return
except yum.Errors.LockError:
return True # just pass for now
try:
self.populateTsInfo()
self.populateUpdates()
if self.opts.do_update:
uit = UpdateInstallThread(self)
uit.start()
elif self.opts.do_download:
self.emitDownloading()
dl = UpdateDownloadThread(self)
dl.start()
else:
# just notify about things being available
self.emitAvailable()
self.releaseLocks()
except Exception, e:
self.emitCheckFailed("%s" %(e,))
self.doUnlock()
return True
def getUpdateInfo(self):
"""Return information about the update. This may be
previously cached information if the configured time interval
between update retrievals has not yet elapsed, or there is an
error in trying to retrieve the update information.
:return: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
# if we have a cached copy, use it
if self.updateInfoTime and (time.time() - self.updateInfoTime <
self.opts.updaterefresh):
return self.updateInfo
# try to get the lock so we can update the info. fall back to
# cached if available or try a few times.
for i in range(10):
try:
self.doLock()
break
except yum.Errors.LockError:
# if we can't get the lock, return what we have if we can
if self.updateInfo:
return self.updateInfo
time.sleep(1)
else:
return []
try:
self.updateCheckSetup()
self.populateUpdates()
self.releaseLocks()
except:
self.doUnlock()
return self.updateInfo
def updateCheckSetup(self):
"""Set up the transaction set, rpm database, and prepare to
get updates.
"""
self.doTsSetup()
self.doRpmDBSetup()
self.doUpdateSetup()
def releaseLocks(self):
"""Close the rpm database, and release the yum lock."""
self.closeRpmDB()
self.doUnlock()
def emitAvailable(self):
"""Emit a notice stating whether updates are available."""
map(lambda x: x.updatesAvailable(self.updateInfo), self.emitters)
def emitDownloading(self):
"""Emit a notice stating that updates are downloading."""
map(lambda x: x.updatesDownloading(self.updateInfo), self.emitters)
def emitUpdateApplied(self):
"""Emit a notice stating that automatic updates have been applied."""
map(lambda x: x.updatesApplied(self.updateInfo), self.emitters)
def emitUpdateFailed(self, errmsgs):
"""Emit a notice stating that automatic updates failed."""
map(lambda x: x.updatesFailed(errmsgs), self.emitters)
def emitCheckFailed(self, error):
"""Emit a notice stating that checking for updates failed."""
map(lambda x: x.checkFailed(error), self.emitters)
def emitSetupFailed(self, error, translation_domain=""):
"""Emit a notice stating that checking for updates failed."""
map(lambda x: x.setupFailed(error, translation_domain), self.emitters)
class YumDbusListener(dbus.service.Object):
"""Class to export methods that control the daemon over the
dbus.
"""
def __init__(self, updd, bus_name, object_path='/Updatesd',
allowshutdown = False):
dbus.service.Object.__init__(self, bus_name, object_path)
self.updd = updd
self.allowshutdown = allowshutdown
def doCheck(self):
"""Check whether updates are available.
:return: False
"""
self.updd.updatesCheck()
return False
@dbus.service.method("edu.duke.linux.yum", in_signature="")
def CheckNow(self):
"""Check whether updates are available.
:return: a message stating that a check has been queued
"""
# make updating checking asynchronous since we discover whether
# or not there are updates via a callback signal anyway
gobject.idle_add(self.doCheck)
return "check queued"
@dbus.service.method("edu.duke.linux.yum", in_signature="")
def ShutDown(self):
"""Shut down the daemon.
:return: whether remote callers have permission to shut down
the daemon
"""
if not self.allowshutdown:
return False
# we have to do this in a callback so that it doesn't get
# sent back to the caller
gobject.idle_add(shutDown)
return True
@dbus.service.method("edu.duke.linux.yum", in_signature="", out_signature="a(a{ss}a{ss})")
def GetUpdateInfo(self):
"""Return information about the available updates
:return: a list of tuples of dictionaries. Each
dictionary contains information about a package, and each
tuple specifies an available upgrade: the second dictionary
in the tuple has information about a package that is
currently installed, and the first dictionary has
information what the package can be upgraded to
"""
# FIXME: should this be async?
upds = self.updd.getUpdateInfo()
return upds
def shutDown():
"""Shut down the daemon."""
sys.exit(0)
def restart():
"""Restart the daemon, reloading configuration files."""
os.chdir(initial_directory)
os.execve(sys.argv[0], sys.argv, os.environ)
def main(options = None):
"""Configure and start the daemon."""
# we'll be threading for downloads/updates
gobject.threads_init()
dbus.glib.threads_init()
if options is None:
parser = OptionParser()
parser.add_option("-f", "--no-fork", action="store_true", default=False, dest="nofork")
parser.add_option("-r", "--remote-shutdown", action="store_true", default=False, dest="remoteshutdown")
(options, args) = parser.parse_args()
if not options.nofork:
if os.fork():
sys.exit()
fd = os.open("/dev/null", os.O_RDWR)
os.dup2(fd, 0)
os.dup2(fd, 1)
os.dup2(fd, 2)
os.close(fd)
confparser = ConfigParser()
opts = UDConfig()
if os.path.exists(config_file):
confpp_obj = ConfigPreProcessor(config_file)
try:
confparser.readfp(confpp_obj)
except ParsingError, e:
print >> sys.stderr, "Error reading config file: %s" % e
sys.exit(1)
syslog.openlog("yum-updatesd", 0, syslog.LOG_DAEMON)
opts.populate(confparser, 'main')
updd = UpdatesDaemon(opts)
if opts.dbus_listener:
bus = dbus.SystemBus()
name = dbus.service.BusName("edu.duke.linux.yum", bus=bus)
YumDbusListener(updd, name, allowshutdown = options.remoteshutdown)
run_interval_ms = opts.run_interval * 1000 # needs to be in ms
gobject.timeout_add(run_interval_ms, updd.updatesCheck)
mainloop = gobject.MainLoop()
mainloop.run()
if __name__ == "__main__":
main()