Source

pythongrid / pythongrid.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#! /usr/bin/env python

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Written (W) 2008-2009 Christian Widmer
# Written (W) 2008-2009 Cheng Soon Ong
# Copyright (C) 2008-2009 Max-Planck-Society


"""
pythongrid provides a high level front end to DRMAA-python.
This module provides wrappers that simplify submission and collection of jobs,
in a more 'pythonic' fashion.
"""

#paths on cluster file system
#PYTHONPATH = ["/fml/ag-raetsch/home/raetsch/svn/tools/python/", "/fml/ag-raetsch/home/raetsch/svn/tools/python/pythongrid/", '/fml/ag-raetsch/home/raetsch/mylibs/lib/python2.5/site-packages/', '/fml/ag-raetsch/home/raetsch/projects/Git-QPalma/ParaParser', '/fml/ag-raetsch/home/raetsch/projects/Git-QPalma/DynProg/', '/fml/ag-raetsch/share/software/mosek/5/tools/platform/linux64x86/bin', '/fml/ag-raetsch/home/fabio/site-packages', '/fml/ag-raetsch/home/raetsch/projects/Git-QPalma/Genefinding', '/fml/ag-raetsch/share/software/lib/python2.5/site-packages']

import sys
import os
import os.path
import bz2
import cPickle
import getopt
import time
import random
import traceback


#paths on cluster file system
PYTHONPATH = os.environ['PYTHONPATH'] #["/fml/ag-raetsch/home/raetsch/svn/tools/python/", "/fml/ag-raetsch/home/raetsch/svn/tools/python/pythongrid/", '/fml/ag-raetsch/home/raetsch/mylibs/lib/python2.5/site-packages/', '/fml/ag-raetsch/home/raetsch/projects/Git-QPalma/ParaParser', '/fml/ag-raetsch/home/raetsch/projects/Git-QPalma/DynProg/', '/fml/ag-raetsch/share/software/mosek/5/tools/platform/linux64x86/bin', '/fml/ag-raetsch/home/fabio/site-packages', '/fml/ag-raetsch/home/raetsch/projects/Git-QPalma/Genefinding', '/fml/ag-raetsch/share/software/lib/python2.5/site-packages']

# location of pythongrid.py on cluster file system
# TODO set this in configuration file
PYGRID = "~/svn/tools/python/pythongrid/pythongrid.py"

# define temp directories for the input and output variables
# (must be writable from cluster)
# TODO define separate client/server TEMPDIR
# ag-raetsch
TEMPDIR = "~/tmp/"


# used for generating random filenames
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

PPATH=reduce(lambda x,y: x+':'+y, PYTHONPATH) ;
print PPATH
os.environ['PYTHONPATH'] = PPATH;

sys.path.extend(PYTHONPATH)


print "sys.path=" + str(sys.path) ;

jp = os.path.join

drmaa_present=True
multiprocessing_present=True

try:
    import drmaa
except ImportError, detail:
    print "Error importing drmaa. Only local multi-threading supported."
    print "Please check your installation."
    print detail
    drmaa_present=False

try:
    import multiprocessing
except ImportError, detail:
    print "Error importing multiprocessing. Local computing limited to one CPU."
    print "Please install python2.6 or the backport of the multiprocessing package"
    print detail
    multiprocessing_present=False

class Job(object):
    """
    Central entity that wraps a function and its data. Basically,
    a job consists of a function, its argument list, its
    keyword list and a field "ret" which is filled, when
    the execute method gets called
    """

    def __init__(self, f, args, kwlist={}, cleanup=True):
        """
        constructor of Job

        @param f: a function, which should be executed.
        @type f: function
        @param args: argument list of function f
        @type args: list
        @param kwlist: dictionary of keyword arguments
        @type kwlist: dict
        @param cleanup: flag that determines the cleanup of input and log file
        @type cleanup: boolean
        """
        self.f = f
        self.args = args
        self.kwlist = kwlist
        self.cleanup = cleanup
        self.ret = None
        self.inputfile = ""
        self.outputfile = ""
        self.nativeSpecification = ""
        self.exception = None
        self.environment = None
        self.replace_env = False

        outdir = os.path.expanduser(TEMPDIR)
        if not os.path.isdir(outdir):
            print '%s does not exist. Please create a directory' % outdir
            raise Exception()

        # TODO: ensure uniqueness of file names
        self.name = 'pg'+''.join([random.choice(alphabet) for a in xrange(8)])
        self.inputfile = jp(outdir,self.name + "_in.bz2")
        self.outputfile = jp(outdir,self.name + "_out.bz2")
        self.jobid = ""


    def __repr_broken__(self):
        #TODO: fix representation
        retstr1 = ('%s\nargs=%s\nkwlist=%s\nret=%s\ncleanup=%s' %
                   self.f, self.args, self.kwlist, self.ret, self.cleanup)
        retstr2 = ('\nnativeSpecification=%s\ninputfile=%s\noutputfile=%s\n' %
                   self.nativeSpecification, self.inputfile, self.outputfile)
        return retstr1 + retstr2

    def execute(self):
        """
        Executes function f with given arguments
        and writes return value to field ret.
        If an exception is encountered during execution, ret will
        remain empty and the exception will be written
        to the exception field of the Job object.
        Input data is removed after execution to save space.
        """
        try:
            self.ret = apply(self.f, self.args, self.kwlist)

        except Exception, e:

            print "exception encountered"
            print "type:", str(type(e))
            print "line number:", sys.exc_info()[2].tb_lineno
            print e
            traceback.print_exc(file=sys.stdout)
            print "========="
            self.exception = e


class KybJob(Job):
    """
    Specialization of generic Job that provides an interface to
    the system at MPI Biol. Cyber. Tuebingen.
    """

    def __init__(self, f, args, kwlist={}, cleanup=True):
        """
        constructor of KybJob
        """
        Job.__init__(self, f, args, kwlist, cleanup)
        self.h_vmem = ""
        self.arch = ""
        self.tmpfree = ""
        self.h_cpu = ""
        self.h_rt = ""
        self.express = ""
        self.matlab = ""
        self.simulink = ""
        self.compiler = ""
        self.imagetb = ""
        self.opttb = ""
        self.stattb = ""
        self.sigtb = ""
        self.cplex = ""
        self.nicetohave = ""


    def getNativeSpecification(self):
        """
        define python-style getter
        """

        ret = ""

        if (self.name != ""):
            ret = ret + " -N " + str(self.name)
        if (self.h_vmem != ""):
            ret = ret + " -l " + "h_vmem" + "=" + str(self.h_vmem)
        if (self.arch != ""):
            ret = ret + " -l " + "arch" + "=" + str(self.arch)
        if (self.tmpfree != ""):
            ret = ret + " -l " + "tmpfree" + "=" + str(self.tmpfree)
        if (self.h_cpu != ""):
            ret = ret + " -l " + "h_cpu" + "=" + str(self.h_cpu)
        if (self.h_rt != ""):
            ret = ret + " -l " + "h_rt" + "=" + str(self.h_rt)
        if (self.express != ""):
            ret = ret + " -l " + "express" + "=" + str(self.express)
        if (self.matlab != ""):
            ret = ret + " -l " + "matlab" + "=" + str(self.matlab)
        if (self.simulink != ""):
            ret = ret + " -l " + "simulink" + "=" + str(self.simulink)
        if (self.compiler != ""):
            ret = ret + " -l " + "compiler" + "=" + str(self.compiler)
        if (self.imagetb != ""):
            ret = ret + " -l " + "imagetb" + "=" + str(self.imagetb)
        if (self.opttb != ""):
            ret = ret + " -l " + "opttb" + "=" + str(self.opttb)
        if (self.stattb != ""):
            ret = ret + " -l " + "stattb" + "=" + str(self.stattb)
        if (self.sigtb != ""):
            ret = ret + " -l " + "sigtb" + "=" + str(self.sigtb)
        if (self.cplex != ""):
            ret = ret + " -l " + "cplex" + "=" + str(self.cplex)
        if (self.nicetohave != ""):
            ret = ret + " -l " + "nicetohave" + "=" + str(self.nicetohave)

        return ret


    def setNativeSpecification(self, x):
        """
        define python-style setter
        @param x: nativeSpecification string to be set
        @type x: string
        """

        self.__nativeSpecification = x

    nativeSpecification = property(getNativeSpecification,
                                   setNativeSpecification)



#only define this class if the multiprocessing module is present
if multiprocessing_present:

    class JobsProcess(multiprocessing.Process):
        """
        In case jobs are to be computed locally, a number of Jobs (possibly one)
        are assinged to one thread.
        """

        def __init__(self, jobs):
            """
            Constructor
            @param jobs: list of jobs
            @type jobs: list of Job objects
            """

            self.jobs = jobs
            multiprocessing.Process.__init__(self)

        def run(self):
            """
            Executes each job in job list
            """
            for job in self.jobs:
                job.execute()


def _execute(job):
    """Cannot pickle method instances, so fake a function.
    Used by _process_jobs_locally"""
    
    return apply(job.f, job.args, job.kwlist)



def _process_jobs_locally(jobs, maxNumThreads=None):
    """
    Local execution using the package multiprocessing, if present
    
    @param jobs: jobs to be executed
    @type jobs: list<Job>
    @param maxNumThreads: maximal number of threads
    @type maxNumThreads: int
    
    @return: list of jobs, each with return in job.ret
    @rtype: list<Job>
    """
    
    
    if (not multiprocessing_present or maxNumThreads == 1):
        #perform sequential computation
        for job in jobs:
            job.execute()
    else:
        #print multiprocessing.cpu_count()
        po = multiprocessing.Pool(maxNumThreads)
        result = po.map(_execute, jobs)
        for ix,job in enumerate(jobs):
            job.ret = result[ix]
            
    return jobs


def submit_jobs(jobs):
    """
    Method used to send a list of jobs onto the cluster.
    @param jobs: list of jobs to be executed
    @type jobs: list<Job>
    """

    s = drmaa.Session()
    s.initialize()
    jobids = []

    for job in jobs:
        save(job.inputfile, job)
        jt = s.createJobTemplate()

        #fetch only specific env vars from shell
        #shell_env = {"LD_LIBRARY_PATH": os.getenv("LD_LIBRARY_PATH"),
        #             "PYTHONPATH": os.getenv("PYTHONPATH"),
        #             "MOSEKLM_LICENSE_FILE": os.getenv("MOSEKLM_LICENSE_FILE"),
        #             }

        # fetch env vars from shell        
        shell_env = os.environ

        if job.environment and job.replace_env:
            # only consider defined env vars
            jt.setEnvironment(job.environment)

        elif job.environment and not job.replace_env:
            # replace env var from shell with defined env vars
            env = shell_env
            env.update(job.environment)
            jt.setEnvironment(env)

        else:
            # only consider env vars from shell
            jt.setEnvironment(shell_env)

        jt.remoteCommand = os.path.expanduser(PYGRID)
        jt.args = [job.inputfile]
        jt.joinFiles = True
        jt.setNativeSpecification(job.nativeSpecification)
        jt.outputPath = ":" + os.path.expanduser(TEMPDIR)
        jt.errorPath = ":" + os.path.expanduser(TEMPDIR)

        jobid = s.runJob(jt)

        # set job fields that depend on the jobid assigned by grid engine
        job.jobid = jobid
        log_stdout_fn = (os.path.expanduser(TEMPDIR) + job.name + '.o' + jobid)
        log_stderr_fn = (os.path.expanduser(TEMPDIR) + job.name + '.e' + jobid)

        print 'Your job %s has been submitted with id %s' % (job.name, jobid)
        print "stdout:", log_stdout_fn
        print "stderr:", log_stderr_fn
        print ""

        #display tmp file size
        # print os.system("du -h " + invars)

        jobids.append(jobid)
        s.deleteJobTemplate(jt)

    sid = s.getContact()
    s.exit()

    return (sid, jobids)


def collect_jobs(sid, jobids, joblist, wait=False):
    """
    Collect the results from the jobids, returns a list of Jobs

    @param sid: session identifier
    @type sid: string returned by cluster
    @param jobids: list of job identifiers returned by the cluster
    @type jobids: list of strings
    @param wait: Wait for jobs to finish?
    @type wait: Boolean, defaults to False
    """

    for ix in xrange(len(jobids)):
        assert(jobids[ix] == joblist[ix].jobid)

    s = drmaa.Session()
    s.initialize(sid)

    if wait:
        drmaaWait = drmaa.Session.TIMEOUT_WAIT_FOREVER
    else:
        drmaaWait = drmaa.Session.TIMEOUT_NO_WAIT

    s.synchronize(jobids, drmaaWait, True)
    print "success: all jobs finished"
    s.exit()

    #attempt to collect results
    retJobs = []
    for ix, job in enumerate(joblist):
        
        log_stdout_fn = (os.path.expanduser(TEMPDIR) + job.name + '.o' + jobids[ix])
        log_stderr_fn = (os.path.expanduser(TEMPDIR) + job.name + '.e' + jobids[ix])
        
        try:
            retJob = load(job.outputfile)
            assert(retJob.name == job.name)
            retJobs.append(retJob)

            #print exceptions
            if retJob.exception != None:
                print str(type(retJob.exception))
                print "Exception encountered in job with log file:"
                print log_stdout_fn
                print retJob.exception

            #remove files
            elif retJob.cleanup:

                print "cleaning up:", job.outputfile
                os.remove(job.outputfile)

                if retJob != None:

                    print "cleaning up:", log_stdout_fn
                    os.remove(log_stdout_fn)

                    print "cleaning up:", log_stderr_fn
                    #os.remove(log_stderr_fn)


        except Exception, detail:
            print "error while unpickling file: " + job.outputfile
            print "this could caused by a problem with the cluster environment, imports or environment variables"
            print "check log files for more information: "
            print "stdout:", log_stdout_fn
            print "stderr:", log_stderr_fn
            
            print detail



    return retJobs


def process_jobs(jobs, local=False, maxNumThreads=1):
    """
    Director function to decide whether to run on the cluster or locally
    """
    
    if (not local and drmaa_present):
        # Use submit_jobs and collect_jobs to run jobs and wait for the results.
        (sid, jobids) = submit_jobs(jobs)
        return collect_jobs(sid, jobids, jobs, wait=True)

    elif (not local and not drmaa_present):
        print 'Warning: import drmaa failed, computing locally'
        return  _process_jobs_locally(jobs, maxNumThreads=maxNumThreads)

    else:
        return  _process_jobs_locally(jobs, maxNumThreads=maxNumThreads)


def get_status(sid, jobids):
    """
    Get the status of all jobs in jobids.
    Returns True if all jobs are finished.

    There is some instability in determining job completion
    """
    _decodestatus = {
        -42: 'sge and drmaa not in sync',
        drmaa.Session.UNDETERMINED: 'process status cannot be determined',
        drmaa.Session.QUEUED_ACTIVE: 'job is queued and active',
        drmaa.Session.SYSTEM_ON_HOLD: 'job is queued and in system hold',
        drmaa.Session.USER_ON_HOLD: 'job is queued and in user hold',
        drmaa.Session.USER_SYSTEM_ON_HOLD: 'job is in user and system hold',
        drmaa.Session.RUNNING: 'job is running',
        drmaa.Session.SYSTEM_SUSPENDED: 'job is system suspended',
        drmaa.Session.USER_SUSPENDED: 'job is user suspended',
        drmaa.Session.DONE: 'job finished normally',
        drmaa.Session.FAILED: 'job finished, but failed',
        }

    s = drmaa.Session()
    s.initialize(sid)
    status_summary = {}.fromkeys(_decodestatus, 0)
    for jobid in jobids:
        try:
            curstat = s.getJobProgramStatus(jobid)
        except drmaa.InvalidJobError, message:
            print message
            status_summary[-42] += 1
        else:
            status_summary[curstat] += 1

    print 'Status of %s at %s' % (sid, time.strftime('%d/%m/%Y - %H.%M:%S'))
    for curkey in status_summary.keys():
        if status_summary[curkey]>0:
            print '%s: %d' % (_decodestatus[curkey], status_summary[curkey])
    s.exit()

    return ((status_summary[drmaa.Session.DONE]
             +status_summary[-42])==len(jobids))


#####################################################################
# Dealing with data
#####################################################################


def save(filename, myobj):
    """
    Save myobj to filename using pickle
    """
    try:
        f = bz2.BZ2File(filename, 'wb')
    except IOError, details:
        sys.stderr.write('File ' + filename + ' cannot be written\n')
        sys.stderr.write(details)
        return

    cPickle.dump(myobj, f, protocol=2)
    f.close()


def load(filename):
    """
    Load from filename using pickle
    """
    try:
        f = bz2.BZ2File(filename, 'rb')
    except IOError, details:
        sys.stderr.write('File ' + filename + ' cannot be read\n')
        sys.stderr.write(details)
        return

    myobj = cPickle.load(f)
    f.close()
    return myobj


################################################################
#      The following code will be executed on the cluster      #
################################################################


def run_job(pickleFileName):
    """
    This is the code that is executed on the cluster side.
    Runs job which was pickled to a file called pickledFileName.

    @param pickleFileName: filename of pickled Job object
    @type pickleFileName: string
    """

    inPath = pickleFileName
    job = load(inPath)

    job.execute()

    #remove input file
    if job.cleanup:
        os.remove(job.inputfile)

    save(job.outputfile, job)


class Usage(Exception):
    """
    Simple Exception for cmd-line user-interface.
    """

    def __init__(self, msg):
        """
        Constructor of simple Exception.

        @param msg: exception message
        @type msg: string
        """

        self.msg = msg


def main(argv=None):
    """
    Parse the command line inputs and call run_job

    @param argv: list of arguments
    @type argv: list of strings
    """


    if argv is None:
        argv = sys.argv

    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
            run_job(args[0])
        except getopt.error, msg:
            raise Usage(msg)


    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"

        return 2

if __name__ == "__main__":
    main(sys.argv)