loop_execute.py 8.65 KB
Newer Older
1
2
3
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

Samuel GAIST's avatar
Samuel GAIST committed
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
###################################################################################
#                                                                                 #
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/               #
# Contact: beat.support@idiap.ch                                                  #
#                                                                                 #
# Redistribution and use in source and binary forms, with or without              #
# modification, are permitted provided that the following conditions are met:     #
#                                                                                 #
# 1. Redistributions of source code must retain the above copyright notice, this  #
# list of conditions and the following disclaimer.                                #
#                                                                                 #
# 2. Redistributions in binary form must reproduce the above copyright notice,    #
# this list of conditions and the following disclaimer in the documentation       #
# and/or other materials provided with the distribution.                          #
#                                                                                 #
# 3. Neither the name of the copyright holder nor the names of its contributors   #
# may be used to endorse or promote products derived from this software without   #
# specific prior written permission.                                              #
#                                                                                 #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND #
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED   #
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE          #
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE    #
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL      #
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR      #
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER      #
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,   #
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   #
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.            #
#                                                                                 #
###################################################################################
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


"""Executes a loop algorithm. (%(version)s)

usage:
  %(prog)s [--debug] <addr> <dir> <cache> [<db_addr>]
  %(prog)s (--help)
  %(prog)s (--version)


arguments:
  <addr>    Listen for incoming request on this address ('host:port')
  <dir>     Directory containing all configuration required to run the views
  <cache>   Path to the cache
  <db_addr> Address for databases-related I/O requests


options:
  -h, --help         Shows this help message and exit
  -V, --version      Shows program's version number and exit
  -d, --debug        Runs executor in debugging mode

"""

import logging

import os
import sys
import docopt

import zmq

67
68
69
from beat.backend.python.execution import LoopExecutor
from beat.backend.python.execution import LoopMessageHandler
from beat.backend.python.exceptions import UserError
70
71


72
# ----------------------------------------------------------
73
74
75
76
77


def process_traceback(tb, prefix):
    import traceback

78
    algorithms_prefix = os.path.join(prefix, "algorithms") + os.sep
79
80
81
82
83

    for first_line, line in enumerate(tb):
        if line[0].startswith(algorithms_prefix):
            break

84
85
    s = "".join(traceback.format_list(tb[first_line:]))
    s = s.replace(algorithms_prefix, "").strip()
86
87
88
89

    return s


90
# ----------------------------------------------------------
91
92
93
94
95
96
97
98


def main(arguments=None):

    # Parse the command-line arguments
    if arguments is None:
        arguments = sys.argv[1:]

99
100
    package = __name__.rsplit(".", 2)[0]
    version = package + " v" + __import__("pkg_resources").require(package)[0].version
101
102
103
104

    prog = os.path.basename(sys.argv[0])

    args = docopt.docopt(
105
        __doc__ % dict(prog=prog, version=version), argv=arguments, version=version
106
107
108
    )

    # Setup the logging system
109
110
111
112
    formatter = logging.Formatter(
        fmt="[%(asctime)s - loop_provider.py - " "%(name)s] %(levelname)s: %(message)s",
        datefmt="%d/%b/%Y %H:%M:%S",
    )
113
114
115
116

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

117
    root_logger = logging.getLogger("beat.backend.python")
118
119
    root_logger.addHandler(handler)

120
    if args["--debug"]:
121
122
123
124
125
126
127
        root_logger.setLevel(logging.DEBUG)
    else:
        root_logger.setLevel(logging.INFO)

    logger = logging.getLogger(__name__)

    # Create the message handler
128
    message_handler = LoopMessageHandler(args["<addr>"])
129
130
131

    context = None
    db_socket = None
132
    if args["<db_addr>"]:
133
134
        context = zmq.Context()
        db_socket = context.socket(zmq.PAIR)
135
136
        db_socket.connect(args["<db_addr>"])
        logger.debug("loop: zmq client connected to db `%s'", args["<db_addr>"])
137
138
139
140
141
142

    # If necessary, change to another user (with less privileges, but has access
    # to the databases)
    try:

        # Check the dir
143
144
        if not os.path.exists(args["<dir>"]):
            raise IOError("Running directory `%s' not found" % args["<dir>"])
145
146
147

        # Sets up the execution
        try:
148
149
150
151
152
153
            loop_executor = LoopExecutor(
                message_handler=message_handler,
                directory=args["<dir>"],
                cache_root=args["<cache>"],
                db_socket=db_socket,
            )
154
155
156
157
        except (MemoryError):
            raise
        except Exception as e:
            import traceback
158

159
160
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb = traceback.extract_tb(exc_traceback)
161
            s = process_traceback(tb, os.path.join(args["<dir>"], "prefix"))
162
163
164
165
166
167
168
169
170
171
            raise UserError("%s%s: %s" % (s, type(e).__name__, e))

        try:
            status = loop_executor.setup()
            if not status:
                raise UserError("Could not setup loop algorithm (returned False)")
        except (UserError, MemoryError):
            raise
        except Exception as e:
            import traceback
172

173
174
175
176
177
178
179
180
181
182
183
184
185
186
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb = traceback.extract_tb(exc_traceback)
            s = process_traceback(tb, loop_executor.prefix)
            raise UserError("%s%s: %s" % (s, type(e).__name__, e))

        # Prepare the algorithm
        try:
            status = loop_executor.prepare()
            if not status:
                raise UserError("Could not prepare loop algorithm (returned False)")
        except (UserError, MemoryError):
            raise
        except Exception as e:
            import traceback
187

188
189
190
191
192
193
194
195
196
197
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb = traceback.extract_tb(exc_traceback)
            s = process_traceback(tb, loop_executor.prefix)
            raise UserError("%s%s: %s" % (s, type(e).__name__, e))

        # Execute the code
        try:
            logger.debug("loop: Starting process")
            loop_executor.process()
            loop_executor.wait()
198
            loop_executor.close()
199
200
201
202
        except (MemoryError):
            raise
        except Exception as e:
            import traceback
203

204
205
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb = traceback.extract_tb(exc_traceback)
206
            s = process_traceback(tb, os.path.join(args["<dir>"], "prefix"))
207
208
209
            raise UserError("%s%s: %s" % (s, type(e).__name__, e))

    except UserError as e:
210
        message_handler.send_error(str(e), "usr")
211
212
213
        message_handler.destroy()
        return 1

214
    except MemoryError:
215
        # Say something meaningful to the user
216
217
218
219
220
221
222
        msg = (
            "The user process for this block ran out of memory. We "
            "suggest you optimise your code to reduce memory usage or, "
            "if this is not an option, choose an appropriate processing "
            "queue with enough memory."
        )
        message_handler.send_error(msg, "usr")
223
224
225
        message_handler.destroy()
        return 1

226
    except Exception:
227
        import traceback
228
229

        message_handler.send_error(traceback.format_exc(), "sys")
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
        message_handler.destroy()
        return 1

    if db_socket is not None:
        db_socket.setsockopt(zmq.LINGER, 0)
        db_socket.close()

        context.term()
        logger.debug("loop: 0MQ client finished")

    message_handler.destroy()

    return 0


245
if __name__ == "__main__":
246
    sys.exit(main())