-
Notifications
You must be signed in to change notification settings - Fork 77
/
unattended-upgrade-shutdown
executable file
·414 lines (366 loc) · 15.2 KB
/
unattended-upgrade-shutdown
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
#!/usr/bin/python3
# Copyright (c) 2009-2018 Canonical Ltd
#
# AUTHOR:
# Michael Vogt <[email protected]>
# Balint Reczey <[email protected]>
#
# unattended-upgrade-shutdown - helper that checks if a
# unattended-upgrade is in progress and waits until it exits
#
# This file is part of unattended-upgrades
#
# unattended-upgrades 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.
#
# unattended-upgrades 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 unattended-upgrades; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import copy
import dbus
import signal
import sys
import time
import logging
import logging.handlers
import gettext
import subprocess
import os.path
# for dbus signal handling
try:
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
except ImportError:
pass
from optparse import OptionParser, Values
Values # pyflakes
from gettext import gettext as _
from threading import Event
try:
import apt_pkg
except Exception:
# if there is no python-apt no unattended-upgrades can run so not
# need to stop the shutdown
logging.exception("importing of apt_pkg failed, exiting")
sys.exit(0)
def do_usplash(msg):
# type: (str) -> None
if os.path.exists("/sbin/usplash_write"):
logging.debug("Running usplash_write")
subprocess.call(["/sbin/usplash_write", "TEXT", msg])
subprocess.call(["/sbin/usplash_write", "PULSATE"])
def do_plymouth(msg):
# type: (str) -> None
if os.path.exists("/bin/plymouth"):
for line in msg.split("\n"):
logging.debug("Running plymouth --text")
subprocess.call(["/bin/plymouth", "message", "--text", line])
def log_msg(msg, level=logging.WARN):
# type: (str, int) -> None
""" helper that will print msg to usplash, plymouth, console """
logging.log(level, msg)
do_plymouth(msg)
do_usplash(msg)
def log_progress():
# type: () -> None
""" helper to log the install progress (if any) """
# wait a some seconds and try again
msg = _("Unattended-upgrade in progress during shutdown, "
"please don't turn off the computer")
# progress info
progress = "/var/run/unattended-upgrades.progress"
if os.path.exists(progress):
msg += "\n" + open(progress).read()
# log it
log_msg(msg)
def signal_stop_unattended_upgrade():
""" send SIGTERM to running unattended-upgrade if there is any """
pidfile = "/var/run/unattended-upgrades.pid"
if os.path.exists(pidfile):
pid = int(open(pidfile).read())
logging.debug("found running unattended-upgrades pid %s" % pid)
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
logging.debug("sending SIGTERM failed because unattended-upgrades "
"already stopped")
def exit_log_result(success):
if success:
log_msg(_("All upgrades installed"), logging.INFO)
sys.exit(0)
else:
log_msg(_("Unattended-upgrades stopped. There may be upgrades"
" left to be installed in the next run."), logging.INFO)
sys.exit(1)
class UnattendedUpgradesShutdown():
def __init__(self, options):
# type: (Values) -> None
self.options = options
self.max_delay = options.delay * 60
self.iter_timer_set = False
self.apt_pkg_reinit_done = None
self.shutdown_pending = False
self.on_shutdown_mode = None
self.on_shutdown_mode_uu_proc = None
self.start_time = None
self.lock_was_taken = False
self.signal_sent = False
self.stop_signal_received = Event()
try:
hasattr(GLib, "MainLoop")
DBusGMainLoop(set_as_default=True)
except NameError:
pass
try:
self.inhibit_lock = self.get_inhibit_shutdown_lock()
except dbus.exceptions.DBusException:
logging.warning("Could not get delay inhibitor lock")
self.inhibit_lock = None
self.logind_proxy = None
self.wait_period = min(3, self.get_inhibit_max_delay() / 3)
self.preparing_for_shutdown = False
def get_logind_proxy(self):
""" Get logind dbus proxy object """
if not self.logind_proxy:
bus = dbus.SystemBus()
if self.inhibit_lock is None:
# try to get inhibit_lock or throw exception quickly when
# logind is down
self.inhibit_lock = self.get_inhibit_shutdown_lock()
self.logind_proxy = bus.get_object(
'org.freedesktop.login1', '/org/freedesktop/login1')
return self.logind_proxy
def get_inhibit_shutdown_lock(self):
""" Take delay inhibitor lock """
bus = dbus.SystemBus()
return bus.call_blocking(
'org.freedesktop.login1', '/org/freedesktop/login1',
'org.freedesktop.login1.Manager', 'Inhibit', 'ssss',
('shutdown', 'Unattended Upgrades Shutdown',
_('Stop ongoing upgrades or perform upgrades before shutdown'),
'delay'), timeout=2.0)
def get_inhibit_max_delay(self):
try:
logind_proxy = self.get_logind_proxy()
getter_interface = dbus.Interface(
logind_proxy,
dbus_interface='org.freedesktop.DBus.Properties')
return (getter_interface.Get(
"org.freedesktop.login1.Manager", "InhibitDelayMaxUSec")
/ (1000 * 1000))
except dbus.exceptions.DBusException:
return 3
def is_preparing_for_shutdown(self):
if not self.shutdown_pending:
try:
logind_proxy = self.get_logind_proxy()
getter_interface = dbus.Interface(
logind_proxy,
dbus_interface='org.freedesktop.DBus.Properties')
self.shutdown_pending = getter_interface.Get(
"org.freedesktop.login1.Manager", "PreparingForShutdown")
except dbus.exceptions.DBusException:
return False
return self.shutdown_pending
def start_iterations(self):
if not self.iter_timer_set:
try:
GLib.timeout_add(self.wait_period * 1000, self.iter)
# schedule first iteration immediately
GLib.timeout_add(0, lambda: self.iter() and False)
except NameError:
pass
def run_polling(self, signal_handler):
logging.warning(
_("Unable to monitor PrepareForShutdown() signal, polling "
"instead."))
logging.warning(
_("To enable monitoring the PrepareForShutdown() signal "
"instead of polling please install the python3-gi package"))
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGHUP, signal_handler)
# poll for PrepareForShutdown then run final iterations
if self.options.wait_for_signal:
logging.debug("Waiting for signal to start operation ")
while (not self.stop_signal_received.is_set()
and not self.is_preparing_for_shutdown()):
self.stop_signal_received.wait(self.wait_period)
else:
logging.debug("Skip waiting for signals, starting operation "
"now")
while not self.iter():
# TODO iter on sigterm and sighup, too
time.sleep(self.wait_period)
def run(self):
""" delay shutdown and wait for PrepareForShutdown or other signals"""
# set signal handlers
def signal_handler(signum, frame):
# type: (object) -> None
logging.warning(
"SIGTERM or SIGHUP received, stopping unattended-upgrades "
"only if it is running")
self.stop_signal_received.set()
self.start_iterations()
# fall back to polling without GLib
try:
hasattr(GLib, "MainLoop")
except NameError:
self.run_polling(signal_handler)
return
for sig in (signal.SIGTERM, signal.SIGHUP):
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, sig,
signal_handler, None, None)
if self.options.wait_for_signal:
def prepare_for_shutdown_handler(active):
""" Handle PrepareForShutdown() """
if not active:
logging.warning("PrepareForShutdown(false) received, "
"this should not happen")
# PrepareForShutdown arrived, starting final iterations
self.start_iterations()
try:
self.get_logind_proxy().connect_to_signal(
"PrepareForShutdown", prepare_for_shutdown_handler)
except dbus.exceptions.DBusException:
logging.warning(
_("Unable to monitor PrepareForShutdown() signal, polling "
"instead."))
logging.warning(
_("Maybe systemd-logind service is not running."))
self.run_polling(signal_handler)
return
logging.debug("Waiting for signal to start operation ")
else:
# starting final iterations immediately
logging.debug("Skip waiting for signals, starting operation "
"now")
self.start_iterations()
GLib.MainLoop().run()
def try_iter_on_shutdown(self):
# check if we need to run unattended-upgrades on shutdown and if
# so, run it
try:
if self.apt_pkg_reinit_done is None:
logging.debug("Initializing apt_pkg configuration")
apt_pkg.init_config()
self.apt_pkg_reinit_done = True
except apt_pkg.Error as error:
# apt may be in a transient state due to unattended-upgrades
# running, thus assuming non shutdown mode is reasonable
logging.error(_("Apt returned an error thus shutdown mode is "
"disabled"))
logging.error(_("error message: '%s'"), error)
self.apt_pkg_reinit_done = False
if self.on_shutdown_mode is None:
self.on_shutdown_mode = (
not self.options.stop_only
and not self.stop_signal_received.is_set()
and self.apt_pkg_reinit_done
and apt_pkg.config.find_b(
"Unattended-Upgrade::InstallOnShutdown", False))
if self.on_shutdown_mode:
env = copy.copy(os.environ)
env["UNATTENDED_UPGRADES_FORCE_INSTALL_ON_SHUTDOWN"] = "1"
logging.debug("starting unattended-upgrades in shutdown mode")
self.on_shutdown_mode_uu_proc = subprocess.Popen(
["unattended-upgrade"], env=env)
log_msg(_("Running unattended-upgrades in shutdown mode"))
# run u-u, but switch to stopping when receiving stop signal
# because it means shutdown progressed despite holding the lock
if self.on_shutdown_mode:
log_progress()
if self.on_shutdown_mode_uu_proc.poll() is not None:
# unattended-upgrades stopped on its own
exit_log_result(True)
else:
return True
return False
def iter(self):
if self.start_time is None:
self.start_time = time.time()
logging.debug("Starting countdown of %s minutes",
self.max_delay / 60)
else:
if (time.time() - self.start_time) > self.max_delay:
logging.warning(_(
"Giving up on lockfile after %s minutes of delay"),
self.max_delay / 60)
sys.exit(1)
if not self.stop_signal_received.is_set():
if self.try_iter_on_shutdown():
return True
# run monitoring and keep "UI" updated
res = apt_pkg.get_lock(self.options.lock_file)
logging.debug("get_lock returned %i" % res)
# exit here if there is no lock
if res > 0:
logging.debug("lock not taken")
if self.lock_was_taken:
exit_log_result(self.signal_sent)
else:
sys.exit(0)
self.lock_was_taken = True
signal_stop_unattended_upgrade()
self.signal_sent = True
# show log
log_progress()
return True
def main():
# setup gettext
localesApp = "unattended-upgrades"
localesDir = "/usr/share/locale"
gettext.bindtextdomain(localesApp, localesDir)
gettext.textdomain(localesApp)
# use a normal logfile instead of syslog too as on shutdown its too
# easy to get syslog killed
logdir = "/var/log/unattended-upgrades/"
try:
apt_pkg.init_config()
logdir = apt_pkg.config.find_dir(
"Unattended-Upgrade::LogDir", logdir)
except apt_pkg.Error as error:
logging.error(_("Apt returned an error when loading configuration, "
"using default values"))
logging.error(_("error message: '%s'"), error)
parser = OptionParser()
parser.add_option("", "--debug",
action="store_true", dest="debug",
default=apt_pkg.config.find_b(
"Unattended-Upgrade::Debug", False),
help="print debug messages")
parser.add_option("", "--delay", default=25, type="int",
help="delay in minutes to wait for unattended-upgrades")
parser.add_option("", "--lock-file",
default="/var/run/unattended-upgrades.lock",
help="lock file location")
parser.add_option("", "--stop-only",
action="store_true", dest="stop_only", default=False,
help="only stop running unattended-upgrades, don't "
"start it even when "
"Unattended-Upgrade::InstallOnShutdown is true")
parser.add_option("", "--wait-for-signal",
action="store_true", dest="wait_for_signal",
default=False,
help="wait for TERM signal before starting operation")
(options, args) = parser.parse_args()
# setup logging
level = logging.INFO
if options.debug:
level = logging.DEBUG
if not os.path.exists(logdir):
os.makedirs(logdir)
logfile = os.path.join(logdir, "unattended-upgrades-shutdown.log")
logging.basicConfig(filename=logfile,
level=level,
format="%(asctime)s %(levelname)s - %(message)s")
UnattendedUpgradesShutdown(options).run()
if __name__ == "__main__":
main()