source: trunk/plugin/togap.py @ 85

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

plugin/togap.py:

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