workflow.py 18.3 KB
Newer Older
Jerome Mariette's avatar
Jerome Mariette committed
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
#
# Copyright (C) 2012 INRA
# 
# 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 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import inspect
import os
import sys
import uuid
import pkgutil
import tempfile
import pickle
import time
import threading
Jerome Mariette's avatar
Jerome Mariette committed
27
28
from ConfigParser import ConfigParser, NoOptionError
import types
Jerome Mariette's avatar
Jerome Mariette committed
29
import logging
Jerome Mariette's avatar
Jerome Mariette committed
30

Jerome Mariette's avatar
Jerome Mariette committed
31
import jflow
Jerome Mariette's avatar
Jerome Mariette committed
32
33
import jflow.utils as utils
from jflow.workflows_manager import WorkflowsManager, JFlowConfigReader
Jerome Mariette's avatar
Jerome Mariette committed
34
from jflow.parameter import Parameter, date
Jerome Mariette's avatar
Jerome Mariette committed
35
36
37
38
39
40
41
42
43
44
45
46

from weaver.script import ABSTRACTIONS
from weaver.script import DATASETS
from weaver.script import FUNCTIONS
from weaver.script import NESTS
from weaver.script import OPTIONS
from weaver.script import STACKS
from weaver.nest import Nest
from weaver.options import Options
from cctools.makeflow import MakeflowLog
from cctools.makeflow.log import Node

Jerome Mariette's avatar
Jerome Mariette committed
47

Jerome Mariette's avatar
Jerome Mariette committed
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
class Workflow(threading.Thread):
    """
    """

    PROPERTIES_FILE_NAME = "workflow.properties"
    MAKEFLOW_LOG_FILE_NAME = "Makeflow.makeflowlog"
    DUMP_FILE_NAME = "workflow.dump"
    WORKING = ".working"
    STATUS_STARTED = "started"
    STATUS_COMPLETED = "completed"
    STATUS_FAILED = "failed"
    STATUS_ABORTED = "aborted"
    
    def __init__(self, args={}, id=None):
        """ 
        """
        # define as a thread
        threading.Thread.__init__(self)
        self.jflow_config_reader = JFlowConfigReader()
        self.manager = WorkflowsManager()
        self.components = []
        self.makes = {}
        self.globals = {}
        self.options = Options()
        self.status = self.STATUS_STARTED
        self.start_time = None
        self.end_time = None
75
        self.function = "process"
Jerome Mariette's avatar
Jerome Mariette committed
76
77
78
79
80
81
82
83
84
        self.comp_pckg = self._import_components()
        self.engine_arguments = ''
        self.component_nameids = {}
        # try to parse engine arguments
        try:
            type, options = self.jflow_config_reader.get_batch()
            if type: self.engine_arguments += ' -T ' + type
            if options : self.engine_arguments += ' -B "' + options + '"'
        except: self.engine_arguments = None
Jerome Mariette's avatar
Jerome Mariette committed
85
86
87
88
89
90
        try:
            # Add config information
            self.name, self.description, self.parameters = self._get_from_config()
        except:
            raise IOError(self.__class__.__name__ + " workflow property file not found or invalid.")
        
Jerome Mariette's avatar
Jerome Mariette committed
91
        self.id = id
Jerome Mariette's avatar
Jerome Mariette committed
92
        self.args = self._extend_and_format_args(self.parameters, args)
Jerome Mariette's avatar
Jerome Mariette committed
93
        self.metadata = self.args["metadata"]
Jerome Mariette's avatar
Jerome Mariette committed
94
95
96
97
98
        if self.id is not None:
            self.directory = self.manager.get_workflow_directory(self.name, self.id)
            if not os.path.isdir(self.directory):
                os.makedirs(self.directory, 0751)
            self._serialize()
99
    
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    def init_component_nameids(self):
        # TODO
        # could be better with a better parsing of the add_component parameters
        for line in inspect.getsourcelines(getattr(self, self.function))[0]:
            if line.find("self.add_component(") != -1:
                prefix = "default"
                params = line.strip().split("self.add_component(")[1][:-1]
                try: prefix = params.split("component_prefix=")[1][1:-1]
                except: pass
                component_name = params.split(",")[0][1:-1]
                if self._component_is_duplicated(component_name+"."+prefix):
                    raise ValueError("Component " + component_name + " with prefix " + 
                                     prefix + " already exist in this pipeline!")
                self.component_nameids[component_name+"."+prefix] = None
    
115
116
117
118
119
120
121
    @staticmethod
    def config_parser(arg_line):
        for arg in arg_line.split():
            if not arg.strip():
                continue
            yield arg
    
Jerome Mariette's avatar
Jerome Mariette committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    def __setstate__(self, state):
        self.__dict__ = state.copy()
        threading.Thread.__init__(self, name=self.name)
        
    def __getstate__(self):
        """
        Threading uses Lock Object, do not consider these objects when serializing a workflow
        """
        odict = self.__dict__.copy()
        del odict['_Thread__started']
        del odict['_Thread__block']
        del odict['_Thread__stderr']
        return odict
    
    def add_component(self, component_name, args=[], kwargs={}, component_prefix="default"):
        # first build and check if this component is OK
138
139
140
141
142
143
144
145
        if self.comp_pckg.has_key(component_name):
            my_pckge = __import__(self.comp_pckg[component_name], globals(), locals(), [component_name], -1)
            # build the object and define required field
            cmpt_object = getattr(my_pckge, component_name)()
            cmpt_object.output_directory = self.get_component_output_directory(component_name, component_prefix)
            cmpt_object.prefix = component_prefix
            if kwargs: cmpt_object.define_parameters(**kwargs)
            else: cmpt_object.define_parameters(*args)
146
147
148
149
150
            # add the component
            self.components.append(cmpt_object)
            # if this one require a dynamic pipeline, execute the first part
            if cmpt_object.is_dynamic:
                self._execute_weaver()
151
152
            return cmpt_object
        else:
Jerome Mariette's avatar
Jerome Mariette committed
153
            raise ImportError(component_name + " component cannot be loaded, available components are: {0}".format(", ".join(self.comp_pckg.keys())))
Jerome Mariette's avatar
Jerome Mariette committed
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
    
    def pre_process(self):
        pass
    
    def process(self):
        """ 
        Run the workflow, has to be implemented by subclasses
        """
        raise NotImplementedError
    
    def post_process(self):
        pass
    
    def get_temporary_file(self, suffix=".txt"):
        # first check if tmp directory exists
        if not os.path.isdir(self.jflow_config_reader.get_tmp_directory()):
            os.makedirs(self.jflow_config_reader.get_tmp_directory(), 0751)
        tempfile_name = os.path.basename(tempfile.NamedTemporaryFile(suffix=suffix).name)
        return os.path.join(self.jflow_config_reader.get_tmp_directory(), tempfile_name)

    def get_component_output_directory(self, component_name, component_prefix):
        return os.path.join(self.directory, component_name + "_" + component_prefix)
    
    def get_components_nameid(self):
        return self.component_nameids.keys()
    
    def run(self):
        """
        Only require for Threading
        """
184
185
        # first init the component list within the workflow
        self.init_component_nameids()
Jerome Mariette's avatar
Jerome Mariette committed
186
187
188
189
190
191
192
193
        self.start_time = time.time()
        self.status = self.STATUS_STARTED
        self.end_time = None  
        # serialize the workflow before pre processing
        self._serialize()
        self.pre_process()
        # serialize the workflow before running
        self._serialize()
Jerome Mariette's avatar
Jerome Mariette committed
194
        try: 
195
            getattr(self, self.function)()
Jerome Mariette's avatar
Jerome Mariette committed
196
        except SystemExit, e: 
Jerome Mariette's avatar
Jerome Mariette committed
197
198
199
            self.status = self.STATUS_FAILED
            self.end_time = time.time()
            self._serialize()
Jerome Mariette's avatar
Jerome Mariette committed
200
            raise
Jerome Mariette's avatar
Jerome Mariette committed
201
202
203
        if len(self.components) > 0:
            self._execute_weaver()
        self._serialize()
Jerome Mariette's avatar
Jerome Mariette committed
204
205
        self.post_process()
        if self.status == self.STATUS_STARTED: self.status = self.STATUS_COMPLETED        
Jerome Mariette's avatar
Jerome Mariette committed
206
207
208
        self.end_time = time.time()
        self._serialize()
    
Jerome Mariette's avatar
Jerome Mariette committed
209
    def _extend_and_format_args(self, parameters, args):
Jerome Mariette's avatar
Jerome Mariette committed
210
211
        
        extended_args = {}
Jerome Mariette's avatar
Jerome Mariette committed
212
        for param in parameters:
Jerome Mariette's avatar
Jerome Mariette committed
213
214
215
216
217
218
            try: args[param.name] = args[param.name].encode('ascii','ignore')
            except: pass
            # if this parameter has been modified by the user
            if args.has_key(param.name):
                # if it's an append parameter, the result should be a list
                if param.action == "append":
Jerome Mariette's avatar
Jerome Mariette committed
219
220
221
222
                    if args[param.name]:
                        try: value = args[param.name].split(",") 
                        except: value = args[param.name]
                    else: value = []
Jerome Mariette's avatar
Jerome Mariette committed
223
224
225
226
227
228
229
                    extended_args[param.name] = value
                # if it's a date
                elif param.type == date:
                    if isinstance(args[param.name], str):
                        extended_args[param.name] = date(args[param.name])
                    else:
                        extended_args[param.name] = args[param.name]
230
231
                # if it's a boolean
                elif param.type == types.BooleanType:
Jerome Mariette's avatar
Jerome Mariette committed
232
                    extended_args[param.name] = args[param.name] in [True, 1, 'true', '1', 't', 'y', 'yes']
Jerome Mariette's avatar
Jerome Mariette committed
233
234
235
236
237
238
239
                else:
                    extended_args[param.name] = args[param.name]
            # otherwise use the default
            else:
                extended_args[param.name] = param.default
        return extended_args
    
Jerome Mariette's avatar
Jerome Mariette committed
240
241
242
243
    def _get_from_config(self):
        reader = ConfigParser()
        reader.read(self._get_property_path())
        parameters = []
Jerome Mariette's avatar
Jerome Mariette committed
244
245
        try:
            params = {}
Jerome Mariette's avatar
Jerome Mariette committed
246
            # first grab all parameters name
Jerome Mariette's avatar
Jerome Mariette committed
247
248
249
250
251
252
            for param in reader.items("parameters"):
                cvalue = reader.get("parameters", param[0])
                cparam = param[0].split(".")[0]
                ckey = param[0].split(".")[1]
                if not params.has_key(cparam):
                    params[cparam] = {ckey: cvalue}
Jerome Mariette's avatar
Jerome Mariette committed
253
                else:
Jerome Mariette's avatar
Jerome Mariette committed
254
255
                    params[cparam][ckey] = cvalue
            for param in params:
Jerome Mariette's avatar
Jerome Mariette committed
256
                oparam = Parameter(**params[param])
Jerome Mariette's avatar
Jerome Mariette committed
257
258
259
                parameters.append(oparam)
        except:
            pass
Jerome Mariette's avatar
Jerome Mariette committed
260
261
262
        # finally add the metadata parameter
        metadata = Parameter("metadata", "--metadata", "Which metadata should be linked to this workflow", action="append")
        parameters.append(metadata)
Jerome Mariette's avatar
Jerome Mariette committed
263
264
265
266
        return [reader.get("global", "name"),
                reader.get("global", "description"),
                parameters]
    
Jerome Mariette's avatar
Jerome Mariette committed
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
    def _update_status_from_log(self):
        # first update the status from weaver folders
        # TODO update self.end_time
        try:
            working_directory = os.path.join(self.directory, self.WORKING)
            make_states = []
            for wdir in os.listdir(working_directory):
                log_path = os.path.join(working_directory, wdir, self.MAKEFLOW_LOG_FILE_NAME)
                log = MakeflowLog(log_path)
                log.parse()
                make_states.append(log.state)
            if self.STATUS_ABORTED in make_states:
                self.status = self.STATUS_ABORTED
            elif self.STATUS_FAILED in make_states:
                self.status = self.STATUS_FAILED
            elif self.status != self.STATUS_COMPLETED:
                self.status = self.STATUS_STARTED
        except: pass
        self._serialize()

    def get_status(self):
        self._update_status_from_log()
        return self.status
    
    def get_component_status(self, component_nameid):
        status = {"time": 0.0,
                  "tasks": 0,
                  "waiting": 0,
                  "running": 0,
                  "failed":0,
                  "aborted": 0,
                  "completed": 0}
        try:
            log = MakeflowLog(self.component_nameids[component_nameid])
            log.parse()
            symbols = set(n.symbol for n in log.nodes if n.symbol)
            if not symbols: return None
            for n in log.nodes:
                if not n.symbol: continue
                if n.symbol == component_nameid:
                    status["tasks"] += 1
                    status["time"]  += n.elapsed_time
                    if n.state == Node.WAITING:
                        status["waiting"] += 1
                    elif n.state == Node.RUNNING:
                        status["running"] += 1
                    elif n.state == Node.FAILED:
                        status["failed"] += 1
                    elif n.state == Node.ABORTED:
                        status["aborted"] += 1
                    elif n.state == Node.COMPLETED:
                        status["completed"] += 1
        except: pass
        return status        
    
    def makeflow_pretty_print_node(self, dag, node):
        sys.stdout.write('{0:>10} {1} {2}\n'.format('NODE', node.id, node.symbol))
        
        for output_file in sorted(node.output_files):
            sys.stdout.write('{0:>10} {1:>10} {2}\n'.format('', 'OUTPUT', output_file))
    
        for input_file in sorted(node.input_files):
            sys.stdout.write('{0:>10} {1:>10} {2}\n'.format('', 'INPUT', input_file))
            
        sys.stdout.write('{0:>10} {1:>10} {2}\n'.format('', 'COMMAND', node.command))

    def _execute_weaver(self, engine_wrapper=None):
        # Add nest path and path to script to Python module path to allow
        # for importing modules outside of $PYTHONPATH
        make_directory, new_make = self._get_current_make()
        current_working_directory = os.path.join(os.path.join(self.directory, self.WORKING), make_directory)
        sys.path.insert(0, os.path.abspath(os.path.dirname(current_working_directory)))

        # Load built-ins
        self._import('abstraction', ABSTRACTIONS)
        self._import('dataset', DATASETS)
        self._import('function', FUNCTIONS)
        self._import('nest', NESTS)
        self._import('options', OPTIONS)
        self._import('stack', STACKS)
                
        # Execute nest
        with Nest(current_working_directory, wrapper=engine_wrapper, path=self.jflow_config_reader.get_makeflow_path()) as nest:
            with self.options:
                if new_make:
                    try:
                        for component in self.components:
                            nest.symbol = component.get_nameid()
355
                            nest.batch = component.batch_options
Jerome Mariette's avatar
Jerome Mariette committed
356
357
358
359
360
361
                            self.component_nameids[component.get_nameid()] = os.path.join(current_working_directory, self.MAKEFLOW_LOG_FILE_NAME)
                            component.execute()
                        # create the DAG
                        nest.compile()
                    except Exception as e:
                        self.status = self.STATUS_FAILED
Jerome Mariette's avatar
Jerome Mariette committed
362
                        self.end_time = time.time()
Jerome Mariette's avatar
Jerome Mariette committed
363
                        self._serialize()
Jerome Mariette's avatar
Jerome Mariette committed
364
                        raise
Jerome Mariette's avatar
Jerome Mariette committed
365
366
367
368
369
370
371
372
373
                self.components = []
                # Once a weaver script is compiled, serialize the workflow
                self._serialize()
                try:
                    nest.execute(self.engine_arguments, exit_on_failure=True)
                except:
                    self.status = self.STATUS_FAILED
                    self.end_time = time.time()
                    self._serialize()
Jerome Mariette's avatar
Jerome Mariette committed
374
                    raise
Jerome Mariette's avatar
Jerome Mariette committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395

    def _get_current_make(self):
        current_component, make_directory, new_make = [], None, False
        for component in self.components:
            current_component.append(component.get_nameid())
        for make in self.makes:
            if set(current_component) == set(self.makes[make]):
                make_directory = make
        # If the components in the queue have already been compiled
        if make_directory is None:
            make_directory = uuid.uuid4().hex[:10]
            self.makes[make_directory] = current_component
            new_make = True
        return [make_directory, new_make]
    
    def _serialize(self):
        self.dump_path = os.path.join(self.directory, self.DUMP_FILE_NAME)
        workflow_dump = open(self.dump_path, "wb")
        pickle.dump(self, workflow_dump)
        workflow_dump.close()

396
397
    def _component_is_duplicated(self, component_nameid):
        if component_nameid in self.component_nameids.keys():
Jerome Mariette's avatar
Jerome Mariette committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
            return True
        return False

    def _get_property_path(self):
        """ 
        Return(type:string):  the path to the workflow properties file, None if does not exist
        """
        property_file = os.path.join(os.path.dirname(inspect.getfile(self.__class__)), self.PROPERTIES_FILE_NAME)
        return property_file if os.path.isfile(property_file) else None

    def _import_components(self):
        pckge = {}
        # then import pipeline packages
        pipeline_dir = os.path.dirname(inspect.getfile(self.__class__))
        for importer, modname, ispkg in pkgutil.iter_modules([os.path.join(pipeline_dir, "components")], "workflows." + 
                                                             os.path.basename(pipeline_dir) + ".components."):
Jerome Mariette's avatar
Jerome Mariette committed
414
415
416
417
418
            try:
                m = __import__(modname)
                for class_name, obj in inspect.getmembers(sys.modules[modname], inspect.isclass):
                    if issubclass(obj, jflow.component.Component) and obj.__name__ != jflow.component.Component.__name__:
                        pckge[class_name] = modname
Jerome Mariette's avatar
Jerome Mariette committed
419
            except Exception as e:
Jerome Mariette's avatar
Jerome Mariette committed
420
                logging.getLogger("Workflow._import_components").debug("Component <{0}> cannot be loaded: {1}".format(modname, e))
Jerome Mariette's avatar
Jerome Mariette committed
421
422
423
        # finally import workflows shared packages
        workflows_dir = os.path.dirname(os.path.dirname(inspect.getfile(self.__class__)))
        for importer, modname, ispkg in pkgutil.iter_modules([os.path.join(workflows_dir, "components")], "workflows.components."):
Jerome Mariette's avatar
Jerome Mariette committed
424
425
426
427
428
            try:
                m = __import__(modname)
                for class_name, obj in inspect.getmembers(sys.modules[modname], inspect.isclass):
                    if issubclass(obj, jflow.component.Component) and obj.__name__ != jflow.component.Component.__name__:
                        pckge[class_name] = modname
Jerome Mariette's avatar
Jerome Mariette committed
429
430
            except Exception as e:
                logging.getLogger("Workflow._import_components").debug("Component <{0}> cannot be loaded: {1}".format(modname, e))
Jerome Mariette's avatar
Jerome Mariette committed
431
432
433
434
435
436
437
438
439
440
441
442
        return pckge

    def _import(self, module, symbols):
        """ Import ``symbols`` from ``module`` into global namespace. """
        # Import module
        m = 'weaver.{0}'.format(module)
        m = __import__(m, self.globals, self.globals, symbols, -1)

        # Import symbols from module into global namespace, which we store as
        # an attribute for later use (i.e. during compile)
        for symbol in symbols:
            self.globals[symbol] = getattr(m, symbol)