loop_execute.py 9.84 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


"""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
64
65
import simplejson as json
import subprocess  # nosec
66
67
68

import zmq

69
70
71
from beat.backend.python.execution import LoopExecutor
from beat.backend.python.execution import LoopMessageHandler
from beat.backend.python.exceptions import UserError
72
73


74
# ----------------------------------------------------------
75
76
77
78
79


def process_traceback(tb, prefix):
    import traceback

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

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

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

    return s


92
# ----------------------------------------------------------
93
94
95
96
97
98
99
100


def main(arguments=None):

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

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

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

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

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

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

119
    root_logger = logging.getLogger("beat.backend.python")
120
121
    root_logger.addHandler(handler)

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

    logger = logging.getLogger(__name__)

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

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

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

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
    # Check the dir
    if not os.path.exists(args["<dir>"]):
        raise IOError("Running directory `%s' not found" % args["<dir>"])

    # Load the configuration
    with open(os.path.join(args["<dir>"], "configuration.json"), "r") as f:
        cfg = json.load(f)

    user_id = cfg["uid"]

    # Create a new user with less privileges (if necessary)
    if os.getuid() != user_id:
        retcode = subprocess.call(  # nosec
            [
                "adduser",
                "--uid",
                str(user_id),
                "--no-create-home",
                "--disabled-password",
                "--disabled-login",
                "--gecos",
                '""',
                "-q",
                "beat-nobody",
            ]
        )
        if retcode != 0:
            msg = "Failed to create a user with the UID {}".format(user_id)
            message_handler.send_error(msg, "sys")
            message_handler.destroy()
            return 1

        # Change to the user with less privileges
        try:
            os.setgid(user_id)
            os.setuid(user_id)
        except Exception as e:
            msg = "Failed to change to user id {}: {}".format(cfg["uid"], e)
            message_handler.send_error(msg, "sys")
            message_handler.destroy()
            return 1
184

185
    try:
186
187
        # Sets up the execution
        try:
188
189
190
191
192
193
            loop_executor = LoopExecutor(
                message_handler=message_handler,
                directory=args["<dir>"],
                cache_root=args["<cache>"],
                db_socket=db_socket,
            )
194
195
196
197
        except (MemoryError):
            raise
        except Exception as e:
            import traceback
198

199
200
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb = traceback.extract_tb(exc_traceback)
201
            s = process_traceback(tb, os.path.join(args["<dir>"], "prefix"))
202
203
204
205
206
207
208
209
210
211
            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
212

213
214
215
216
217
218
219
220
221
222
223
224
225
226
            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
227

228
229
230
231
232
233
234
235
236
237
            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()
238
            loop_executor.close()
239
240
241
242
        except (MemoryError):
            raise
        except Exception as e:
            import traceback
243

244
245
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb = traceback.extract_tb(exc_traceback)
246
            s = process_traceback(tb, os.path.join(args["<dir>"], "prefix"))
247
248
249
            raise UserError("%s%s: %s" % (s, type(e).__name__, e))

    except UserError as e:
250
        message_handler.send_error(str(e), "usr")
251
252
253
        message_handler.destroy()
        return 1

254
    except MemoryError:
255
        # Say something meaningful to the user
256
257
258
259
260
261
262
        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")
263
264
265
        message_handler.destroy()
        return 1

266
    except Exception:
267
        import traceback
268
269

        message_handler.send_error(traceback.format_exc(), "sys")
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        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


285
if __name__ == "__main__":
286
    sys.exit(main())