bugfix for crucial packages
[nodeupdate.git] / NodeUpdate.py
1 #!/usr/bin/python2
2
3 import sys
4 import os
5 import string
6 from random import Random
7 from types import StringTypes
8
9 from time import strftime
10 TIMEFORMAT="%Y-%m-%d %H:%M:%S"
11
12 NODEUPDATE_PID_FILE= "/var/run/NodeUpdate.pid"
13
14 # variables for cron file creation
15 TARGET_SCRIPT = '(echo && date && echo && /usr/bin/NodeUpdate.py start) >>/var/log/NodeUpdate.log 2>&1'
16 TARGET_DESC = 'Update node RPMs periodically'
17 TARGET_USER = 'root'
18 TARGET_SHELL = '/bin/bash'
19 CRON_FILE = '/etc/cron.d/NodeUpdate.cron'
20
21 YUM_PATH = "/usr/bin/yum"
22
23 RPM_PATH = "/bin/rpm"
24
25 RPM_GPG_PATH = "/etc/pki/rpm-gpg"
26
27 # location of file containing http/https proxy info, if needed
28 PROXY_FILE = '/etc/planetlab/http_proxy'
29
30 # this is the flag that indicates an update needs to restart
31 # the system to take effect. it is created by the rpm that requested
32 # the reboot
33 REBOOT_FLAG = '/etc/planetlab/update-reboot'
34
35 # location of directory containing boot server ssl certs
36 SSL_CERT_DIR='/mnt/cdrom/bootme/cacert/'
37
38 # file containing the list of extensions this node has, each
39 # correspond to a package group in yum repository.
40 # this is expected to be updated from the 'extensions tag' 
41 # through the 'extensions.php' nodeconfig script
42 EXTENSIONS_FILE='/etc/planetlab/extensions'
43
44 # file containing a list of rpms that we should attempt to delete
45 # before updating everything else. This list is not removed with 
46 # 'yum remove', because that could accidently remove dependency rpms
47 # that were not intended to be deleted.
48 DELETE_RPM_LIST_FILE= '/etc/planetlab/delete-rpm-list'
49
50 # ok, so the logic should be simple, just yum update the world
51 # however there are many cases in the real life where this 
52 # just does not work, because of a glitch somewhere
53 # so, we force the update of crucial pkgs independently, as 
54 # the whole group is sometimes too much to swallow 
55 # this one is builtin
56 CRUCIAL_PACKAGES_BUILTIN=[
57     'NodeUpdate',
58     'nodemanager-lib',
59     'nodemanager-lxc',
60     'nodemanager-vs',
61 ]
62 # and operations can also try to push a list through a conf_file
63 # should use the second one for consistency, try the first one as well for legacy
64 CRUCIAL_PACKAGES_OPTIONAL_PATHS = [
65     # this is a legacy name, please avoid using this one
66     '/etc/planetlab/NodeUpdate.packages',
67     # file to use with a hand-written conf_file
68     '/etc/planetlab/crucial-rpm-list',
69     # this one could some day be maintained by a predefined config_file
70     '/etc/planetlab/sliceimage-rpm-list',
71 ]
72
73 # print out a message only if we are displaying output
74 def Message(message):
75     if displayOutput:
76         if isinstance(message,StringTypes) \
77            and len(message) >= 2 \
78            and message[0] == "\n":
79             print "\n",
80             message = message[1:]
81         print strftime(TIMEFORMAT),
82         print message
83
84 # always print errors
85 def Error(Str):
86     print strftime(TIMEFORMAT),
87     print Str
88
89
90 # create an entry in /etc/cron.d so we run periodically.
91 # we will be run once a day at a 0-59 minute random offset
92 # into a 0-23 random hour
93 def UpdateCronFile():
94     try:
95         
96         randomMinute= Random().randrange(0, 59, 1);
97         randomHour= Random().randrange(0, 11, 1);
98         
99         f = open(CRON_FILE, 'w');
100         f.write("# %s\n" % (TARGET_DESC));
101         ### xxx is root aliased to the support mailing list ?
102         f.write("MAILTO=%s\n" % (TARGET_USER));
103         f.write("SHELL=%s\n" % (TARGET_SHELL));
104         f.write("%s %s,%s * * * %s %s\n\n" %
105                  (randomMinute, randomHour,
106                   randomHour + 12, TARGET_USER, TARGET_SCRIPT));
107         f.close()
108     
109         print("Created new cron.d entry.")
110     except:
111         print("Unable to create cron.d entry.")
112
113
114 # simply remove the cron file we created
115 def RemoveCronFile():
116     try:
117         os.unlink(CRON_FILE)
118         print("Deleted cron.d entry.")
119     except:
120         print("Unable to delete cron.d entry.")
121         
122
123
124 class NodeUpdate:
125
126     def __init__(self, doReboot):
127         if self.CheckProxy():
128             os.environ['http_proxy']= self.HTTP_PROXY
129             os.environ['HTTP_PROXY']= self.HTTP_PROXY
130         self.doReboot= doReboot
131
132     def CheckProxy(self):
133         Message("Checking existence of proxy config file...")
134         if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
135             self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
136             Message("Using proxy %s." % self.HTTP_PROXY)
137             return 1
138         else:
139             Message("Not using any proxy.")
140             return 0
141
142     def InstallKeys(self):
143         Message("\nRemoving any existing GPG signing keys from the RPM database")
144         os.system("%s --allmatches -e gpg-pubkey" % RPM_PATH)
145         Message("\nInstalling all GPG signing keys in %s" % RPM_GPG_PATH)
146         os.system("%s --import %s/*" % (RPM_PATH, RPM_GPG_PATH))
147
148     def ClearRebootFlag(self):
149         os.system("/bin/rm -rf %s" % REBOOT_FLAG)
150
151     def CheckForUpdates(self):
152         Message("\nRemoving any existing reboot flags")
153         self.ClearRebootFlag()
154         if self.doReboot == 0:
155             Message("\nIgnoring any reboot flags set by RPMs");
156         Message("\nChecking if yum supports SSL certificate checks")
157         if os.system("%s --help | grep -q sslcertdir" % YUM_PATH) == 0:
158             Message("It does, using --sslcertdir option")
159             sslcertdir = "--sslcertdir=" + SSL_CERT_DIR
160         else:
161             Message("Unsupported, not using --sslcertdir option")
162             sslcertdir = ""
163                     
164         yum_options=""
165         Message("\nChecking if yum supports --verbose")
166         if os.system("%s --help | grep -q verbose" % YUM_PATH) == 0:
167             Message("It does, using --verbose option")
168             yum_options += " --verbose"
169         else:
170             Message("Unsupported, not using --verbose option")
171         
172         # a configurable list of packages to try and update independently
173         # cautious..
174         try:
175             crucial_packages = []
176             for package in CRUCIAL_PACKAGES_BUILTIN:
177                 crucial_packages.append(package)
178             for path in CRUCIAL_PACKAGES_OPTIONAL_PATHS:
179                 try:
180                     crucial_packages += file(path).read().split()
181                 except:
182                     pass
183             for package in crucial_packages:
184                 # if package is not yet installed, like e.g. slice images, 
185                 # need to yum install, not yum update
186                 if os.system("rpm -q %s > /dev/null"%package) == 0:
187                     Message("\nUpdating crucial package %s" % package)
188                     os.system("%s %s -y update %s" %(YUM_PATH, yum_options, package))
189                 else:
190                     Message("\Installing crucial package %s" % package)
191                     os.system("%s %s -y install %s" %(YUM_PATH, yum_options, package))
192         except:
193             pass
194
195         Message("\nUpdating PlanetLab group")
196         os.system("%s %s %s -y groupinstall \"PlanetLab\"" %
197                    (YUM_PATH, yum_options, sslcertdir))
198
199         Message("\nUpdating rest of system")
200         os.system("%s %s %s -y update" % (YUM_PATH, yum_options, sslcertdir))
201
202         Message("\nChecking for extra groups (extensions) to update")
203         if os.access(EXTENSIONS_FILE, os.R_OK) and \
204            os.path.isfile(EXTENSIONS_FILE):
205             extensions_contents= file(EXTENSIONS_FILE).read()
206             extensions_contents= string.strip(extensions_contents)
207             if extensions_contents == "":
208                 Message("No extra groups found in file.")
209             else:
210                 extensions_contents.strip()
211                 for extension in extensions_contents.split():
212                     group = "extension%s" % extension
213                     Message("\nUpdating %s group" % group)
214                     os.system("%s %s %s -y groupinstall \"%s\"" %
215                                (YUM_PATH, yum_options, sslcertdir, group))
216         else:
217             Message("No extensions file found")
218             
219         if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
220             Message("\nAt least one update requested the system be rebooted")
221             self.ClearRebootFlag()
222             os.system("/sbin/shutdown -r now")
223
224     def RebuildRPMdb(self):
225         Message("\nRebuilding RPM Database.")
226         try: os.system("rm /var/lib/rpm/__db.*")
227         except Exception, err: print "RebuildRPMdb: %s" % err
228         try: os.system("%s --rebuilddb" % RPM_PATH)
229         except Exception, err: print "RebuildRPMdb: %s" % err
230
231     def YumCleanAll (self):
232         Message ("\nCleaning all yum cache (yum clean all)")
233         try:
234             os.system("yum clean all")
235         except:
236             pass
237
238     def RemoveRPMS(self):
239         Message("\nLooking for RPMs to be deleted.")
240         if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
241            os.path.isfile(DELETE_RPM_LIST_FILE):
242             rpm_list_contents= file(DELETE_RPM_LIST_FILE).read().strip()
243
244             if rpm_list_contents == "":
245                 Message("No RPMs listed in file to delete.")
246                 return
247
248             rpm_list= string.split(rpm_list_contents)
249             
250             Message("Deleting RPMs from %s: %s" %(DELETE_RPM_LIST_FILE," ".join(rpm_list)))
251
252             # invoke them separately as otherwise one faulty (e.g. already uninstalled)
253             # would prevent the other ones from uninstalling
254             for rpm in rpm_list:
255                 # is it installed
256                 is_installed = os.system ("%s -q %s"%(RPM_PATH,rpm))==0
257                 if not is_installed:
258                     Message ("Ignoring rpm %s marked to delete, already uninstalled"%rpm)
259                     continue
260                 uninstalled = os.system("%s -ev %s" % (RPM_PATH, rpm))==0
261                 if uninstalled:
262                     Message ("Successfully removed RPM %s"%rpm)
263                     continue
264                 else:
265                     Error("Unable to delete RPM %s, continuing. rc=%d" % (rpm,uninstalled))
266             
267         else:
268             Message("No RPMs list file found.")
269
270 ##############################
271 if __name__ == "__main__":
272
273     # if we are invoked with 'start', display the output. 
274     # this is useful for running something silently 
275     # under cron and as a service (at startup), 
276     # so the cron only outputs errors and doesn't
277     # generate mail when it works correctly
278
279     displayOutput= 0
280
281     # if we hit an rpm that requests a reboot, do it if this is
282     # set to 1. can be turned off by adding noreboot to command line
283     # option
284     
285     doReboot= 1
286
287     if "start" in sys.argv or "display" in sys.argv:
288         displayOutput= 1
289         Message ("\nTurning on messages")
290
291     if "noreboot" in sys.argv:
292         doReboot= 0
293
294     if "updatecron" in sys.argv:
295         # simply update the /etc/cron.d file for us, and exit
296         UpdateCronFile()
297         sys.exit(0)
298
299     if "removecron" in sys.argv:
300         RemoveCronFile()
301         sys.exit(0)     
302
303             
304     # see if we are already running by checking the existance
305     # of a PID file, and if it exists, attempting a test kill
306     # to see if the process really does exist. If both of these
307     # tests pass, exit.
308     
309     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
310         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
311         if pid <> "":
312             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
313                 Message("It appears we are already running, exiting.")
314                 sys.exit(1)
315                     
316     # write out our process id
317     pidfile= file(NODEUPDATE_PID_FILE, 'w')
318     pidfile.write("%d\n" % os.getpid())
319     pidfile.close()
320
321     
322     nodeupdate= NodeUpdate(doReboot)
323     if not nodeupdate:
324         Error("Unable to initialize.")
325     else:
326         nodeupdate.RebuildRPMdb()
327         nodeupdate.RemoveRPMS()
328         nodeupdate.InstallKeys()
329         nodeupdate.YumCleanAll()
330         nodeupdate.CheckForUpdates()
331         Message("\nUpdate complete.")
332
333     # remove the PID file
334     os.unlink(NODEUPDATE_PID_FILE)