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