6696bfb684a3883d2bcbc8ca71e7311b46d08f90
[nodeupdate.git] / NodeUpdate.py
1 #!/usr/bin/python2
2
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
8 # met:
9
10 #     * Redistributions of source code must retain the above copyright
11 #       notice, this list of conditions and the following disclaimer.
12
13 #     * Redistributions in binary form must reproduce the above
14 #       copyright notice, this list of conditions and the following
15 #       disclaimer in the documentation and/or other materials provided
16 #       with the distribution.
17
18 #     * Neither the name of the Intel Corporation nor the names of its
19 #       contributors may be used to endorse or promote products derived
20 #       from this software without specific prior written permission.
21
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
26 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34 # EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF
35 # YOUR JURISDICTION. It is licensee's responsibility to comply with any
36 # export regulations applicable in licensee's jurisdiction. Under
37 # CURRENT (May 2000) U.S. export regulations this software is eligible
38 # for export from the U.S. and can be downloaded by or otherwise
39 # exported or reexported worldwide EXCEPT to U.S. embargoed destinations
40 # which include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan,
41 # Afghanistan and any other country to which the U.S. has embargoed
42 # goods and services.
43
44
45 import sys, os
46 from random import Random
47 import string
48
49 # not needed now
50 #PLANETLAB_BIN = "/usr/local/planetlab/bin/"
51 #sys.path.append(PLANETLAB_BIN)
52 #import BootServerRequest
53
54
55 NODEUPDATE_PID_FILE= "/var/run/NodeUpdate.pid"
56
57 # variables for cron file creation
58 TARGET_SCRIPT = '(echo && date && echo && /usr/bin/NodeUpdate.py start) >>/var/log/NodeUpdate.log 2>&1'
59 TARGET_DESC = 'Update node RPMs periodically'
60 TARGET_USER = 'root'
61 TARGET_SHELL = '/bin/bash'
62 CRON_FILE = '/etc/cron.d/NodeUpdate.cron'
63
64 YUM_PATH = "/usr/bin/yum"
65
66 RPM_PATH = "/bin/rpm"
67
68 RPM_GPG_PATH = "/etc/pki/rpm-gpg"
69
70
71 # location of file containing http/https proxy info, if needed
72 PROXY_FILE = '/etc/planetlab/http_proxy'
73
74 # this is the flag that indicates an update needs to restart
75 # the system to take effect. it is created by the rpm that requested
76 # the reboot
77 REBOOT_FLAG = '/etc/planetlab/update-reboot'
78
79 # location of directory containing boot server ssl certs
80 SSL_CERT_DIR='/mnt/cdrom/bootme/cacert/'
81
82 # file containing list of extra groups to attempt to update,
83 # if necessary.
84 EXTRA_GROUPS_FILE= '/etc/planetlab/extra-node-groups'
85
86 # file containing a list of rpms that we should attempt to delete
87 # before we updating everything else. this list is not
88 # removed with 'yum remove', because that could accidently remove
89 # dependency rpms that were not intended to be deleted.
90 DELETE_RPM_LIST_FILE= '/etc/planetlab/delete-rpm-list'
91
92
93 # print out a message only if we are displaying output
94 def Message(Str):
95     if displayOutput:
96         print Str
97
98
99 # print out a message only if we are displaying output
100 def Error(Str):
101     print Str
102
103
104 # create an entry in /etc/cron.d so we run periodically.
105 # we will be run once a day at a 0-59 minute random offset
106 # into a 0-23 random hour
107 def UpdateCronFile():
108     try:
109         
110         randomMinute= Random().randrange( 0, 59, 1 );
111         randomHour= Random().randrange( 0, 23, 1 );
112         
113         f = open( CRON_FILE, 'w' );
114         f.write( "# %s\n" % (TARGET_DESC) );
115         f.write( "MAILTO=%s\n" % (TARGET_USER) );
116         f.write( "SHELL=%s\n" % (TARGET_SHELL) );
117         f.write( "%s %s * * * %s %s\n\n" %
118                  (randomMinute, randomHour, TARGET_USER, TARGET_SCRIPT) );
119         f.close()
120     
121         print( "Created new cron.d entry." )
122     except:
123         print( "Unable to create cron.d entry." )
124
125
126 # simply remove the cron file we created
127 def RemoveCronFile():
128     try:
129         os.unlink( CRON_FILE )
130         print( "Deleted cron.d entry." )
131     except:
132         print( "Unable to delete cron.d entry." )
133         
134
135
136 class NodeUpdate:
137
138     def __init__( self, doReboot ):
139         if self.CheckProxy():
140             os.environ['http_proxy']= self.HTTP_PROXY
141             os.environ['HTTP_PROXY']= self.HTTP_PROXY
142             
143         self.doReboot= doReboot
144
145     
146
147     def CheckProxy( self ):
148         Message( "Checking existance of proxy config file..." )
149         
150         if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
151             self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
152             Message( "Using proxy %s." % self.HTTP_PROXY )
153             return 1
154         else:
155             Message( "Not using any proxy." )
156             return 0
157
158
159     def InstallKeys( self ):
160         Message( "\nRemoving any existing GPG signing keys from the RPM database" )
161         os.system( "%s --allmatches -e gpg-pubkey" % RPM_PATH )
162
163         Message( "\nInstalling all GPG signing keys in %s" % RPM_GPG_PATH )
164         os.system( "%s --import %s/*" % (RPM_PATH, RPM_GPG_PATH) )
165
166
167     def ClearRebootFlag( self ):
168         os.system( "/bin/rm -rf %s" % REBOOT_FLAG )
169
170
171     def CheckForUpdates( self ):
172
173         Message( "\nRemoving any existing reboot flags" )
174         self.ClearRebootFlag()
175
176         if self.doReboot == 0:
177             Message( "\nIgnoring any reboot flags set by RPMs" );
178
179         Message( "\nChecking if yum supports SSL certificate checks" )
180         if os.system( "%s --help | grep -q sslcertdir" % YUM_PATH ) == 0:
181             Message( "Yes, using --sslcertdir option" )
182             sslcertdir = "--sslcertdir=" + SSL_CERT_DIR
183         else:
184             Message( "No, not using --sslcertdir option" )
185             sslcertdir = ""
186                     
187         Message( "\nUpdating PlanetLab group" )
188         os.system( "%s %s -y groupupdate \"PlanetLab\"" %
189                    (YUM_PATH, sslcertdir) )
190
191         Message( "\nUpdating rest of system" )
192         os.system( "%s %s -y update" %
193                    (YUM_PATH, sslcertdir) )
194
195         Message( "\nChecking for extra groups to update" )
196         if os.access(EXTRA_GROUPS_FILE, os.R_OK) and \
197            os.path.isfile(EXTRA_GROUPS_FILE):
198             extra_groups_contents= file(EXTRA_GROUPS_FILE).read()
199             extra_groups_contents= string.strip(extra_groups_contents)
200             if extra_groups_contents == "":
201                 Message( "No extra groups found in file." )
202             else:
203                 for group in string.split(extra_groups_contents,"\n"):
204                     Message( "\nUpdating %s group" % group )
205                     os.system( "%s %s -y groupupdate \"%s\"" %
206                                (YUM_PATH, sslcertdir, group) )
207         else:
208             Message( "No extra groups file found" )
209             
210         if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
211             Message( "\nAt least one update requested the system be rebooted" )
212             self.ClearRebootFlag()
213             os.system( "/sbin/shutdown -r now" )
214
215             
216     def RemoveRPMS( self ):
217
218         Message( "\nLooking for RPMs to be deleted." )
219         if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
220            os.path.isfile(DELETE_RPM_LIST_FILE):
221             rpm_list_contents= file(DELETE_RPM_LIST_FILE).read()
222             rpm_list_contents= string.strip(rpm_list_contents)
223
224             if rpm_list_contents == "":
225                 Message( "No RPMs listed in file to delete." )
226                 return
227
228             rpm_list= string.join(string.split(rpm_list_contents))
229             
230             Message( "Deleting these RPMs:" )
231             Message( rpm_list_contents )
232             
233             rc= os.system( "%s -ev %s" % (RPM_PATH, rpm_list) )
234
235             if rc != 0:
236                 Error( "Unable to delete RPMs, continuing. rc=%d" % rc )
237             else:
238                 Message( "RPMs deleted successfully." )
239             
240         else:
241             Message( "No RPMs list file found." )
242
243
244
245 if __name__ == "__main__":
246
247     # if we are invoked with 'start', display the output. this
248     # is usefull for running something under cron and as a service
249     # (at startup), so the cron only outputs errors and doesn't
250     # generate mail when it works correctly
251
252     displayOutput= 0
253
254     # if we hit an rpm that requests a reboot, do it if this is
255     # set to 1. can be turned off by adding noreboot to command line
256     # option
257     
258     doReboot= 1
259
260     if "start" in sys.argv:
261         displayOutput= 1
262
263     if "noreboot" in sys.argv:
264         doReboot= 0
265
266     if "updatecron" in sys.argv:
267         # simply update the /etc/cron.d file for us, and exit
268         UpdateCronFile()
269         sys.exit(0)
270
271     if "removecron" in sys.argv:
272         RemoveCronFile()
273         sys.exit(0)     
274
275             
276     # see if we are already running by checking the existance
277     # of a PID file, and if it exists, attempting a test kill
278     # to see if the process really does exist. If both of these
279     # tests pass, exit.
280     
281     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
282         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
283         if pid <> "":
284             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
285                 Message( "It appears we are already running, exiting." )
286                 sys.exit(1)
287                     
288     # write out our process id
289     pidfile= file( NODEUPDATE_PID_FILE, 'w' )
290     pidfile.write( "%d\n" % os.getpid() )
291     pidfile.close()
292
293     
294     nodeupdate= NodeUpdate(doReboot)
295     if not nodeupdate:
296         Error( "Unable to initialize." )
297     else:
298         nodeupdate.RemoveRPMS()
299         nodeupdate.InstallKeys()
300         nodeupdate.CheckForUpdates()
301         Message( "\nUpdate complete." )
302
303     # remove the PID file
304     os.unlink( NODEUPDATE_PID_FILE )
305