source: trunk/plugin/togap.py @ 91

Last change on this file since 91 was 91, checked in by bastiaans, 19 years ago

plugin/PBSQuery.py:

  • Custom version with destructor that kills pbs connection to server

plugin/togap.py:

  • Misc
File size: 9.3 KB
Line 
1#!/usr/bin/env python
2
3# Specify debugging level here;
4#
5DEBUG_LEVEL = 0
6
7# Wether or not to run as a daemon in background
8#
9DAEMONIZE = 0
10
11# How many seconds interval for polling of jobs
12#
13# this will effect directly how accurate the
14# end time of a job can be determined
15#
16TORQUE_POLL_INTERVAL = 10
17
18# Alternate location of gmond.conf
19#
20# Default: /etc/gmond.conf
21#
22#GMOND_CONF = '/etc/gmond.conf'
23
24from PBSQuery import PBSQuery
25import sys
26import time
27import os
28import socket
29import string
30
31class DataProcessor:
32        """Class for processing of data"""
33
34        binary = '/usr/bin/gmetric'
35
36        def __init__( self, binary=None ):
37                """Remember alternate binary location if supplied"""
38
39                if binary:
40                        self.binary = binary
41
42                # Timeout for XML
43                #
44                # From ganglia's documentation:
45                #
46                # 'A metric will be deleted DMAX seconds after it is received, and
47                # DMAX=0 means eternal life.'
48
49                self.dmax = str( int( TORQUE_POLL_INTERVAL ) )
50
51                try:
52                        gmond_file = GMOND_CONF
53
54                except NameError:
55                        gmond_file = '/etc/gmond.conf'
56
57                if not os.path.exists( gmond_file ):
58                        debug_msg( 0, gmond_file + ' does not exist' )
59                        sys.exit( 1 )
60
61                incompatible = self.checkGmetricVersion()
62
63                if incompatible:
64                        debug_msg( 0, 'Gmetric version not compatible, pls upgrade to at least 3.0.1' )
65                        sys.exit( 1 )
66
67        def checkGmetricVersion( self ):
68                """
69                Check version of gmetric is at least 3.0.1
70                for the syntax we use
71                """
72
73                for line in os.popen( self.binary + ' --version' ).readlines():
74
75                        line = line.split( ' ' )
76
77                        if len( line ) == 2 and str(line).find( 'gmetric' ) != -1:
78                       
79                                gmetric_version = line[1].split( '\n' )[0]
80
81                                version_major = int( gmetric_version.split( '.' )[0] )
82                                version_minor = int( gmetric_version.split( '.' )[1] )
83                                version_patch = int( gmetric_version.split( '.' )[2] )
84
85                                incompatible = 0
86
87                                if version_major < 3:
88
89                                        incompatible = 1
90                               
91                                elif version_major == 3:
92
93                                        if version_minor == 0:
94
95                                                if version_patch < 1:
96                                               
97                                                        incompatible = 1
98
99                return incompatible
100
101        def multicastGmetric( self, metricname, metricval, valtype='string' ):
102                """Call gmetric binary and multicast"""
103
104                cmd = self.binary
105
106                try:
107                        cmd = cmd + ' -c' + GMOND_CONF
108                except NameError:
109                        debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
110
111                cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
112
113                print cmd
114                os.system( cmd )
115
116class PBSDataGatherer:
117
118        jobs = { }
119
120        def __init__( self ):
121                """Setup appropriate variables"""
122
123                self.jobs = { }
124                self.dp = DataProcessor()
125                self.initPbsQuery()
126
127        def initPbsQuery( self ):
128
129                self.pq = None
130                self.pq = PBSQuery()
131
132        def getAttr( self, attrs, name ):
133                """Return certain attribute from dictionary, if exists"""
134
135                if attrs.has_key( name ):
136                        return attrs[name]
137                else:
138                        return ''
139
140        def jobDataChanged( self, jobs, job_id, attrs ):
141                """Check if job with attrs and job_id in jobs has changed"""
142
143                if jobs.has_key( job_id ):
144                        oldData = jobs[ job_id ]       
145                else:
146                        return 1
147
148                for name, val in attrs.items():
149
150                        if oldData.has_key( name ):
151
152                                if oldData[ name ] != attrs[ name ]:
153
154                                        return 1
155
156                        else:
157                                return 1
158
159                return 0
160
161        def getJobData( self, known_jobs ):
162                """Gather all data on current jobs in Torque"""
163
164                if len( known_jobs ) > 0:
165                        jobs = known_jobs
166                else:
167                        jobs = { }
168
169                self.initPbsQuery()
170                time.sleep( 1 )
171               
172                joblist = self.pq.getjobs()
173
174                self.cur_time = time.time()
175
176                jobs_processed = [ ]
177
178                for name, attrs in joblist.items():
179
180                        job_id = name.split( '.' )[0]
181
182                        jobs_processed.append( job_id )
183
184                        name = self.getAttr( attrs, 'Job_Name' )
185                        queue = self.getAttr( attrs, 'queue' )
186                        owner = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
187                        requested_time = self.getAttr( attrs, 'Resource_List.walltime' )
188                        requested_memory = self.getAttr( attrs, 'Resource_List.mem' )
189                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
190                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
191                                ppn = mynoderequest.split( ':' )[1].split( 'ppn=' )[1]
192                        else:
193                                ppn = ''
194                        status = self.getAttr( attrs, 'job_state' )
195                        start_timestamp = self.getAttr( attrs, 'mtime' )
196
197                        nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
198                        nodeslist = [ ]
199
200                        for node in nodes:
201                                host = node.split( '/' )[0]
202
203                                if nodeslist.count( host ) == 0:
204                                        nodeslist.append( node.split( '/' )[0] )
205
206                        myAttrs = { }
207                        myAttrs['name'] = name
208                        myAttrs['queue'] = queue
209                        myAttrs['owner'] = owner
210                        myAttrs['requested_time'] = requested_time
211                        myAttrs['requested_memory'] = requested_memory
212                        myAttrs['ppn'] = ppn
213                        myAttrs['status'] = status
214                        myAttrs['start_timestamp'] = start_timestamp
215                        myAttrs['reported'] = str( int( self.cur_time ) )
216                        myAttrs['nodes'] = nodeslist
217                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
218                        myAttrs['poll_interval'] = TORQUE_POLL_INTERVAL
219
220                        if self.jobDataChanged( jobs, job_id, myAttrs ):
221                                jobs[ job_id ] = myAttrs
222
223                                #self.printJob( jobs, job_id )
224
225                                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
226
227                for id, attrs in jobs.items():
228
229                        if id not in jobs_processed:
230
231                                # This one isn't there anymore; toedeledoki!
232                                #
233                                del jobs[ id ]
234
235                return jobs
236
237        def submitJobData( self, jobs ):
238                """Submit job info list"""
239
240                self.dp.multicastGmetric( 'TOGA-HEARTBEAT', str( int( self.cur_time ) ) )
241
242                # Now let's spread the knowledge
243                #
244                for jobid, jobattrs in jobs.items():
245
246                        if jobattrs['status'] in [ 'Q', 'R' ]:
247
248                                gmetric_val = self.compileGmetricVal( jobid, jobattrs )
249
250                                for val in gmetric_val:
251                                        self.dp.multicastGmetric( 'TOGA-JOB-' + jobid, val )
252
253        def makeNodeString( self, nodelist ):
254                """Make one big string of all hosts"""
255
256                node_str = None
257
258                for node in nodelist:
259                        if not node_str:
260                                node_str = node
261                        else:
262                                node_str = node_str + ';' + node
263
264                return node_str
265
266        def compileGmetricVal( self, jobid, jobattrs ):
267                """Create a val string for gmetric of jobinfo"""
268
269                appendList = [ ]
270                appendList.append( 'name=' + jobattrs['name'] )
271                appendList.append( 'queue=' + jobattrs['queue'] )
272                appendList.append( 'owner=' + jobattrs['owner'] )
273                appendList.append( 'requested_time=' + jobattrs['requested_time'] )
274                appendList.append( 'requested_memory=' + jobattrs['requested_memory'] )
275                appendList.append( 'ppn=' + jobattrs['ppn'] )
276                appendList.append( 'status=' + jobattrs['status'] )
277                appendList.append( 'start_timestamp=' + jobattrs['start_timestamp'] )
278                appendList.append( 'reported=' + jobattrs['reported'] )
279                appendList.append( 'poll_interval=' + str( jobattrs['poll_interval'] ) )
280                appendList.append( 'domain=' + jobattrs['domain'] )
281                appendList.append( 'nodes=' + self.makeNodeString( jobattrs['nodes'] ) )
282
283                return self.makeAppendLists( appendList )
284
285        def makeAppendLists( self, append_list ):
286                """
287                Divide all values from append_list over strings with a maximum
288                size of 1400
289                """
290
291                app_lists = [ ]
292
293                mystr = None
294
295                for val in append_list:
296
297                        if not mystr:
298                                mystr = val
299                        else:
300                                if not self.checkValAppendMaxSize( mystr, val ):
301                                        mystr = mystr + ' ' + val
302                                else:
303                                        # Too big, new appenlist
304                                        app_lists.append( mystr )
305                                        mystr = val
306
307                app_lists.append( mystr )
308
309                return app_lists
310
311        def checkValAppendMaxSize( self, val, text ):
312                """Check if val + text size is not above 1400 (max msg size)"""
313
314                # Max frame size of a udp datagram is 1500 bytes
315                # removing misc header and gmetric stuff leaves about 1400 bytes
316                #
317                if len( val + text ) > 1400:
318                        return 1
319                else:
320                        return 0
321
322        def printJobs( self, jobs ):
323                """Print a jobinfo overview"""
324
325                for name, attrs in self.jobs.items():
326
327                        print 'job %s' %(name)
328
329                        for name, val in attrs.items():
330
331                                print '\t%s = %s' %( name, val )
332
333        def printJob( self, jobs, job_id ):
334                """Print job with job_id from jobs"""
335
336                print 'job %s' %(job_id)
337
338                for name, val in jobs[ job_id ].items():
339
340                        print '\t%s = %s' %( name, val )
341
342        def daemon( self ):
343                """Run as daemon forever"""
344
345                # Fork the first child
346                #
347                pid = os.fork()
348                if pid > 0:
349                        sys.exit(0)  # end parrent
350
351                # creates a session and sets the process group ID
352                #
353                os.setsid()
354
355                # Fork the second child
356                #
357                pid = os.fork()
358                if pid > 0:
359                        sys.exit(0)  # end parrent
360
361                # Go to the root directory and set the umask
362                #
363                os.chdir('/')
364                os.umask(0)
365
366                sys.stdin.close()
367                sys.stdout.close()
368                sys.stderr.close()
369
370                os.open('/dev/null', 0)
371                os.dup(0)
372                os.dup(0)
373
374                self.run()
375
376        def run( self ):
377                """Main thread"""
378
379                while ( 1 ):
380               
381                        self.jobs = self.getJobData( self.jobs )
382                        self.submitJobData( self.jobs )
383                        time.sleep( TORQUE_POLL_INTERVAL )     
384
385def printTime( ):
386        """Print current time/date in human readable format for log/debug"""
387
388        return time.strftime("%a, %d %b %Y %H:%M:%S")
389
390def debug_msg( level, msg ):
391        """Print msg if at or above current debug level"""
392
393        if (DEBUG_LEVEL >= level):
394                        sys.stderr.write( msg + '\n' )
395
396def main():
397        """Application start"""
398
399        gather = PBSDataGatherer()
400        if DAEMONIZE:
401                gather.daemon()
402        else:
403                gather.run()
404
405# w00t someone started me
406#
407if __name__ == '__main__':
408        main()
Note: See TracBrowser for help on using the repository browser.