source: trunk/plugin/togap.py @ 93

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

plugin/togap.py:

  • Removed sleep
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               
171                joblist = self.pq.getjobs()
172
173                self.cur_time = time.time()
174
175                jobs_processed = [ ]
176
177                for name, attrs in joblist.items():
178
179                        job_id = name.split( '.' )[0]
180
181                        jobs_processed.append( job_id )
182
183                        name = self.getAttr( attrs, 'Job_Name' )
184                        queue = self.getAttr( attrs, 'queue' )
185                        owner = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
186                        requested_time = self.getAttr( attrs, 'Resource_List.walltime' )
187                        requested_memory = self.getAttr( attrs, 'Resource_List.mem' )
188                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
189                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
190                                ppn = mynoderequest.split( ':' )[1].split( 'ppn=' )[1]
191                        else:
192                                ppn = ''
193                        status = self.getAttr( attrs, 'job_state' )
194                        start_timestamp = self.getAttr( attrs, 'mtime' )
195
196                        nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
197                        nodeslist = [ ]
198
199                        for node in nodes:
200                                host = node.split( '/' )[0]
201
202                                if nodeslist.count( host ) == 0:
203                                        nodeslist.append( node.split( '/' )[0] )
204
205                        myAttrs = { }
206                        myAttrs['name'] = name
207                        myAttrs['queue'] = queue
208                        myAttrs['owner'] = owner
209                        myAttrs['requested_time'] = requested_time
210                        myAttrs['requested_memory'] = requested_memory
211                        myAttrs['ppn'] = ppn
212                        myAttrs['status'] = status
213                        myAttrs['start_timestamp'] = start_timestamp
214                        myAttrs['reported'] = str( int( self.cur_time ) )
215                        myAttrs['nodes'] = nodeslist
216                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
217                        myAttrs['poll_interval'] = TORQUE_POLL_INTERVAL
218
219                        if self.jobDataChanged( jobs, job_id, myAttrs ):
220                                jobs[ job_id ] = myAttrs
221
222                                #self.printJob( jobs, job_id )
223
224                                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
225
226                for id, attrs in jobs.items():
227
228                        if id not in jobs_processed:
229
230                                # This one isn't there anymore; toedeledoki!
231                                #
232                                del jobs[ id ]
233
234                return jobs
235
236        def submitJobData( self, jobs ):
237                """Submit job info list"""
238
239                self.dp.multicastGmetric( 'TOGA-HEARTBEAT', str( int( self.cur_time ) ) )
240
241                # Now let's spread the knowledge
242                #
243                for jobid, jobattrs in jobs.items():
244
245                        if jobattrs['status'] in [ 'Q', 'R' ]:
246
247                                gmetric_val = self.compileGmetricVal( jobid, jobattrs )
248
249                                for val in gmetric_val:
250                                        self.dp.multicastGmetric( 'TOGA-JOB-' + jobid, val )
251
252        def makeNodeString( self, nodelist ):
253                """Make one big string of all hosts"""
254
255                node_str = None
256
257                for node in nodelist:
258                        if not node_str:
259                                node_str = node
260                        else:
261                                node_str = node_str + ';' + node
262
263                return node_str
264
265        def compileGmetricVal( self, jobid, jobattrs ):
266                """Create a val string for gmetric of jobinfo"""
267
268                appendList = [ ]
269                appendList.append( 'name=' + jobattrs['name'] )
270                appendList.append( 'queue=' + jobattrs['queue'] )
271                appendList.append( 'owner=' + jobattrs['owner'] )
272                appendList.append( 'requested_time=' + jobattrs['requested_time'] )
273                appendList.append( 'requested_memory=' + jobattrs['requested_memory'] )
274                appendList.append( 'ppn=' + jobattrs['ppn'] )
275                appendList.append( 'status=' + jobattrs['status'] )
276                appendList.append( 'start_timestamp=' + jobattrs['start_timestamp'] )
277                appendList.append( 'reported=' + jobattrs['reported'] )
278                appendList.append( 'poll_interval=' + str( jobattrs['poll_interval'] ) )
279                appendList.append( 'domain=' + jobattrs['domain'] )
280                appendList.append( 'nodes=' + self.makeNodeString( jobattrs['nodes'] ) )
281
282                return self.makeAppendLists( appendList )
283
284        def makeAppendLists( self, append_list ):
285                """
286                Divide all values from append_list over strings with a maximum
287                size of 1400
288                """
289
290                app_lists = [ ]
291
292                mystr = None
293
294                for val in append_list:
295
296                        if not mystr:
297                                mystr = val
298                        else:
299                                if not self.checkValAppendMaxSize( mystr, val ):
300                                        mystr = mystr + ' ' + val
301                                else:
302                                        # Too big, new appenlist
303                                        app_lists.append( mystr )
304                                        mystr = val
305
306                app_lists.append( mystr )
307
308                return app_lists
309
310        def checkValAppendMaxSize( self, val, text ):
311                """Check if val + text size is not above 1400 (max msg size)"""
312
313                # Max frame size of a udp datagram is 1500 bytes
314                # removing misc header and gmetric stuff leaves about 1400 bytes
315                #
316                if len( val + text ) > 1400:
317                        return 1
318                else:
319                        return 0
320
321        def printJobs( self, jobs ):
322                """Print a jobinfo overview"""
323
324                for name, attrs in self.jobs.items():
325
326                        print 'job %s' %(name)
327
328                        for name, val in attrs.items():
329
330                                print '\t%s = %s' %( name, val )
331
332        def printJob( self, jobs, job_id ):
333                """Print job with job_id from jobs"""
334
335                print 'job %s' %(job_id)
336
337                for name, val in jobs[ job_id ].items():
338
339                        print '\t%s = %s' %( name, val )
340
341        def daemon( self ):
342                """Run as daemon forever"""
343
344                # Fork the first child
345                #
346                pid = os.fork()
347                if pid > 0:
348                        sys.exit(0)  # end parrent
349
350                # creates a session and sets the process group ID
351                #
352                os.setsid()
353
354                # Fork the second child
355                #
356                pid = os.fork()
357                if pid > 0:
358                        sys.exit(0)  # end parrent
359
360                # Go to the root directory and set the umask
361                #
362                os.chdir('/')
363                os.umask(0)
364
365                sys.stdin.close()
366                sys.stdout.close()
367                sys.stderr.close()
368
369                os.open('/dev/null', 0)
370                os.dup(0)
371                os.dup(0)
372
373                self.run()
374
375        def run( self ):
376                """Main thread"""
377
378                while ( 1 ):
379               
380                        self.jobs = self.getJobData( self.jobs )
381                        self.submitJobData( self.jobs )
382                        time.sleep( TORQUE_POLL_INTERVAL )     
383
384def printTime( ):
385        """Print current time/date in human readable format for log/debug"""
386
387        return time.strftime("%a, %d %b %Y %H:%M:%S")
388
389def debug_msg( level, msg ):
390        """Print msg if at or above current debug level"""
391
392        if (DEBUG_LEVEL >= level):
393                        sys.stderr.write( msg + '\n' )
394
395def main():
396        """Application start"""
397
398        gather = PBSDataGatherer()
399        if DAEMONIZE:
400                gather.daemon()
401        else:
402                gather.run()
403
404# w00t someone started me
405#
406if __name__ == '__main__':
407        main()
Note: See TracBrowser for help on using the repository browser.