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 "{} {} -y group upgrade {}".format(self.command, self.options, group)
138 "{} {} -y groupinstall {}".format(self.command, self.options, group)
139 Message("Invoking {}".format(cmd))
140 return os.system(cmd) == 0
142 ########## update the whole system
143 def update_system(self):
144 cmd = "{} {} -y update".format(self.command, self.options)
145 Message("Invoking {}".format(cmd))
146 return os.system(cmd) == 0
149 cmd = "{} clean all".format(self.command)
150 Message("Invoking {}".format(cmd))
151 return os.system(cmd) == 0
153 # create an entry in /etc/cron.d so we run periodically.
154 # we will be run once a day at a 0-59 minute random offset
155 # into a 0-23 random hour
156 def UpdateCronFile():
159 randomMinute= Random().randrange(0, 59, 1);
160 randomHour= Random().randrange(0, 11, 1);
162 f = open(CRON_FILE, 'w');
163 f.write("# {}\n".format(TARGET_DESC));
164 ### xxx is root aliased to the support mailing list ?
165 f.write("MAILTO={}\n".format(TARGET_USER));
166 f.write("SHELL={}\n".format(TARGET_SHELL));
167 f.write("{} {},{} * * * {} {}\n\n"
168 .format (randomMinute, randomHour,
169 randomHour + 12, TARGET_USER, TARGET_SCRIPT));
172 print("Created new cron.d entry.")
174 print("Unable to create cron.d entry.")
177 # simply remove the cron file we created
178 def RemoveCronFile():
181 print("Deleted cron.d entry.")
183 print("Unable to delete cron.d entry.")
189 def __init__(self, doReboot):
190 if self.CheckProxy():
191 os.environ['http_proxy']= self.HTTP_PROXY
192 os.environ['HTTP_PROXY']= self.HTTP_PROXY
193 self.doReboot= doReboot
195 def CheckProxy(self):
196 Message("Checking existence of proxy config file...")
197 if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
198 self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
199 Message("Using proxy {}".format(self.HTTP_PROXY))
202 Message("Not using any proxy.")
205 def InstallKeys(self):
206 Message("Removing any existing GPG signing keys from the RPM database")
207 os.system("{} --allmatches -e gpg-pubkey".format(RPM_PATH))
208 Message("Installing all GPG signing keys in {}".format(RPM_GPG_PATH))
209 os.system("{} --import {}/*".format(RPM_PATH, RPM_GPG_PATH))
211 def ClearRebootFlag(self):
212 os.system("/bin/rm -rf {}".format(REBOOT_FLAG))
214 def CheckForUpdates(self):
215 Message("Removing any existing reboot flags")
216 self.ClearRebootFlag()
217 if self.doReboot == 0:
218 Message("Ignoring any reboot flags set by RPMs");
222 # this of course is quite suboptimal, but proved to be safer
225 # a configurable list of packages to try and update independently
228 crucial_packages = []
229 for package in CRUCIAL_PACKAGES_BUILTIN:
230 crucial_packages.append(package)
231 for path in CRUCIAL_PACKAGES_OPTIONAL_PATHS:
233 crucial_packages += file(path).read().split()
236 Message("List of crucial packages: {}".format(crucial_packages))
237 for package in crucial_packages:
238 yum_dnf.handle_package(package)
243 Message("Updating PlanetLab group")
244 yum_dnf.update_group("PlanetLab")
246 Message("Updating rest of system")
247 yum_dnf.update_system()
249 Message("Checking for extra groups (extensions) to update")
250 if os.access(EXTENSIONS_FILE, os.R_OK) and \
251 os.path.isfile(EXTENSIONS_FILE):
252 extensions_contents= file(EXTENSIONS_FILE).read()
253 extensions_contents= string.strip(extensions_contents)
254 if extensions_contents == "":
255 Message("No extra groups found in file.")
257 extensions_contents.strip()
258 for extension in extensions_contents.split():
259 group = "extension{}".format(extension)
260 yum_dnf.update_group(group)
262 Message("No extensions file found")
264 if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
265 Message("At least one update requested the system be rebooted")
266 self.ClearRebootFlag()
267 os.system("/sbin/shutdown -r now")
269 def RebuildRPMdb(self):
270 Message("Rebuilding RPM Database.")
272 os.system("rm /var/lib/rpm/__db.*")
273 except Exception as err:
274 print("RebuildRPMdb: exception {}".format(err))
276 os.system("{} --rebuilddb".format(RPM_PATH))
277 except Exception as err:
278 print("RebuildRPMdb: exception {}".format(err))
280 def RemoveRPMS(self):
281 Message("Looking for RPMs to be deleted.")
282 if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
283 os.path.isfile(DELETE_RPM_LIST_FILE):
284 rpm_list_contents= file(DELETE_RPM_LIST_FILE).read().strip()
286 if rpm_list_contents == "":
287 Message("No RPMs listed in file to delete.")
290 rpm_list= string.split(rpm_list_contents)
292 Message("Deleting RPMs from {}: {}".format(DELETE_RPM_LIST_FILE," ".join(rpm_list)))
294 # invoke them separately as otherwise one faulty (e.g. already uninstalled)
295 # would prevent the other ones from uninstalling
298 is_installed = os.system ("{} -q {}".format(RPM_PATH, rpm)) == 0
300 Message ("Ignoring rpm {} marked to delete, already uninstalled".format(rpm))
302 uninstalled = os.system("{} -ev {}".format(RPM_PATH, rpm)) == 0
304 Message ("Successfully removed RPM {}".format(rpm))
307 Error("Unable to delete RPM {}, continuing. rc={}".format(rpm, uninstalled))
310 Message("No RPMs list file found.")
312 ##############################
313 if __name__ == "__main__":
315 # if we are invoked with 'start', display the output.
316 # this is useful for running something silently
317 # under cron and as a service (at startup),
318 # so the cron only outputs errors and doesn't
319 # generate mail when it works correctly
323 # if we hit an rpm that requests a reboot, do it if this is
324 # set to 1. can be turned off by adding noreboot to command line
329 if "start" in sys.argv or "display" in sys.argv:
331 Message ("\nTurning on messages")
333 if "noreboot" in sys.argv:
336 if "updatecron" in sys.argv:
337 # simply update the /etc/cron.d file for us, and exit
341 if "removecron" in sys.argv:
346 # see if we are already running by checking the existance
347 # of a PID file, and if it exists, attempting a test kill
348 # to see if the process really does exist. If both of these
351 if os.access(NODEUPDATE_PID_FILE, os.R_OK):
352 pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
354 if os.system("/bin/kill -0 {} > /dev/null 2>&1".format(pid)) == 0:
355 Message("It appears we are already running, exiting.")
358 # write out our process id
359 pidfile = file(NODEUPDATE_PID_FILE, 'w')
360 pidfile.write("{}\n".format(os.getpid()))
364 nodeupdate = NodeUpdate(doReboot)
366 Error("Unable to initialize.")
368 nodeupdate.RebuildRPMdb()
369 nodeupdate.RemoveRPMS()
370 nodeupdate.InstallKeys()
371 nodeupdate.CheckForUpdates()
372 Message("Update complete.")
374 # remove the PID file
375 os.unlink(NODEUPDATE_PID_FILE)