workflows_manager.py 9.11 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
#
# 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 pkgutil
import workflows
import inspect
import jflow
import sys
import imp
import os
import pickle
Jerome Mariette's avatar
Jerome Mariette committed
26
import threading
Jerome Mariette's avatar
Jerome Mariette committed
27
import tempfile
Jerome Mariette's avatar
Jerome Mariette committed
28
29
30
31

import jflow.utils as utils
from jflow.config_reader import JFlowConfigReader

Jerome Mariette's avatar
Jerome Mariette committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from weaver.function import PythonFunction
from weaver.nest import Nest
from weaver.options import Options


def run_workflow_wrapper(workflow_serial_path):
    import pickle
    # load the workflow object
    workflow_dump = open(workflow_serial_path, "rb")
    workflow = pickle.load(workflow_dump)
    workflow_dump.close()
    # and start it
    workflow.start()

Jerome Mariette's avatar
Jerome Mariette committed
46
47
48
49
50
51
52
class WorkflowsManager(object):
    """
    """
    
    IDS_FILE_NAME = "jflowIDs.txt"
    WF_DIRECTORY_PREFIX = "wf"
    
Jerome Mariette's avatar
Jerome Mariette committed
53
54
    lock_ids_file = threading.Lock()
    
Jerome Mariette's avatar
Jerome Mariette committed
55
56
57
58
    def __init__(self):
        """ 
        """
        self.config_reader = JFlowConfigReader()
Jerome Mariette's avatar
Jerome Mariette committed
59
60
61
62
63
64
65
        self.options = Options()
        # 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        if not os.path.isdir(self.get_output_directory()):
            os.makedirs(self.get_output_directory(), 0751)
        self.ids_file = os.path.join(self.get_output_directory(), self.IDS_FILE_NAME)
    
    def get_available_workflows(self):
        wf_instances = []
        # Load all modules within the workflow module
        for importer, modname, ispkg in pkgutil.iter_modules(workflows.__path__, workflows.__name__ + "."):
            __import__(modname)
            # Search for Workflow classes
            for class_name, obj in inspect.getmembers(sys.modules[modname], inspect.isclass):
                if issubclass(obj, jflow.workflow.Workflow) and obj.__name__ != jflow.workflow.Workflow.__name__:
                    # try to build the workflow
                    try: wf_instances.append(obj())
                    except: pass
        return wf_instances
    
    def rerun_workflow(self, workflow_id):
        workflow = self.get_workflow(workflow_id)
Jerome Mariette's avatar
Jerome Mariette committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
        if self.config_reader.submit_master_job():
            workflow_dump_path = self.get_temporary_file(".dump")
            workflow_dump = open(workflow_dump_path, "wb")
            pickle.dump(workflow, workflow_dump)
            workflow_dump.close()
            # Execute nest
            with Nest(self.get_temporary_directory(), path=self.config_reader.get_makeflow_path()) as nest:
                with self.options:
                    rw = PythonFunction(run_workflow_wrapper, cmd_format="{EXE} {IN} > {OUT}")
                    rw(inputs=workflow_dump_path, outputs=self.get_temporary_file(".stdout"))
                    try:
                        nest.compile()
                        nest.execute(self.engine_arguments, exit_on_failure=True)
                    except:
                        raise
        else:
            workflow.start()
        return workflow

    def run_workflow(self, workflow_class, args):   
Jerome Mariette's avatar
Jerome Mariette committed
105
106
107
108
109
110
        # Load all modules within the workflow module
        for importer, modname, ispkg in pkgutil.iter_modules(workflows.__path__, workflows.__name__ + "."):
            __import__(modname)
            # Search for Workflow classes
            for class_name, obj in inspect.getmembers(sys.modules[modname], inspect.isclass):
                if class_name == workflow_class: workflow = obj(args, id=self.get_next_id())
Jerome Mariette's avatar
Jerome Mariette committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
        if self.config_reader.submit_master_job():
            workflow_dump_path = self.get_temporary_file(".dump")
            workflow_dump = open(workflow_dump_path, "wb")
            pickle.dump(workflow, workflow_dump)
            workflow_dump.close()
            # Execute nest
            with Nest(self.get_temporary_directory(), path=self.config_reader.get_makeflow_path()) as nest:
                with self.options:
                    rw = PythonFunction(run_workflow_wrapper, cmd_format="{EXE} {IN} > {OUT}")
                    rw(inputs=workflow_dump_path, outputs=self.get_temporary_file(".stdout"))
                    try:
                        nest.compile()
                        nest.execute(self.engine_arguments, exit_on_failure=True)
                    except:
                        raise
        else:
            workflow.start()
Jerome Mariette's avatar
Jerome Mariette committed
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
        return workflow
        
    def get_output_directory(self):
        return self.config_reader.get_work_directory()
    
    def get_workflows(self):
        from jflow.workflow import Workflow
        workflows = []
        for wf_name in os.listdir(self.get_output_directory()):
            wf_name_path = os.path.join(self.get_output_directory(), wf_name)
            # If it's a workflow directory
            if os.path.isdir(wf_name_path):
                for wf in os.listdir(wf_name_path):
                    wf_path = os.path.join(wf_name_path, wf)
                    workflow_dump_path = os.path.join(wf_path, Workflow.DUMP_FILE_NAME)
                    try:
                        workflow_dump = open(workflow_dump_path, "rb")
                        workflows.append(pickle.load(workflow_dump))
                        workflow_dump.close()
                    except: pass
        return workflows

    def get_workflow_by_class(self, workflow_class):
        # Load all modules within the workflow module
        for importer, modname, ispkg in pkgutil.iter_modules(workflows.__path__, workflows.__name__ + "."):
            __import__(modname)
            # Search for Workflow classes
            for class_name, obj in inspect.getmembers(sys.modules[modname], inspect.isclass):
                if class_name == workflow_class:
                    return obj()
        return None
    
    def get_workflow(self, workflow_id):
        from jflow.workflow import Workflow
        search_directory = self.WF_DIRECTORY_PREFIX + utils.get_nb_string(workflow_id)
        workflow_dump_path = None
        for wf_name in os.listdir(self.get_output_directory()):
            wf_name_path = os.path.join(self.get_output_directory(), wf_name)
            # If it's a workflow directory
            if os.path.isdir(wf_name_path):
                for wf in os.listdir(wf_name_path):
                    wf_path = os.path.join(wf_name_path, wf)
                    if wf == search_directory:
                        if os.path.isfile(os.path.join(wf_path, Workflow.DUMP_FILE_NAME)):
                            workflow_dump_path = os.path.join(wf_path, Workflow.DUMP_FILE_NAME)
                        break
        if workflow_dump_path:
            workflow_dump = open(workflow_dump_path, "rb")
            workflow = pickle.load(workflow_dump)
            workflow_dump.close()
        else:
            raise ValueError("Workflow with id " + str(workflow_id) + " cannot be retrived!")
        return workflow

    def get_workflow_directory(self, wname, wid):
        return os.path.join(os.path.join(self.config_reader.get_work_directory(), wname), 
                                         self.WF_DIRECTORY_PREFIX + utils.get_nb_string(wid))
    
    def get_next_id(self):
Jerome Mariette's avatar
Jerome Mariette committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        WorkflowsManager.lock_ids_file.acquire()
        cid = 1
        try:
            if os.path.isfile(self.ids_file):
                ifh = open(self.ids_file)
                cid = int(ifh.readline().strip())
                ifh.close()
                ifh = open(self.ids_file, "w")
                ifh.write(str(cid+1))
                ifh.close()
                return cid+1
            else:
                ifh = open(self.ids_file, "w")
                ifh.write("1")
                ifh.close()
        finally:
            WorkflowsManager.lock_ids_file.release()
        return cid
Jerome Mariette's avatar
Jerome Mariette committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    
    def get_temporary_file(self, suffix=".txt"):
        # first check if tmp directory exists
        if not os.path.isdir(self.config_reader.get_tmp_directory()):
            os.makedirs(self.config_reader.get_tmp_directory(), 0751)
        tempfile_name = os.path.basename(tempfile.NamedTemporaryFile(suffix=suffix).name)
        return os.path.join(self.config_reader.get_tmp_directory(), tempfile_name)
    
    def get_temporary_directory(self):
        # first check if tmp directory exists
        if not os.path.isdir(self.config_reader.get_tmp_directory()):
            os.makedirs(self.config_reader.get_tmp_directory(), 0751)
        tempdir_name = os.path.basename(tempfile.NamedTemporaryFile().name)
        tempdir = os.path.join(self.config_reader.get_tmp_directory(), tempdir_name)
        os.makedirs(tempdir, 0751)
        return tempdir
Jerome Mariette's avatar
Jerome Mariette committed
221