for fedora23 nodes - yet again
[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         overall = True
134         if HAS_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
141         else:
142             cmd = "{} {} -y groupinstall {}".format(self.command, self.options, group)
143             Message("Invoking {}".format(cmd))
144             if os.system(cmd) != 0: overall = False
145         return overall
146
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
152
153     def clean_all(self):
154         cmd = "{} clean all".format(self.command)
155         Message("Invoking {}".format(cmd))
156         return os.system(cmd) == 0
157
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():
162     try:
163         
164         randomMinute= Random().randrange(0, 59, 1);
165         randomHour= Random().randrange(0, 11, 1);
166         
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));
175         f.close()
176     
177         print("Created new cron.d entry.")
178     except:
179         print("Unable to create cron.d entry.")
180
181
182 # simply remove the cron file we created
183 def RemoveCronFile():
184     try:
185         os.unlink(CRON_FILE)
186         print("Deleted cron.d entry.")
187     except:
188         print("Unable to delete cron.d entry.")
189         
190
191
192 class NodeUpdate:
193
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
199
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))
205             return 1
206         else:
207             Message("Not using any proxy.")
208             return 0
209
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))
215
216     def ClearRebootFlag(self):
217         os.system("/bin/rm -rf {}".format(REBOOT_FLAG))
218
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");
224                     
225         yum_dnf = YumDnf()
226
227         # this of course is quite suboptimal, but proved to be safer
228         yum_dnf.clean_all()
229
230         # a configurable list of packages to try and update independently
231         # cautious..
232         try:
233             crucial_packages = []
234             for package in CRUCIAL_PACKAGES_BUILTIN:
235                 crucial_packages.append(package)
236             for path in CRUCIAL_PACKAGES_OPTIONAL_PATHS:
237                 try:
238                     crucial_packages += file(path).read().split()
239                 except:
240                     pass
241             Message("List of crucial packages: {}".format(crucial_packages))
242             for package in crucial_packages:
243                 yum_dnf.handle_package(package)
244         except:
245             
246             pass
247
248         Message("Updating PlanetLab group")
249         yum_dnf.update_group("PlanetLab")
250
251         Message("Updating rest of system")
252         yum_dnf.update_system()
253
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.")
261             else:
262                 extensions_contents.strip()
263                 for extension in extensions_contents.split():
264                     group = "extension{}".format(extension)
265                     yum_dnf.update_group(group)
266         else:
267             Message("No extensions file found")
268             
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")
273
274     def RebuildRPMdb(self):
275         Message("Rebuilding RPM Database.")
276         try:
277             os.system("rm /var/lib/rpm/__db.*")
278         except Exception as err:
279             print("RebuildRPMdb: exception {}".format(err))
280         try:
281             os.system("{} --rebuilddb".format(RPM_PATH))
282         except Exception as err:
283             print("RebuildRPMdb: exception {}".format(err))
284
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()
290
291             if rpm_list_contents == "":
292                 Message("No RPMs listed in file to delete.")
293                 return
294
295             rpm_list= string.split(rpm_list_contents)
296             
297             Message("Deleting RPMs from {}: {}".format(DELETE_RPM_LIST_FILE," ".join(rpm_list)))
298
299             # invoke them separately as otherwise one faulty (e.g. already uninstalled)
300             # would prevent the other ones from uninstalling
301             for rpm in rpm_list:
302                 # is it installed
303                 is_installed = os.system ("{} -q {}".format(RPM_PATH, rpm)) == 0
304                 if not is_installed:
305                     Message ("Ignoring rpm {} marked to delete, already uninstalled".format(rpm))
306                     continue
307                 uninstalled = os.system("{} -ev {}".format(RPM_PATH, rpm)) == 0
308                 if uninstalled:
309                     Message ("Successfully removed RPM {}".format(rpm))
310                     continue
311                 else:
312                     Error("Unable to delete RPM {}, continuing. rc={}".format(rpm, uninstalled))
313             
314         else:
315             Message("No RPMs list file found.")
316
317 ##############################
318 if __name__ == "__main__":
319
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
325
326     displayOutput = 0
327
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
330     # option
331     
332     doReboot = 1
333
334     if "start" in sys.argv or "display" in sys.argv:
335         displayOutput = 1
336         Message ("\nTurning on messages")
337
338     if "noreboot" in sys.argv:
339         doReboot = 0
340
341     if "updatecron" in sys.argv:
342         # simply update the /etc/cron.d file for us, and exit
343         UpdateCronFile()
344         sys.exit(0)
345
346     if "removecron" in sys.argv:
347         RemoveCronFile()
348         sys.exit(0)     
349
350             
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
354     # tests pass, exit.
355     
356     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
357         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
358         if pid <> "":
359             if os.system("/bin/kill -0 {} > /dev/null 2>&1".format(pid)) == 0:
360                 Message("It appears we are already running, exiting.")
361                 sys.exit(1)
362                     
363     # write out our process id
364     pidfile = file(NODEUPDATE_PID_FILE, 'w')
365     pidfile.write("{}\n".format(os.getpid()))
366     pidfile.close()
367
368     
369     nodeupdate = NodeUpdate(doReboot)
370     if not nodeupdate:
371         Error("Unable to initialize.")
372     else:
373         nodeupdate.RebuildRPMdb()
374         nodeupdate.RemoveRPMS()
375         nodeupdate.InstallKeys()
376         nodeupdate.CheckForUpdates()
377         Message("Update complete.")
378
379     # remove the PID file
380     os.unlink(NODEUPDATE_PID_FILE)