source: trunk/plugin/togap.py @ 101

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

plugin/PBSQuery.py:

  • Removed; Bas fixed std version

plugin/togap.py:

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