3 from __future__ import print_function
9 from random import Random
10 from types import StringTypes
12 from time import strftime
13 TIMEFORMAT="%Y-%m-%d %H:%M:%S"
15 NODEUPDATE_PID_FILE= "/var/run/NodeUpdate.pid"
17 # variables for cron file creation
18 TARGET_SCRIPT = '(echo && date && echo && /usr/bin/NodeUpdate.py start) >>/var/log/NodeUpdate.log 2>&1'
19 TARGET_DESC = 'Update node RPMs periodically'
21 TARGET_SHELL = '/bin/bash'
22 CRON_FILE = '/etc/cron.d/NodeUpdate.cron'
24 YUM_PATH = "/usr/bin/yum"
25 DNF_PATH = "/usr/bin/dnf"
26 HAS_DNF = os.path.exists(DNF_PATH)
30 RPM_GPG_PATH = "/etc/pki/rpm-gpg"
32 # location of file containing http/https proxy info, if needed
33 PROXY_FILE = '/etc/planetlab/http_proxy'
35 # this is the flag that indicates an update needs to restart
36 # the system to take effect. it is created by the rpm that requested
38 REBOOT_FLAG = '/etc/planetlab/update-reboot'
40 # location of directory containing boot server ssl certs
41 SSL_CERT_DIR='/mnt/cdrom/bootme/cacert/'
43 # file containing the list of extensions this node has, each
44 # correspond to a package group in yum repository.
45 # this is expected to be updated from the 'extensions tag'
46 # through the 'extensions.php' nodeconfig script
47 EXTENSIONS_FILE='/etc/planetlab/extensions'
49 # file containing a list of rpms that we should attempt to delete
50 # before updating everything else. This list is not removed with
51 # 'yum remove', because that could accidently remove dependency rpms
52 # that were not intended to be deleted.
53 DELETE_RPM_LIST_FILE= '/etc/planetlab/delete-rpm-list'
55 # ok, so the logic should be simple, just yum update the world
56 # however there are many cases in the real life where this
57 # just does not work, because of a glitch somewhere
58 # so, we force the update of crucial pkgs independently, as
59 # the whole group is sometimes too much to swallow
61 CRUCIAL_PACKAGES_BUILTIN=[
67 # and operations can also try to push a list through a conf_file
68 # should use the second one for consistency, try the first one as well for legacy
69 CRUCIAL_PACKAGES_OPTIONAL_PATHS = [
70 # this is a legacy name, please avoid using this one
71 '/etc/planetlab/NodeUpdate.packages',
72 # file to use with a hand-written conf_file
73 '/etc/planetlab/crucial-rpm-list',
74 # this one could some day be maintained by a predefined config_file
75 '/etc/planetlab/sliceimage-rpm-list',
78 # print out a message only if we are displaying output
79 def Message(*messages):
81 print(5*'*', strftime(TIMEFORMAT), *messages)
85 print(10*'!', strftime(TIMEFORMAT),*messages)
89 command = DNF_PATH if HAS_DNF else YUM_PATH
90 self.command = command
94 Message("Checking if {} supports --verbose".format(command))
95 if os.system("{} --help | grep -q verbose".format(command)) == 0:
96 Message("It does, using --verbose option")
97 options += " --verbose"
99 Message("Unsupported, not using --verbose option")
100 # --sslcertdir option
101 Message("Checking if {} supports SSL certificate checks"
103 if os.system("{} --help | grep -q sslcertdir".format(command)) == 0:
104 Message("It does, using --sslcertdir option")
105 sslcertdir = "--sslcertdir=" + SSL_CERT_DIR
107 Message("Unsupported, not using --sslcertdir option")
109 self.options = options
111 ########## one individual package
112 def handle_package(self, package):
113 if not self.is_packaged_installed(package):
114 return self.do_package(package, "install")
116 return self.do_package(package, "update")
118 def is_packaged_installed(self, package):
119 cmd = "rpm -q {} > /dev/null".format(package)
120 return os.system(cmd) == 0
122 def do_package(self, package, subcommand):
124 "{} {} -y {} {}".format(self.command, self.options,
126 Message("Invoking {}".format(cmd))
127 return os.system(cmd) == 0
129 ########## update one group
130 def update_group(self, group):
131 # it is important to invoke dnf group *upgrade* and not *update*
132 # because the semantics of groups has changed within dnf
135 cmd = "{} {} -y group install {}".format(self.command, self.options, group)
136 Message("Invoking {}".format(cmd))
137 if os.system(cmd) != 0: overall = False
138 cmd = "{} {} -y group upgrade {}".format(self.command, self.options, group)
139 Message("Invoking {}".format(cmd))
140 if os.system(cmd) != 0: overall = False
142 cmd = "{} {} -y groupinstall {}".format(self.command, self.options, group)
143 Message("Invoking {}".format(cmd))
144 if os.system(cmd) != 0: overall = False
147 ########## update the whole system
148 def update_system(self):
149 cmd = "{} {} -y update".format(self.command, self.options)
150 Message("Invoking {}".format(cmd))
151 return os.system(cmd) == 0
154 cmd = "{} clean all".format(self.command)
155 Message("Invoking {}".format(cmd))
156 return os.system(cmd) == 0
158 # create an entry in /etc/cron.d so we run periodically.
159 # we will be run once a day at a 0-59 minute random offset
160 # into a 0-23 random hour
161 def UpdateCronFile():
164 randomMinute= Random().randrange(0, 59, 1);
165 randomHour= Random().randrange(0, 11, 1);
167 f = open(CRON_FILE, 'w');
168 f.write("# {}\n".format(TARGET_DESC));
169 ### xxx is root aliased to the support mailing list ?
170 f.write("MAILTO={}\n".format(TARGET_USER));
171 f.write("SHELL={}\n".format(TARGET_SHELL));
172 f.write("{} {},{} * * * {} {}\n\n"
173 .format (randomMinute, randomHour,
174 randomHour + 12, TARGET_USER, TARGET_SCRIPT));
177 print("Created new cron.d entry.")
179 print("Unable to create cron.d entry.")
182 # simply remove the cron file we created
183 def RemoveCronFile():
186 print("Deleted cron.d entry.")
188 print("Unable to delete cron.d entry.")
194 def __init__(self, doReboot):
195 if self.CheckProxy():
196 os.environ['http_proxy']= self.HTTP_PROXY
197 os.environ['HTTP_PROXY']= self.HTTP_PROXY
198 self.doReboot= doReboot
200 def CheckProxy(self):
201 Message("Checking existence of proxy config file...")
202 if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
203 self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
204 Message("Using proxy {}".format(self.HTTP_PROXY))
207 Message("Not using any proxy.")
210 def InstallKeys(self):
211 Message("Removing any existing GPG signing keys from the RPM database")
212 os.system("{} --allmatches -e gpg-pubkey".format(RPM_PATH))
213 Message("Installing all GPG signing keys in {}".format(RPM_GPG_PATH))
214 os.system("{} --import {}/*".format(RPM_PATH, RPM_GPG_PATH))
216 def ClearRebootFlag(self):
217 os.system("/bin/rm -rf {}".format(REBOOT_FLAG))
219 def CheckForUpdates(self):
220 Message("Removing any existing reboot flags")
221 self.ClearRebootFlag()
222 if self.doReboot == 0:
223 Message("Ignoring any reboot flags set by RPMs");
227 # this of course is quite suboptimal, but proved to be safer
230 # a configurable list of packages to try and update independently
233 crucial_packages = []
234 for package in CRUCIAL_PACKAGES_BUILTIN:
235 crucial_packages.append(package)
236 for path in CRUCIAL_PACKAGES_OPTIONAL_PATHS:
238 crucial_packages += file(path).read().split()
241 Message("List of crucial packages: {}".format(crucial_packages))
242 for package in crucial_packages:
243 yum_dnf.handle_package(package)
248 Message("Updating PlanetLab group")
249 yum_dnf.update_group("PlanetLab")
251 Message("Updating rest of system")
252 yum_dnf.update_system()
254 Message("Checking for extra groups (extensions) to update")
255 if os.access(EXTENSIONS_FILE, os.R_OK) and \
256 os.path.isfile(EXTENSIONS_FILE):
257 extensions_contents= file(EXTENSIONS_FILE).read()
258 extensions_contents= string.strip(extensions_contents)
259 if extensions_contents == "":
260 Message("No extra groups found in file.")
262 extensions_contents.strip()
263 for extension in extensions_contents.split():
264 group = "extension{}".format(extension)
265 yum_dnf.update_group(group)
267 Message("No extensions file found")
269 if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
270 Message("At least one update requested the system be rebooted")
271 self.ClearRebootFlag()
272 os.system("/sbin/shutdown -r now")
274 def RebuildRPMdb(self):
275 Message("Rebuilding RPM Database.")
277 os.system("rm /var/lib/rpm/__db.*")
278 except Exception as err:
279 print("RebuildRPMdb: exception {}".format(err))
281 os.system("{} --rebuilddb".format(RPM_PATH))
282 except Exception as err:
283 print("RebuildRPMdb: exception {}".format(err))
285 def RemoveRPMS(self):
286 Message("Looking for RPMs to be deleted.")
287 if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
288 os.path.isfile(DELETE_RPM_LIST_FILE):
289 rpm_list_contents= file(DELETE_RPM_LIST_FILE).read().strip()
291 if rpm_list_contents == "":
292 Message("No RPMs listed in file to delete.")
295 rpm_list= string.split(rpm_list_contents)
297 Message("Deleting RPMs from {}: {}".format(DELETE_RPM_LIST_FILE," ".join(rpm_list)))
299 # invoke them separately as otherwise one faulty (e.g. already uninstalled)
300 # would prevent the other ones from uninstalling
303 is_installed = os.system ("{} -q {}".format(RPM_PATH, rpm)) == 0
305 Message ("Ignoring rpm {} marked to delete, already uninstalled".format(rpm))
307 uninstalled = os.system("{} -ev {}".format(RPM_PATH, rpm)) == 0
309 Message ("Successfully removed RPM {}".format(rpm))
312 Error("Unable to delete RPM {}, continuing. rc={}".format(rpm, uninstalled))
315 Message("No RPMs list file found.")
317 ##############################
318 if __name__ == "__main__":
320 # if we are invoked with 'start', display the output.
321 # this is useful for running something silently
322 # under cron and as a service (at startup),
323 # so the cron only outputs errors and doesn't
324 # generate mail when it works correctly
328 # if we hit an rpm that requests a reboot, do it if this is
329 # set to 1. can be turned off by adding noreboot to command line
334 if "start" in sys.argv or "display" in sys.argv:
336 Message ("\nTurning on messages")
338 if "noreboot" in sys.argv:
341 if "updatecron" in sys.argv:
342 # simply update the /etc/cron.d file for us, and exit
346 if "removecron" in sys.argv:
351 # see if we are already running by checking the existance
352 # of a PID file, and if it exists, attempting a test kill
353 # to see if the process really does exist. If both of these
356 if os.access(NODEUPDATE_PID_FILE, os.R_OK):
357 pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
359 if os.system("/bin/kill -0 {} > /dev/null 2>&1".format(pid)) == 0:
360 Message("It appears we are already running, exiting.")
363 # write out our process id
364 pidfile = file(NODEUPDATE_PID_FILE, 'w')
365 pidfile.write("{}\n".format(os.getpid()))
369 nodeupdate = NodeUpdate(doReboot)
371 Error("Unable to initialize.")
373 nodeupdate.RebuildRPMdb()
374 nodeupdate.RemoveRPMS()
375 nodeupdate.InstallKeys()
376 nodeupdate.CheckForUpdates()
377 Message("Update complete.")
379 # remove the PID file
380 os.unlink(NODEUPDATE_PID_FILE)