source: trunk/plugin/togap.py @ 168

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

plugin/togap.py:

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