function.py 10.5 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
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
# Copyright (c) 2010- The University of Notre Dame.
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.

""" Weaver function module """

from weaver.compat  import callable, getfuncname
from weaver.data    import parse_input_list, parse_output_list
from weaver.logger  import D_FUNCTION, debug
from weaver.options import Options
from weaver.stack   import CurrentAbstraction, CurrentNest
from weaver.util    import find_executable, parse_string_list, type_str, WeaverError

import inspect
import itertools
import os
import sys


# Base Function class

class Function(object):
    """ This is the base Function class.

    A :class:`Function` provides the :meth:`command` method that specifies how
    to generate the command for the executable associated with the
    :class:`Function` instance.

    At a minimum, the user must specify the name of the `executable`.  For
    convenience, the function :func:`~weaver.util.find_executable` is used to
    locate the executable.

    **Positional Arguments:**

    - `executable`  -- Path or name of executable.

    **Keyword Arguments:**

    - `cmd_format`  -- String template used to generate command string.
    - `find_dirs`   -- Additional directories to search for executable.

    The `cmd_format` supports the following fields:

    - `{executable}`, `{EXE}` -- The executable file.
    - `{inputs}`, `{IN}`      -- The inputs files.
    - `{outputs}`, `{OUT}`    -- The output files.
    - `{arguments}`, `{ARG}`  -- The arguments.

    The default command string template is :data:`~weaver.Function.CMD_FORMAT`.
    """
    #: Default command string format template
    CMD_FORMAT = '{executable} {arguments} {inputs} > {outputs}'

    def __init__(self, executable, cmd_format=None, find_dirs=None,
        environment=None):
        self.cmd_format  = cmd_format or Function.CMD_FORMAT
        self.path        = find_executable(executable, find_dirs)
        self.environment = environment or dict()
        self.includes    = set([self.path])

        debug(D_FUNCTION, 'Created Function {0}({1}, {2})'.format(
            type_str(self), self.path, self.cmd_format))

    def __call__(self, inputs=None, outputs=None, arguments=None,
        includes=None, local=False, environment=None, collect=False):
        abstraction = CurrentAbstraction()
        nest        = CurrentNest()

        # Engine Functions define inputs and output member attributes
        try:
            inputs  = inputs  or self.inputs
            outputs = outputs or self.outputs
        except AttributeError:
            pass

        inputs   = parse_input_list(inputs)
        outputs  = parse_output_list(outputs, inputs)
        includes = parse_input_list(includes) + parse_input_list(self.includes)
        command  = self.command_format(inputs, outputs, arguments)
        options  = Options(environment=dict(self.environment), collect=inputs if collect else None)

        if local:
            options.local = True
Jerome Mariette's avatar
Jerome Mariette committed
84

Jerome Mariette's avatar
Jerome Mariette committed
85
86
        if environment:
            options.environment.update(environment)
Jerome Mariette's avatar
Jerome Mariette committed
87

88
89
        if nest.batch:
            options.batch = nest.batch
Jerome Mariette's avatar
Jerome Mariette committed
90

Jerome Mariette's avatar
Jerome Mariette committed
91
        nest.schedule(abstraction, self, command,
Jerome Mariette's avatar
Jerome Mariette committed
92
            list(inputs) + list(includes), outputs, options, nest.symbol)
Jerome Mariette's avatar
Jerome Mariette committed
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

        return outputs

    def command_format(self, inputs=None, outputs=None, arguments=None):
        """
        Returns command string by formatting function template with `inputs`
        and `outputs` arguments.

        This method requires the user to **explicitly** specify the `inputs`
        and `outputs` to be used in the command string.
        """
        inputs    = ' '.join(parse_string_list(inputs))
        outputs   = ' '.join(parse_string_list(outputs))
        arguments = ' '.join(parse_string_list(arguments))
        return self.cmd_format.format(
            executable  = self.path,
            EXE         = self.path,
            inputs      = inputs,
            IN          = inputs,
            outputs     = outputs,
            OUT         = outputs,
            arguments   = arguments,
            ARG         = arguments)

    def __str__(self):
        return self.cmd_format.format(
            executable  = self.path,
            EXE         = self.path,
            inputs      = '{inputs}',
            IN          = '{IN}',
            outputs     = '{outputs}',
            OUT         = '{OUT}',
            arguments   = '{arguments}',
            ARG         = '{ARG}')


# Scripting Function classes

class ScriptFunction(Function):
    """ This is the base scripting Function class.

    This class allows for users to define :class:`Function` objects by
    embedding scripts inside of their code.

    **Positional Arguments:**

        - `source`      -- Source code for the script.

    **Keyword Arguments:**

        - `executable`  -- Path or name to use for the script.
        - `cmd_format`  -- String template used to generate command string.

    If `executable` is ``None``, then a unique script name will be generated.
    """
    def __init__(self, source, executable=None, cmd_format=None):
        if executable is None:
            executable = next(CurrentNest().stash)

Jerome Mariette's avatar
Jerome Mariette committed
152
        with open(executable, 'w') as fs:
Jerome Mariette's avatar
Jerome Mariette committed
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
            fs.write(source)
        os.chmod(executable, 0o755)

        Function.__init__(self, executable, cmd_format)


class ShellFunction(ScriptFunction):
    """ This allows the user to embed a shell script.

    **Positional Arguments:**

        - `source`      -- Source code for the script.

    **Keyword Arguments:**

        - `shell`       -- Shell to be used to execute script.
        - `executable`  -- Path or name to use for the script.
        - `cmd_format`  -- String template used to generate command string.

    The supported values for `shell` are ``sh``, ``ksh``, ``bash``, ``csh``,
    and ``tcsh``.  The class assumes that the shells are located in ``/bin``.
    If you pass an absolute path instead of one of the mentioned `shell`
    values, then that will be used as the `shell` path and the basename of the
    specified `shell` path will be used as the script extension.
    """
    SHELL_TABLE = {
        'sh'    :   '/bin/sh',
        'ksh'   :   '/bin/ksh',
        'bash'  :   '/bin/bash',
        'csh'   :   '/bin/csh',
        'tcsh'  :   '/bin/tcsh',
    }
    SHELL_DEFAULT = 'sh'

    def __init__(self, source, shell=None, executable=None, cmd_format=None):
        if shell is None or not os.path.isabs(shell):
            if shell not in ShellFunction.SHELL_TABLE:
                shell = ShellFunction.SHELL_DEFAULT
            shell_path = ShellFunction.SHELL_TABLE[shell]
        else:
            shell_path = shell
            shell = os.path.basename(shell)
        source = '#!%s\n' % shell_path + source
        ScriptFunction.__init__(self, source, executable, cmd_format)


class PythonFunction(ScriptFunction):
    """ This allows the user to embed Python scripts as functions.

    **Positional Arguments:**

        - `function`    -- Name of Python function to materialize as a script.

    **Keyword Arguments:**

        - `executable`  -- Path or name to use for the script.
        - `cmd_format`  -- String template used to generate command string.
    """
    PYTHON_VERSION  = 'python{0}.{1}'.format(sys.version_info[0], sys.version_info[1])
    PYTHON_TEMPLATE = '''#!/usr/bin/env {0}
import {{0}}
{{1}}
{{2}}
if __name__ == '__main__':
    {{3}}(*sys.argv[1:])
'''.format(PYTHON_VERSION)

    def __init__(self, function, add_path=None, executable=None, cmd_format=None):
        # TODO: this doesn't work with Python3
        body = inspect.getsource(function)
        name = getfuncname(function)
        imports = ['os', 'sys']
        try:
            imports.extend(function.func_imports)
        except AttributeError:
            pass
Jerome Mariette's avatar
Jerome Mariette committed
229
        
Jerome Mariette's avatar
Jerome Mariette committed
230
231
232
        if add_path:
            add_path = add_path.extend(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
        else: 
Jerome Mariette's avatar
Jerome Mariette committed
233
234
            add_path = [os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'),
                        os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')]
Jerome Mariette's avatar
Jerome Mariette committed
235
236
237
        path = ""
        for apath in add_path:
            path += "sys.path.insert(0, '" + apath + "')\n"
Jerome Mariette's avatar
Jerome Mariette committed
238
        
Jerome Mariette's avatar
Jerome Mariette committed
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
        source = self.PYTHON_TEMPLATE.format(', '.join(imports), path, body, name)
        ScriptFunction.__init__(self, source, executable, cmd_format)


# Function argument parser

def parse_function(function, py_func_builder=PythonFunction, environment=None):
    """ Return a :class:`Function` object based on the input `function`.

    If `function` is already a :class:`Function`, then return it.  If it is a
    string, then parse it and automagically construct a :class:`Function`
    object.  Otherwise, raise a :class:`~weaver.util.WeaverError`.

    This means that a `function` must be one of the following:

    1. An existing :class:`Function`.
    2. A string template (ex. `{executable} {arguments} {inputs} {outputs}`)
    3. A real Python function that will be converted.

    .. note::

        The parser expects that the **first word** in the `function` string to
        refer to the name of the executable to be used for the
        :class:`Function`.
    """
    if isinstance(function, Function):
        return function

    if isinstance(function, str):
        if ' ' in function:
            flist = function.split(' ')
            return Function(flist[0],
                cmd_format  = ' '.join(['{executable}'] + flist[1:]),
                environment = environment)

        return Function(function, environment=environment)

    if callable(function):
        return py_func_builder(function)

    raise WeaverError(D_FUNCTION,
        'could not parse function argument: {0}'.format(function))

ParseFunction = parse_function


# Pipeline function

class Pipeline(Function):
    DEFAULT_SEPARATOR = '&&'

    def __init__(self, functions, separator=None):
        self.functions = [parse_function(f) for f in functions]
        Function.__init__(self, self.functions[0].path,
            cmd_format='Pipeline({0})'.format(map(str, self.functions)))
        self.includes  = set([f.path for f in self.functions])
        if separator is None:
            self.separator = Pipeline.DEFAULT_SEPARATOR
        else:
            self.separator = separator

    def command_format(self, inputs=None, outputs=None, arguments=None):
        divider = ' ' + self.separator + ' '
        return divider.join([f.command_format(inputs, outputs, arguments)
                             for f in self.functions])

    def __str__(self):
        return self.cmd_format

Jerome Mariette's avatar
Jerome Mariette committed
308
# vim: set sts=4 sw=4 ts=8 expandtab ft=python: