35530358ab65a4505df2e8b0bcb662f101b43e90
[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
184     def RebuildRPMdb( self ):
185         Message( "\nRebuilding RPM Database." )
186         try: os.system( "rm /var/lib/rpm/__db.*" )
187         except Exception, err: print "RebuildRPMdb: %s" % err
188         try: os.system( "%s --rebuilddb" % RPM_PATH )
189         except Exception, err: print "RebuildRPMdb: %s" % err
190
191     def YumCleanAll ( self ):
192         Message ("\nCleaning all yum cache (yum clean all)")
193         try:
194             os.system( "yum clean all")
195         except:
196             pass
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. 
230     # this is useful for running something silently 
231     # under cron and as a service (at startup), 
232     # so the cron only outputs errors and doesn't
233     # generate mail when it works correctly
234
235     displayOutput= 0
236
237     # if we hit an rpm that requests a reboot, do it if this is
238     # set to 1. can be turned off by adding noreboot to command line
239     # option
240     
241     doReboot= 1
242
243     if "start" in sys.argv or "display" in sys.argv:
244         displayOutput= 1
245         Message ("\nTurning on messages")
246
247     if "noreboot" in sys.argv:
248         doReboot= 0
249
250     if "updatecron" in sys.argv:
251         # simply update the /etc/cron.d file for us, and exit
252         UpdateCronFile()
253         sys.exit(0)
254
255     if "removecron" in sys.argv:
256         RemoveCronFile()
257         sys.exit(0)     
258
259             
260     # see if we are already running by checking the existance
261     # of a PID file, and if it exists, attempting a test kill
262     # to see if the process really does exist. If both of these
263     # tests pass, exit.
264     
265     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
266         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
267         if pid <> "":
268             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
269                 Message( "It appears we are already running, exiting." )
270                 sys.exit(1)
271                     
272     # write out our process id
273     pidfile= file( NODEUPDATE_PID_FILE, 'w' )
274     pidfile.write( "%d\n" % os.getpid() )
275     pidfile.close()
276
277     
278     nodeupdate= NodeUpdate(doReboot)
279     if not nodeupdate:
280         Error( "Unable to initialize." )
281     else:
282         nodeupdate.RebuildRPMdb()
283         nodeupdate.RemoveRPMS()
284         nodeupdate.InstallKeys()
285         nodeupdate.YumCleanAll()
286         nodeupdate.CheckForUpdates()
287         Message( "\nUpdate complete." )
288
289     # remove the PID file
290     os.unlink( NODEUPDATE_PID_FILE )
291