Setting tag NodeUpdate-0.5-6
[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 the list of extensions this node has, each
39 # correspond to a package group in yum repository.
40 # this is expected to be updated from the 'extensions tag' 
41 # through the 'extensions.php' nodeconfig script
42 EXTENSIONS_FILE='/etc/planetlab/extensions'
43
44 # file containing a list of rpms that we should attempt to delete
45 # before updating everything else. This list is not removed with 
46 # 'yum remove', because that could accidently remove dependency rpms
47 # that were not intended to be deleted.
48 DELETE_RPM_LIST_FILE= '/etc/planetlab/delete-rpm-list'
49
50
51 # print out a message only if we are displaying output
52 def Message(message):
53     if displayOutput:
54         if isinstance(message,StringTypes) and len(message) >=2 and message[0]=="\n":
55             print "\n",
56             message=message[1:]
57         print strftime(TIMEFORMAT),
58         print message
59
60 # always print errors
61 def Error(Str):
62     print strftime(TIMEFORMAT),
63     print Str
64
65
66 # create an entry in /etc/cron.d so we run periodically.
67 # we will be run once a day at a 0-59 minute random offset
68 # into a 0-23 random hour
69 def UpdateCronFile():
70     try:
71         
72         randomMinute= Random().randrange( 0, 59, 1 );
73         randomHour= Random().randrange( 0, 11, 1 );
74         
75         f = open( CRON_FILE, 'w' );
76         f.write( "# %s\n" % (TARGET_DESC) );
77         ### xxx is root aliased to the support mailing list ?
78         f.write( "MAILTO=%s\n" % (TARGET_USER) );
79         f.write( "SHELL=%s\n" % (TARGET_SHELL) );
80         f.write( "%s %s,%s * * * %s %s\n\n" %
81                  (randomMinute, randomHour, randomHour + 12, TARGET_USER, TARGET_SCRIPT) );
82         f.close()
83     
84         print( "Created new cron.d entry." )
85     except:
86         print( "Unable to create cron.d entry." )
87
88
89 # simply remove the cron file we created
90 def RemoveCronFile():
91     try:
92         os.unlink( CRON_FILE )
93         print( "Deleted cron.d entry." )
94     except:
95         print( "Unable to delete cron.d entry." )
96         
97
98
99 class NodeUpdate:
100
101     def __init__( self, doReboot ):
102         if self.CheckProxy():
103             os.environ['http_proxy']= self.HTTP_PROXY
104             os.environ['HTTP_PROXY']= self.HTTP_PROXY
105             
106         self.doReboot= doReboot
107
108     
109
110     def CheckProxy( self ):
111         Message( "Checking existence of proxy config file..." )
112         
113         if os.access(PROXY_FILE, os.R_OK) and os.path.isfile(PROXY_FILE):
114             self.HTTP_PROXY= string.strip(file(PROXY_FILE,'r').readline())
115             Message( "Using proxy %s." % self.HTTP_PROXY )
116             return 1
117         else:
118             Message( "Not using any proxy." )
119             return 0
120
121
122     def InstallKeys( self ):
123         Message( "\nRemoving any existing GPG signing keys from the RPM database" )
124         os.system( "%s --allmatches -e gpg-pubkey" % RPM_PATH )
125
126         Message( "\nInstalling all GPG signing keys in %s" % RPM_GPG_PATH )
127         os.system( "%s --import %s/*" % (RPM_PATH, RPM_GPG_PATH) )
128
129
130     def ClearRebootFlag( self ):
131         os.system( "/bin/rm -rf %s" % REBOOT_FLAG )
132
133
134     def CheckForUpdates( self ):
135
136         Message( "\nRemoving any existing reboot flags" )
137         self.ClearRebootFlag()
138
139         if self.doReboot == 0:
140             Message( "\nIgnoring any reboot flags set by RPMs" );
141
142         Message( "\nChecking if yum supports SSL certificate checks" )
143         if os.system( "%s --help | grep -q sslcertdir" % YUM_PATH ) == 0:
144             Message( "It does, using --sslcertdir option" )
145             sslcertdir = "--sslcertdir=" + SSL_CERT_DIR
146         else:
147             Message( "Unsupported, not using --sslcertdir option" )
148             sslcertdir = ""
149                     
150         yum_options=""
151         Message( "\nChecking if yum supports --verbose" )
152         if os.system( "%s --help | grep -q verbose" % YUM_PATH ) == 0:
153             Message( "It does, using --verbose option" )
154             yum_options += " --verbose"
155         else:
156             Message( "Unsupported, not using --verbose option" )
157                     
158         Message( "\nUpdating PlanetLab group" )
159         os.system( "%s %s %s -y groupupdate \"PlanetLab\"" %
160                    (YUM_PATH, yum_options, sslcertdir) )
161
162         Message( "\nUpdating rest of system" )
163         os.system( "%s %s %s -y update" %
164                    (YUM_PATH, yum_options, sslcertdir) )
165
166         Message( "\nChecking for extra groups (extensions) to update" )
167         if os.access(EXTENSIONS_FILE, os.R_OK) and \
168            os.path.isfile(EXTENSIONS_FILE):
169             extensions_contents= file(EXTENSIONS_FILE).read()
170             extensions_contents= string.strip(extensions_contents)
171             if extensions_contents == "":
172                 Message( "No extra groups found in file." )
173             else:
174                 extensions_contents.strip()
175                 for extension in extensions_contents.split():
176                     group = "extension%s" % extension
177                     Message( "\nUpdating %s group" % group )
178                     os.system( "%s %s %s -y groupupdate \"%s\"" %
179                                (YUM_PATH, yum_options, sslcertdir, group) )
180         else:
181             Message( "No extensions file found" )
182             
183         if os.access(REBOOT_FLAG, os.R_OK) and os.path.isfile(REBOOT_FLAG) and self.doReboot:
184             Message( "\nAt least one update requested the system be rebooted" )
185             self.ClearRebootFlag()
186             os.system( "/sbin/shutdown -r now" )
187
188     def RebuildRPMdb( self ):
189         Message( "\nRebuilding RPM Database." )
190         try: os.system( "rm /var/lib/rpm/__db.*" )
191         except Exception, err: print "RebuildRPMdb: %s" % err
192         try: os.system( "%s --rebuilddb" % RPM_PATH )
193         except Exception, err: print "RebuildRPMdb: %s" % err
194
195     def YumCleanAll ( self ):
196         Message ("\nCleaning all yum cache (yum clean all)")
197         try:
198             os.system( "yum clean all")
199         except:
200             pass
201
202     def RemoveRPMS( self ):
203
204         Message( "\nLooking for RPMs to be deleted." )
205         if os.access(DELETE_RPM_LIST_FILE, os.R_OK) and \
206            os.path.isfile(DELETE_RPM_LIST_FILE):
207             rpm_list_contents= file(DELETE_RPM_LIST_FILE).read()
208             rpm_list_contents= string.strip(rpm_list_contents)
209
210             if rpm_list_contents == "":
211                 Message( "No RPMs listed in file to delete." )
212                 return
213
214             rpm_list= string.join(string.split(rpm_list_contents))
215             
216             Message( "Deleting these RPMs:" )
217             Message( rpm_list_contents )
218             
219             rc= os.system( "%s -ev %s" % (RPM_PATH, rpm_list) )
220
221             if rc != 0:
222                 Error( "Unable to delete RPMs, continuing. rc=%d" % rc )
223             else:
224                 Message( "RPMs deleted successfully." )
225             
226         else:
227             Message( "No RPMs list file found." )
228
229
230
231 if __name__ == "__main__":
232
233     # if we are invoked with 'start', display the output. 
234     # this is useful for running something silently 
235     # under cron and as a service (at startup), 
236     # so the cron only outputs errors and doesn't
237     # generate mail when it works correctly
238
239     displayOutput= 0
240
241     # if we hit an rpm that requests a reboot, do it if this is
242     # set to 1. can be turned off by adding noreboot to command line
243     # option
244     
245     doReboot= 1
246
247     if "start" in sys.argv or "display" in sys.argv:
248         displayOutput= 1
249         Message ("\nTurning on messages")
250
251     if "noreboot" in sys.argv:
252         doReboot= 0
253
254     if "updatecron" in sys.argv:
255         # simply update the /etc/cron.d file for us, and exit
256         UpdateCronFile()
257         sys.exit(0)
258
259     if "removecron" in sys.argv:
260         RemoveCronFile()
261         sys.exit(0)     
262
263             
264     # see if we are already running by checking the existance
265     # of a PID file, and if it exists, attempting a test kill
266     # to see if the process really does exist. If both of these
267     # tests pass, exit.
268     
269     if os.access(NODEUPDATE_PID_FILE, os.R_OK):
270         pid= string.strip(file(NODEUPDATE_PID_FILE).readline())
271         if pid <> "":
272             if os.system("/bin/kill -0 %s > /dev/null 2>&1" % pid) == 0:
273                 Message( "It appears we are already running, exiting." )
274                 sys.exit(1)
275                     
276     # write out our process id
277     pidfile= file( NODEUPDATE_PID_FILE, 'w' )
278     pidfile.write( "%d\n" % os.getpid() )
279     pidfile.close()
280
281     
282     nodeupdate= NodeUpdate(doReboot)
283     if not nodeupdate:
284         Error( "Unable to initialize." )
285     else:
286         nodeupdate.RebuildRPMdb()
287         nodeupdate.RemoveRPMS()
288         nodeupdate.InstallKeys()
289         nodeupdate.YumCleanAll()
290         nodeupdate.CheckForUpdates()
291         Message( "\nUpdate complete." )
292
293     # remove the PID file
294     os.unlink( NODEUPDATE_PID_FILE )
295