bump release number
[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 = '/usr/local/planetlab/bin/NodeUpdate.py'
59 TARGET_DESC = 'Update node RPMs periodically'
60 TARGET_USER = 'root'
61 CRON_FILE = '/etc/cron.d/NodeUpdate.cron'
62
63 YUM_PATH = "/usr/bin/yum"
64
65 RPM_PATH = "/bin/rpm"
66
67
68 # location of file containing http/https proxy info, if needed
69 PROXY_FILE = '/etc/planetlab/http_proxy'
70
71 # this is the flag that indicates an update needs to restart
72 # the system to take effect. it is created by the rpm that requested
73 # the reboot
74 REBOOT_FLAG = '/etc/planetlab/update-reboot'
75
76 # location of directory containing boot server ssl certs
77 SSL_CERT_DIR='/mnt/cdrom/bootme/cacert/'
78
79 # file containing list of extra groups to attempt to update,
80 # if necessary.
81 EXTRA_GROUPS_FILE= '/etc/planetlab/extra-node-groups'
82
83 # file containing a list of rpms that we should attempt to delete
84 # before we updating everything else. this list is not
85 # removed with 'yum remove', because that could accidently remove
86 # dependency rpms that were not intended to be deleted.
87 DELETE_RPM_LIST_FILE= '/etc/planetlab/delete-rpm-list'
88
89
90 # print out a message only if we are displaying output
91 def Message(Str):
92     if displayOutput:
93         print Str
94
95
96 # print out a message only if we are displaying output
97 def Error(Str):
98     print Str
99
100
101 # create an entry in /etc/cron.d so we run periodically
102 # we will be run once an hour at a 0-59 random offset
103 def UpdateCronFile():
104     try:
105         randomMinute= Random().randrange( 0, 59, 1 );
106         
107         f = open( CRON_FILE, 'w' );
108         f.write( "# %s\n" % (TARGET_DESC) );
109         f.write( "MAILTO=%s\n" % (TARGET_USER) );
110         f.write( "%s * * * * %s %s\n\n" % (randomMinute, TARGET_USER, TARGET_SCRIPT) );
111         f.close()
112     
113         print( "Created new cron.d entry." )
114     except:
115         print( "Unable to create cron.d entry." )
116
117
118 # simply remove the cron file we created
119 def RemoveCronFile():
120     try:
121         os.unlink( CRON_FILE )
122         print( "Deleted cron.d entry." )
123     except:
124         print( "Unable to delete cron.d entry." )
125         
126
127
128 class NodeUpdate:
129
130     def __init__( self, doReboot ):
131         if self.CheckProxy():
132             os.environ['http_proxy']= self.HTTP_PROXY
133             os.environ['HTTP_PROXY']= self.HTTP_PROXY
134             
135         self.doReboot= doReboot
136
137     
138
139     def CheckProxy( self ):
140         Message( "Checking existance of proxy config file..." )
141         
142         if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
143             self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
144             Message( "Using proxy %s." % self.HTTP_PROXY )
145             return 1
146         else:
147             Message( "Not using any proxy." )
148             return 0
149
150
151     def ClearRebootFlag( self ):
152         os.system( "/bin/rm -rf %s" % REBOOT_FLAG )
153
154
155     def CheckForUpdates( self ):
156
157         Message( "\nRemoving any existing reboot flags" )
158         self.ClearRebootFlag()
159
160         if self.doReboot == 0:
161             Message( "\nIgnoring any reboot flags set by RPMs" );
162                     
163         Message( "\nUpdating PlanetLab group" )
164         os.system( "%s --sslcertdir=%s -y groupupdate \"PlanetLab\"" %
165                    (YUM_PATH,SSL_CERT_DIR) )
166
167         Message( "\nUpdating rest of system" )
168         os.system( "%s --sslcertdir=%s -y update" %
169                    (YUM_PATH,SSL_CERT_DIR) )
170
171         Message( "\nChecking for extra groups to update" )
172         if os.access(EXTRA_GROUPS_FILE, os.R_OK) and \
173            os.path.isfile(EXTRA_GROUPS_FILE):
174             extra_groups_contents= file(EXTRA_GROUPS_FILE).read()
175             extra_groups_contents= string.strip(extra_groups_contents)
176             if extra_groups_contents == "":
177                 Message( "No extra groups found in file." )
178             else:
179                 for group in string.split(extra_groups_contents,"\n"):
180                     Message( "\nUpdating %s group" % group )
181                     os.system( "%s --sslcertdir=%s -y groupupdate \"%s\"" %
182                                (YUM_PATH,SSL_CERT_DIR,group) )
183         else:
184             Message( "No extra groups file found" )
185             
186         if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
187             Message( "\nAt least one update requested the system be rebooted" )
188             self.ClearRebootFlag()
189             os.system( "/sbin/shutdown -r now" )
190
191             
192     def RemoveRPMS( self ):
193
194         Message( "\nLooking for RPMs to be deleted." )
195         if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
196            os.path.isfile(DELETE_RPM_LIST_FILE):
197             rpm_list_contents= file(DELETE_RPM_LIST_FILE).read()
198             rpm_list_contents= string.strip(rpm_list_contents)
199
200             if rpm_list_contents == "":
201                 Message( "No RPMs listed in file to delete." )
202                 return
203
204             rpm_list= string.join(string.split(rpm_list_contents))
205             
206             Message( "Deleting these RPMs:" )
207             Message( rpm_list_contents )
208             
209             rc= os.system( "%s -ev %s" % (RPM_PATH, rpm_list) )
210
211             if rc != 0:
212                 Error( "Unable to delete RPMs, continuing. rc=%d" % rc )
213             else:
214                 Message( "RPMs deleted successfully." )
215             
216         else:
217             Message( "No RPMs list file found." )
218
219
220
221 if __name__ == "__main__":
222
223     # if we are invoked with 'start', display the output. this
224     # is usefull for running something under cron and as a service
225     # (at startup), so the cron only outputs errors and doesn't
226     # generate mail when it works correctly
227
228     displayOutput= 0
229
230     # if we hit an rpm that requests a reboot, do it if this is
231     # set to 1. can be turned off by adding noreboot to command line
232     # option
233     
234     doReboot= 1
235
236     if "start" in sys.argv:
237         displayOutput= 1
238
239     if "noreboot" in sys.argv:
240         doReboot= 0
241
242     if "updatecron" in sys.argv:
243         # simply update the /etc/cron.d file for us, and exit
244         UpdateCronFile()
245         sys.exit(0)
246
247     if "removecron" in sys.argv:
248         RemoveCronFile()
249         sys.exit(0)     
250
251             
252     # see if we are already running by checking the existance
253     # of a PID file, and if it exists, attempting a test kill
254     # to see if the process really does exist. If both of these
255     # tests pass, exit.
256     
257     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
258         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
259         if pid <> "":
260             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
261                 Message( "It appears we are already running, exiting." )
262                 sys.exit(1)
263                     
264     # write out our process id
265     pidfile= file( NODEUPDATE_PID_FILE, 'w' )
266     pidfile.write( "%d\n" % os.getpid() )
267     pidfile.close()
268
269     
270     nodeupdate= NodeUpdate(doReboot)
271     if not nodeupdate:
272         Error( "Unable to initialize." )
273     else:
274         nodeupdate.RemoveRPMS()
275         nodeupdate.CheckForUpdates()
276         Message( "\nUpdate complete." )
277
278     # remove the PID file
279     os.unlink( NODEUPDATE_PID_FILE )
280