add yum clean all to the routine of NodeUpdate
[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
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 list of extra groups to attempt to update,
39 # if necessary.
40 EXTRA_GROUPS_FILE= '/etc/planetlab/extra-node-groups'
41
42 # file containing a list of rpms that we should attempt to delete
43 # before updating everything else. This list is not removed with 
44 # 'yum remove', because that could accidently remove dependency rpms
45 # that were not intended to be deleted.
46 DELETE_RPM_LIST_FILE= '/etc/planetlab/delete-rpm-list'
47
48
49 # print out a message only if we are displaying output
50 def Message(message):
51     if displayOutput:
52         if isinstance(message,StringTypes) and len(message) >=2 and message[0]=="\n":
53             print "\n",
54             message=message[1:]
55         print strftime(TIMEFORMAT),
56         print message
57
58 # always print errors
59 def Error(Str):
60     print strftime(TIMEFORMAT),
61     print Str
62
63
64 # create an entry in /etc/cron.d so we run periodically.
65 # we will be run once a day at a 0-59 minute random offset
66 # into a 0-23 random hour
67 def UpdateCronFile():
68     try:
69         
70         randomMinute= Random().randrange( 0, 59, 1 );
71         randomHour= Random().randrange( 0, 11, 1 );
72         
73         f = open( CRON_FILE, 'w' );
74         f.write( "# %s\n" % (TARGET_DESC) );
75         ### xxx is root aliased to the support mailing list ?
76         f.write( "MAILTO=%s\n" % (TARGET_USER) );
77         f.write( "SHELL=%s\n" % (TARGET_SHELL) );
78         f.write( "%s %s,%s * * * %s %s\n\n" %
79                  (randomMinute, randomHour, randomHour + 12, TARGET_USER, TARGET_SCRIPT) );
80         f.close()
81     
82         print( "Created new cron.d entry." )
83     except:
84         print( "Unable to create cron.d entry." )
85
86
87 # simply remove the cron file we created
88 def RemoveCronFile():
89     try:
90         os.unlink( CRON_FILE )
91         print( "Deleted cron.d entry." )
92     except:
93         print( "Unable to delete cron.d entry." )
94         
95
96
97 class NodeUpdate:
98
99     def __init__( self, doReboot ):
100         if self.CheckProxy():
101             os.environ['http_proxy']= self.HTTP_PROXY
102             os.environ['HTTP_PROXY']= self.HTTP_PROXY
103             
104         self.doReboot= doReboot
105
106     
107
108     def CheckProxy( self ):
109         Message( "Checking existence of proxy config file..." )
110         
111         if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
112             self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
113             Message( "Using proxy %s." % self.HTTP_PROXY )
114             return 1
115         else:
116             Message( "Not using any proxy." )
117             return 0
118
119
120     def InstallKeys( self ):
121         Message( "\nRemoving any existing GPG signing keys from the RPM database" )
122         os.system( "%s --allmatches -e gpg-pubkey" % RPM_PATH )
123
124         Message( "\nInstalling all GPG signing keys in %s" % RPM_GPG_PATH )
125         os.system( "%s --import %s/*" % (RPM_PATH, RPM_GPG_PATH) )
126
127
128     def ClearRebootFlag( self ):
129         os.system( "/bin/rm -rf %s" % REBOOT_FLAG )
130
131
132     def CheckForUpdates( self ):
133
134         Message( "\nRemoving any existing reboot flags" )
135         self.ClearRebootFlag()
136
137         if self.doReboot == 0:
138             Message( "\nIgnoring any reboot flags set by RPMs" );
139
140         Message( "\nChecking if yum supports SSL certificate checks" )
141         if os.system( "%s --help | grep -q sslcertdir" % YUM_PATH ) == 0:
142             Message( "It does, using --sslcertdir option" )
143             sslcertdir = "--sslcertdir=" + SSL_CERT_DIR
144         else:
145             Message( "Unsupported, not using --sslcertdir option" )
146             sslcertdir = ""
147                     
148         yum_options=""
149         Message( "\nChecking if yum supports --verbose" )
150         if os.system( "%s --help | grep -q verbose" % YUM_PATH ) == 0:
151             Message( "It does, using --verbose option" )
152             yum_options += " --verbose"
153         else:
154             Message( "Unsupported, not using --verbose option" )
155                     
156         Message( "\nUpdating PlanetLab group" )
157         os.system( "%s %s %s -y groupupdate \"PlanetLab\"" %
158                    (YUM_PATH, yum_options, sslcertdir) )
159
160         Message( "\nUpdating rest of system" )
161         os.system( "%s %s %s -y update" %
162                    (YUM_PATH, yum_options, sslcertdir) )
163
164         Message( "\nChecking for extra groups to update" )
165         if os.access(EXTRA_GROUPS_FILE, os.R_OK) and \
166            os.path.isfile(EXTRA_GROUPS_FILE):
167             extra_groups_contents= file(EXTRA_GROUPS_FILE).read()
168             extra_groups_contents= string.strip(extra_groups_contents)
169             if extra_groups_contents == "":
170                 Message( "No extra groups found in file." )
171             else:
172                 for group in string.split(extra_groups_contents,"\n"):
173                     Message( "\nUpdating %s group" % group )
174                     os.system( "%s %s %s -y groupupdate \"%s\"" %
175                                (YUM_PATH, yum_options, sslcertdir, group) )
176         else:
177             Message( "No extra groups file found" )
178             
179         if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
180             Message( "\nAt least one update requested the system be rebooted" )
181             self.ClearRebootFlag()
182             os.system( "/sbin/shutdown -r now" )
183             # in the case where shutdown would hang, e.g. b/c of an initscript 
184             # leave it 10 minutes and brute-force kill
185             DELAY=10*60
186             time.sleep(DELAY)
187             # bad, but not worse than a PCU-driven powercycle
188             os.system ("sync; sleep 1; sync; reboot")
189
190     def RebuildRPMdb( self ):
191         Message( "\nRebuilding RPM Database." )
192         try: os.system( "rm /var/lib/rpm/__db.*" )
193         except Exception, err: print "RebuildRPMdb: %s" % err
194         try: os.system( "%s --rebuilddb" % RPM_PATH )
195         except Exception, err: print "RebuildRPMdb: %s" % err
196
197     def YumCleanAll ( self ):
198         Message ("\nCleaning all yum cache (yum clean all)")
199         try:
200             os.system( "yum clean all")
201         except:
202             pass
203
204     def RemoveRPMS( self ):
205
206         Message( "\nLooking for RPMs to be deleted." )
207         if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
208            os.path.isfile(DELETE_RPM_LIST_FILE):
209             rpm_list_contents= file(DELETE_RPM_LIST_FILE).read()
210             rpm_list_contents= string.strip(rpm_list_contents)
211
212             if rpm_list_contents == "":
213                 Message( "No RPMs listed in file to delete." )
214                 return
215
216             rpm_list= string.join(string.split(rpm_list_contents))
217             
218             Message( "Deleting these RPMs:" )
219             Message( rpm_list_contents )
220             
221             rc= os.system( "%s -ev %s" % (RPM_PATH, rpm_list) )
222
223             if rc != 0:
224                 Error( "Unable to delete RPMs, continuing. rc=%d" % rc )
225             else:
226                 Message( "RPMs deleted successfully." )
227             
228         else:
229             Message( "No RPMs list file found." )
230
231
232
233 if __name__ == "__main__":
234
235     # if we are invoked with 'start', display the output. 
236     # this is useful for running something silently 
237     # under cron and as a service (at startup), 
238     # so the cron only outputs errors and doesn't
239     # generate mail when it works correctly
240
241     displayOutput= 0
242
243     # if we hit an rpm that requests a reboot, do it if this is
244     # set to 1. can be turned off by adding noreboot to command line
245     # option
246     
247     doReboot= 1
248
249     if "start" in sys.argv or "display" in sys.argv:
250         displayOutput= 1
251         Message ("\nTurning on messages")
252
253     if "noreboot" in sys.argv:
254         doReboot= 0
255
256     if "updatecron" in sys.argv:
257         # simply update the /etc/cron.d file for us, and exit
258         UpdateCronFile()
259         sys.exit(0)
260
261     if "removecron" in sys.argv:
262         RemoveCronFile()
263         sys.exit(0)     
264
265             
266     # see if we are already running by checking the existance
267     # of a PID file, and if it exists, attempting a test kill
268     # to see if the process really does exist. If both of these
269     # tests pass, exit.
270     
271     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
272         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
273         if pid <> "":
274             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
275                 Message( "It appears we are already running, exiting." )
276                 sys.exit(1)
277                     
278     # write out our process id
279     pidfile= file( NODEUPDATE_PID_FILE, 'w' )
280     pidfile.write( "%d\n" % os.getpid() )
281     pidfile.close()
282
283     
284     nodeupdate= NodeUpdate(doReboot)
285     if not nodeupdate:
286         Error( "Unable to initialize." )
287     else:
288         nodeupdate.RebuildRPMdb()
289         nodeupdate.RemoveRPMS()
290         nodeupdate.InstallKeys()
291         nodeupdate.YumCleanAll()
292         nodeupdate.CheckForUpdates()
293         Message( "\nUpdate complete." )
294
295     # remove the PID file
296     os.unlink( NODEUPDATE_PID_FILE )
297