33ea1f5de92fb1a9be46aad8f9bbe06cbe4da414
[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 # location of file containing http/https proxy info, if needed
66 PROXY_FILE = '/etc/planetlab/http_proxy'
67
68 # this is the flag that indicates an update needs to restart
69 # the system to take effect. it is created by the rpm that requested
70 # the reboot
71 REBOOT_FLAG = '/etc/planetlab/update-reboot'
72
73 # location of directory containing boot server ssl certs
74 SSL_CERT_DIR='/mnt/cdrom/bootme/cacert/'
75
76
77 # print out a message only if we are displaying output
78 def Message(Str):
79     if displayOutput:
80         print Str
81
82
83 # print out a message only if we are displaying output
84 def Error(Str):
85     print Str
86
87
88 # create an entry in /etc/cron.d so we run periodically
89 # we will be run once an hour at a 0-59 random offset
90 def UpdateCronFile():
91     try:
92         randomMinute= Random().randrange( 0, 59, 1 );
93         
94         f = open( CRON_FILE, 'w' );
95         f.write( "# %s\n" % (TARGET_DESC) );
96         f.write( "MAILTO=%s\n" % (TARGET_USER) );
97         f.write( "%s * * * * %s %s\n\n" % (randomMinute, TARGET_USER, TARGET_SCRIPT) );
98         f.close()
99     
100         print( "Created new cron.d entry." )
101     except:
102         print( "Unable to create cron.d entry." )
103
104
105 # simply remove the cron file we created
106 def RemoveCronFile():
107     try:
108         os.unlink( CRON_FILE )
109         print( "Deleted cron.d entry." )
110     except:
111         print( "Unable to delete cron.d entry." )
112         
113
114
115 class NodeUpdate:
116
117     def __init__( self, doReboot ):
118         if self.CheckProxy():
119             os.environ['http_proxy']= self.HTTP_PROXY
120             os.environ['HTTP_PROXY']= self.HTTP_PROXY
121             
122         self.doReboot= doReboot
123
124     
125
126     def CheckProxy( self ):
127         Message( "Checking existance of proxy config file..." )
128         
129         if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
130             self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
131             Message( "Using proxy %s." % self.HTTP_PROXY )
132             return 1
133         else:
134             Message( "Not using any proxy." )
135             return 0
136
137
138     def ClearRebootFlag( self ):
139         os.system( "/bin/rm -rf %s" % REBOOT_FLAG )
140
141
142     def CheckForUpdates( self ):
143
144         Message( "\nRemoving any existing reboot flags" )
145         self.ClearRebootFlag()
146
147         if self.doReboot == 0:
148             Message( "\nIgnoring any reboot flags set by RPMs" );
149                     
150         Message( "\nUpdating PlanetLab group" )
151         os.system( "%s --sslcertdir=%s -y groupupdate \"PlanetLab\"" %
152                    (YUM_PATH,SSL_CERT_DIR) )
153
154         Message( "\nUpdating rest of system" )
155         os.system( "%s --sslcertdir=%s -y update" %
156                    (YUM_PATH,SSL_CERT_DIR) )
157
158         if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
159             Message( "\nAt least one update requested the system be rebooted" )
160             self.ClearRebootFlag()
161             os.system( "/sbin/shutdown -r now" )
162             
163
164
165
166 if __name__ == "__main__":
167
168     # if we are invoked with 'start', display the output. this
169     # is usefull for running something under cron and as a service
170     # (at startup), so the cron only outputs errors and doesn't
171     # generate mail when it works correctly
172
173     displayOutput= 0
174
175     # if we hit an rpm that requests a reboot, do it if this is
176     # set to 1. can be turned off by adding noreboot to command line
177     # option
178     
179     doReboot= 1
180
181     if "start" in sys.argv:
182         displayOutput= 1
183
184     if "noreboot" in sys.argv:
185         doReboot= 0
186
187     if "updatecron" in sys.argv:
188         # simply update the /etc/cron.d file for us, and exit
189         UpdateCronFile()
190         sys.exit(0)
191
192     if "removecron" in sys.argv:
193         RemoveCronFile()
194         sys.exit(0)     
195
196             
197     # see if we are already running by checking the existance
198     # of a PID file, and if it exists, attempting a test kill
199     # to see if the process really does exist. If both of these
200     # tests pass, exit.
201     
202     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
203         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
204         if pid <> "":
205             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
206                 print "It appears we are already running, exiting."
207                 sys.exit(1)
208                     
209     # write out our process id
210     pidfile= file( NODEUPDATE_PID_FILE, 'w' )
211     pidfile.write( "%d\n" % os.getpid() )
212     pidfile.close()
213
214     
215     nodeupdate= NodeUpdate(doReboot)
216     if not nodeupdate:
217         print "Unable to initialize."
218     else:
219         nodeupdate.CheckForUpdates()        
220
221     # remove the PID file
222     os.unlink( NODEUPDATE_PID_FILE )