source: trunk/plugin/togap.py @ 76

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

plugin/togap.py:

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