09183fbdda2bb82a3da567818b461d86fd5ef77f
[nodeupdate.git] / NodeUpdate.py
1 #!/usr/bin/python2
2
3 from __future__ import print_function
4
5 import sys
6 import os
7 import os.path
8 import string
9 from random import Random
10 from types import StringTypes
11
12 from time import strftime
13 TIMEFORMAT="%Y-%m-%d %H:%M:%S"
14
15 NODEUPDATE_PID_FILE= "/var/run/NodeUpdate.pid"
16
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'
20 TARGET_USER = 'root'
21 TARGET_SHELL = '/bin/bash'
22 CRON_FILE = '/etc/cron.d/NodeUpdate.cron'
23
24 YUM_PATH = "/usr/bin/yum"
25 DNF_PATH = "/usr/bin/dnf"
26 HAS_DNF = os.path.exists(DNF_PATH)
27
28 RPM_PATH = "/bin/rpm"
29
30 RPM_GPG_PATH = "/etc/pki/rpm-gpg"
31
32 # location of file containing http/https proxy info, if needed
33 PROXY_FILE = '/etc/planetlab/http_proxy'
34
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
37 # the reboot
38 REBOOT_FLAG = '/etc/planetlab/update-reboot'
39
40 # location of directory containing boot server ssl certs
41 SSL_CERT_DIR='/mnt/cdrom/bootme/cacert/'
42
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'
48
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'
54
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 
60 # this one is builtin
61 CRUCIAL_PACKAGES_BUILTIN=[
62     'NodeUpdate',
63     'nodemanager-lib',
64     'nodemanager-lxc',
65     'nodemanager-vs',
66 ]
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',
76 ]
77
78 # print out a message only if we are displaying output
79 def Message(*messages):
80     if displayOutput:
81         print(5*'*', strftime(TIMEFORMAT), *messages)
82
83 # always print errors
84 def Error(*messages):
85     print(10*'!', strftime(TIMEFORMAT),*messages)
86
87 class YumDnf:
88     def __init__(self):
89         command = DNF_PATH if HAS_DNF else YUM_PATH
90         self.command = command
91
92         options = ""
93         # --verbose option
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"
98         else:
99             Message("Unsupported, not using --verbose option")
100         # --sslcertdir option
101         Message("Checking if {} supports SSL certificate checks"
102                 .format(command))
103         if os.system("{} --help | grep -q sslcertdir".format(command)) == 0:
104             Message("It does, using --sslcertdir option")
105             sslcertdir = "--sslcertdir=" + SSL_CERT_DIR
106         else:
107             Message("Unsupported, not using --sslcertdir option")
108             sslcertdir = ""
109         self.options = options
110
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")
115         else:
116             return self.do_package(package, "update")
117
118     def is_packaged_installed(self, package):
119         cmd = "rpm -q {} > /dev/null".format(package)
120         return os.system(cmd) == 0
121
122     def do_package(self, package, subcommand):
123         cmd = \
124             "{} {} -y {} {}".format(self.command, self.options,
125                                     subcommand, package)
126         Message("Invoking {}".format(cmd))
127         return os.system(cmd) == 0
128
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
133         if HAS_DNF:
134             cmd = \
135                 "{} {} -y group upgrade {}".format(self.command, self.options, group)
136         else:
137             cmd = \
138                 "{} {} -y groupinstall {}".format(self.command, self.options, group)
139         Message("Invoking {}".format(cmd))
140         return os.system(cmd) == 0
141
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
147
148     def clean_all(self):
149         cmd = "{} clean all".format(self.command)
150         Message("Invoking {}".format(cmd))
151         return os.system(cmd) == 0
152
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():
157     try:
158         
159         randomMinute= Random().randrange(0, 59, 1);
160         randomHour= Random().randrange(0, 11, 1);
161         
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));
170         f.close()
171     
172         print("Created new cron.d entry.")
173     except:
174         print("Unable to create cron.d entry.")
175
176
177 # simply remove the cron file we created
178 def RemoveCronFile():
179     try:
180         os.unlink(CRON_FILE)
181         print("Deleted cron.d entry.")
182     except:
183         print("Unable to delete cron.d entry.")
184         
185
186
187 class NodeUpdate:
188
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
194
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))
200             return 1
201         else:
202             Message("Not using any proxy.")
203             return 0
204
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))
210
211     def ClearRebootFlag(self):
212         os.system("/bin/rm -rf {}".format(REBOOT_FLAG))
213
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");
219                     
220         yum_dnf = YumDnf()
221
222         # this of course is quite suboptimal, but proved to be safer
223         yum_dnf.clean_all()
224
225         # a configurable list of packages to try and update independently
226         # cautious..
227         try:
228             crucial_packages = []
229             for package in CRUCIAL_PACKAGES_BUILTIN:
230                 crucial_packages.append(package)
231             for path in CRUCIAL_PACKAGES_OPTIONAL_PATHS:
232                 try:
233                     crucial_packages += file(path).read().split()
234                 except:
235                     pass
236             Message("List of crucial packages: {}".format(crucial_packages))
237             for package in crucial_packages:
238                 yum_dnf.handle_package(package)
239         except:
240             
241             pass
242
243         Message("Updating PlanetLab group")
244         yum_dnf.update_group("PlanetLab")
245
246         Message("Updating rest of system")
247         yum_dnf.update_system()
248
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.")
256             else:
257                 extensions_contents.strip()
258                 for extension in extensions_contents.split():
259                     group = "extension{}".format(extension)
260                     yum_dnf.update_group(group)
261         else:
262             Message("No extensions file found")
263             
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")
268
269     def RebuildRPMdb(self):
270         Message("Rebuilding RPM Database.")
271         try:
272             os.system("rm /var/lib/rpm/__db.*")
273         except Exception as err:
274             print("RebuildRPMdb: exception {}".format(err))
275         try:
276             os.system("{} --rebuilddb".format(RPM_PATH))
277         except Exception as err:
278             print("RebuildRPMdb: exception {}".format(err))
279
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()
285
286             if rpm_list_contents == "":
287                 Message("No RPMs listed in file to delete.")
288                 return
289
290             rpm_list= string.split(rpm_list_contents)
291             
292             Message("Deleting RPMs from {}: {}".format(DELETE_RPM_LIST_FILE," ".join(rpm_list)))
293
294             # invoke them separately as otherwise one faulty (e.g. already uninstalled)
295             # would prevent the other ones from uninstalling
296             for rpm in rpm_list:
297                 # is it installed
298                 is_installed = os.system ("{} -q {}".format(RPM_PATH, rpm)) == 0
299                 if not is_installed:
300                     Message ("Ignoring rpm {} marked to delete, already uninstalled".format(rpm))
301                     continue
302                 uninstalled = os.system("{} -ev {}".format(RPM_PATH, rpm)) == 0
303                 if uninstalled:
304                     Message ("Successfully removed RPM {}".format(rpm))
305                     continue
306                 else:
307                     Error("Unable to delete RPM {}, continuing. rc={}".format(rpm, uninstalled))
308             
309         else:
310             Message("No RPMs list file found.")
311
312 ##############################
313 if __name__ == "__main__":
314
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
320
321     displayOutput = 0
322
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
325     # option
326     
327     doReboot = 1
328
329     if "start" in sys.argv or "display" in sys.argv:
330         displayOutput = 1
331         Message ("\nTurning on messages")
332
333     if "noreboot" in sys.argv:
334         doReboot = 0
335
336     if "updatecron" in sys.argv:
337         # simply update the /etc/cron.d file for us, and exit
338         UpdateCronFile()
339         sys.exit(0)
340
341     if "removecron" in sys.argv:
342         RemoveCronFile()
343         sys.exit(0)     
344
345             
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
349     # tests pass, exit.
350     
351     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
352         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
353         if pid <> "":
354             if os.system("/bin/kill -0 {} > /dev/null 2>&1".format(pid)) == 0:
355                 Message("It appears we are already running, exiting.")
356                 sys.exit(1)
357                     
358     # write out our process id
359     pidfile = file(NODEUPDATE_PID_FILE, 'w')
360     pidfile.write("{}\n".format(os.getpid()))
361     pidfile.close()
362
363     
364     nodeupdate = NodeUpdate(doReboot)
365     if not nodeupdate:
366         Error("Unable to initialize.")
367     else:
368         nodeupdate.RebuildRPMdb()
369         nodeupdate.RemoveRPMS()
370         nodeupdate.InstallKeys()
371         nodeupdate.CheckForUpdates()
372         Message("Update complete.")
373
374     # remove the PID file
375     os.unlink(NODEUPDATE_PID_FILE)