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