algorithms.py 14.3 KB
Newer Older
André Anjos's avatar
André Anjos committed
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
35
###################################################################################
#                                                                                 #
# 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.            #
#                                                                                 #
###################################################################################

André Anjos's avatar
André Anjos committed
36

37
import click
André Anjos's avatar
André Anjos committed
38
import logging
39
40
41
import os
import simplejson as json

André Anjos's avatar
André Anjos committed
42
43

from beat.core import algorithm
44
from beat.core.execution import DockerExecutor
45
46
47
48
from beat.core.dock import Host
from beat.core import hash
from beat.backend.python.algorithm import Storage as AlgorithmStorage

49
from . import common
50
51
from . import commands

52
from .decorators import raise_on_error
53
54
from .click_helper import AliasedGroup

André Anjos's avatar
André Anjos committed
55

56
logger = logging.getLogger(__name__)
André Anjos's avatar
André Anjos committed
57

58
59

def pull_impl(webapi, prefix, names, force, indentation, format_cache, lib_cache):
Samuel GAIST's avatar
Samuel GAIST committed
60
    """Copies algorithms (and required libraries/dataformats) from the server.
André Anjos's avatar
André Anjos committed
61
62
63
64
65
66
67
68
69

  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    prefix (str): A string representing the root of the path in which the user
      objects are stored

André Anjos's avatar
André Anjos committed
70
71
72
73
74
    names (:py:class:`list`): A list of strings, each representing the unique
      relative path of the objects to retrieve or a list of usernames from
      which to retrieve objects. If the list is empty, then we pull all
      available objects of a given type. If no user is set, then pull all
      public objects of a given type.
André Anjos's avatar
André Anjos committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

    force (bool): If set to ``True``, then overwrites local changes with the
      remotely retrieved copies.

    indentation (int): The indentation level, useful if this function is called
      recursively while downloading different object types. This is normally
      set to ``0`` (zero).

    format_cache (dict): A dictionary containing all dataformats already
      downloaded.

    lib_cache (dict): A dictionary containing all libraries already
      downloaded.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

Samuel GAIST's avatar
Samuel GAIST committed
98
99
    from .dataformats import pull_impl as dataformats_pull
    from .libraries import pull_impl as libraries_pull
André Anjos's avatar
André Anjos committed
100

Samuel GAIST's avatar
Samuel GAIST committed
101
102
103
104
105
106
107
108
109
    status, names = common.pull(
        webapi,
        prefix,
        "algorithm",
        names,
        ["declaration", "code", "description"],
        force,
        indentation,
    )
André Anjos's avatar
André Anjos committed
110

Samuel GAIST's avatar
Samuel GAIST committed
111
112
    if status != 0:
        return status
André Anjos's avatar
André Anjos committed
113

Samuel GAIST's avatar
Samuel GAIST committed
114
115
116
    # see what dataformats one needs to pull
    if indentation == 0:
        indentation = 4
André Anjos's avatar
André Anjos committed
117

Samuel GAIST's avatar
Samuel GAIST committed
118
119
120
121
122
123
    dataformats = []
    libraries = []
    for name in names:
        obj = algorithm.Algorithm(prefix, name)
        dataformats.extend(obj.dataformats.keys())
        libraries.extend(obj.libraries.keys())
André Anjos's avatar
André Anjos committed
124

Samuel GAIST's avatar
Samuel GAIST committed
125
126
127
128
    # downloads any formats to which we depend on
    df_status = dataformats_pull(
        webapi, prefix, dataformats, force, indentation, format_cache
    )
André Anjos's avatar
André Anjos committed
129

Samuel GAIST's avatar
Samuel GAIST committed
130
131
132
    lib_status = libraries_pull(
        webapi, prefix, libraries, force, indentation, lib_cache
    )
André Anjos's avatar
André Anjos committed
133

Samuel GAIST's avatar
Samuel GAIST committed
134
    return status + df_status + lib_status
André Anjos's avatar
André Anjos committed
135

136
137

def print_examples():
Samuel GAIST's avatar
Samuel GAIST committed
138
139
    print(
        """
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
To feed data from a database to an algorithm:
=============================================

{
    "algorithm": "<username>/<algorithm>/<version>",
    "channel": "main",
    "inputs": {
        "<input_name>": {
            "database": "<database>/<version>",
            "protocol": "<protocol>",
            "set": "<set>",
            "output": "<output_name>",
            "channel": "main"
        }
    },
    "outputs": {
        "<output_name>": {
Philip ABBET's avatar
Philip ABBET committed
157
          "channel": "main"
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
        }
    },
    "parameters": {
      "<parameter_name>": <value>
    },
    "environment": {
        "name": "<environment_name>",
        "version": "<environment_version>"
    }
}


To feed data from a file in the cache:
======================================

{
    "algorithm": "<username>/<algorithm>/<version>",
    "channel": "main",
    "inputs": {
        "<input_name>": {
            "hash": "<hash>",
            "channel": "main"
        }
    },
    "outputs": {
        "<output_name>": {
Philip ABBET's avatar
Philip ABBET committed
184
          "channel": "main"
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
        }
    },
    "parameters": {
      "<parameter_name>": <value>
    },
    "environment": {
        "name": "<environment_name>",
        "version": "<environment_version>"
    }
}


To execute an analyzer:
=======================

{
    "algorithm": "<username>/<algorithm>/<version>",
    "channel": "main",
    "inputs": {
        "<input_name>": {
            "hash": "<hash>",
            "channel": "main"
        }
    },
    "parameters": {
      "<parameter_name>": <value>
    },
    "environment": {
        "name": "<environment_name>",
        "version": "<environment_version>"
    }
}
Samuel GAIST's avatar
Samuel GAIST committed
217
218
"""
    )
219
220


221
def execute_impl(prefix, cache, instructions_file):
Samuel GAIST's avatar
Samuel GAIST committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    try:
        # Load the JSON configuration
        if not os.path.exists(instructions_file):
            raise IOError("JSON instructions file `%s' not found" % instructions_file)

        with open(instructions_file, "r") as f:
            configuration = json.load(f)

        # Add missing configuration fields
        configuration["queue"] = "unused"
        configuration["nb_slots"] = 1

        if "parameters" not in configuration:
            configuration["parameters"] = {}

        for name, cfg in configuration["inputs"].items():
            cfg["endpoint"] = name
            suffix = ""
            if "database" in cfg:  # Connected to a database output
                cfg["hash"] = hash.hashDataset(
                    cfg["database"], cfg["protocol"], cfg["set"]
                )
                suffix = ".db"

            cfg["path"] = hash.toPath(cfg["hash"], suffix=suffix)

        algo = AlgorithmStorage(prefix, configuration["algorithm"])

        if "outputs" in configuration:  # Standard algorithm
            for name, cfg in configuration["outputs"].items():
                cfg["endpoint"] = name
                cfg["hash"] = hash.hashBlockOutput(
                    "block",
                    configuration["algorithm"],
                    algo.hash(),
                    configuration["parameters"],
                    configuration["environment"],
                    dict([(k, v["hash"]) for k, v in configuration["inputs"].items()]),
                    name,
                )
                cfg["path"] = hash.toPath(cfg["hash"], "")

        else:  # Analyzer
            configuration["result"] = {}
            configuration["result"]["hash"] = hash.hashAnalyzer(
                "block",
                configuration["algorithm"],
                algo.hash(),
                configuration["parameters"],
                configuration["environment"],
                dict([(k, v["hash"]) for k, v in configuration["inputs"].items()]),
            )
            configuration["result"]["path"] = hash.toPath(
                configuration["result"]["hash"], ""
            )

        # Sets up the execution
        dataformat_cache = {}
        database_cache = {}
        algorithm_cache = {}

        host = Host(raise_on_errors=False)

        executor = DockerExecutor(
            host,
            prefix,
            configuration,
            cache,
            dataformat_cache,
            database_cache,
            algorithm_cache,
        )

        if not executor.valid:
            logger.error(
                "Invalid configuration:\n  * %s" % "\n  * ".join(executor.errors)
            )
            return 1

        # Execute the algorithm
        with executor:
            result = executor.process()
            if result["status"] != 0:
                print("STDERR:")
                print(result["stderr"])

        # Display the results
        if "outputs" in configuration:  # Standard algorithm
            print("Outputs of the algorithms available at:")
            for name, cfg in configuration["outputs"].items():
                print("  - %s: %s" % (name, cfg["path"]))
        else:
            print(
                "Results of the analyzer available at: %s"
                % configuration["result"]["path"]
            )

    except Exception:
        import traceback

        logger.error(traceback.format_exc())
        return 1
324

Samuel GAIST's avatar
Samuel GAIST committed
325
    return 0
326
327


328
@click.group(cls=AliasedGroup)
329
330
331
332
@click.pass_context
def algorithms(ctx):
    """Configuration and manipulation of algorithms"""

333
    ctx.meta["asset_type"] = "algorithm"
Samuel GAIST's avatar
Samuel GAIST committed
334

335

336
algorithms.command(name="list")(commands.command("list"))
337
algorithms.command(name="path")(commands.command("path"))
338
algorithms.command(name="edit")(commands.command("edit"))
339
algorithms.command(name="check")(commands.command("check"))
340
algorithms.command(name="status")(commands.command("status"))
341
algorithms.command(name="create")(commands.command("create"))
André Anjos's avatar
André Anjos committed
342
343


344
@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
345
346
347
348
@click.argument("name", nargs=-1)
@click.option(
    "--force", help="Performs operation regardless of conflicts", is_flag=True
)
349
@click.pass_context
350
@raise_on_error
351
def pull(ctx, name, force):
Samuel GAIST's avatar
Samuel GAIST committed
352
    """Downloads the specified algorithms from the server
André Anjos's avatar
André Anjos committed
353

354
355
  Example:
    $ beat algorithms pull --force yyy
Samuel GAIST's avatar
Samuel GAIST committed
356
357
358
  """
    with common.make_webapi(ctx.meta["config"]) as webapi:
        return pull_impl(webapi, ctx.meta["config"].path, name, force, 0, {}, {})
André Anjos's avatar
André Anjos committed
359

360

361
@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
362
363
364
365
366
367
368
369
370
@click.argument("name", nargs=-1)
@click.option(
    "--force", help="Performs operation regardless of conflicts", is_flag=True
)
@click.option(
    "--dry-run",
    help="Doesn't really perform the task, just " "comments what would do",
    is_flag=True,
)
371
@click.pass_context
372
@raise_on_error
373
def push(ctx, name, force, dry_run):
Samuel GAIST's avatar
Samuel GAIST committed
374
    """Uploads algorithms to the server
375

376
377
  Example:
    $ beat algorithms push --dry-run yyy
Samuel GAIST's avatar
Samuel GAIST committed
378
379
380
381
382
383
384
385
386
387
388
389
390
  """
    with common.make_webapi(ctx.meta["config"]) as webapi:
        return common.push(
            webapi,
            ctx.meta["config"].path,
            "algorithm",
            name,
            ["name", "declaration", "code", "description"],
            {},
            force,
            dry_run,
            0,
        )
André Anjos's avatar
André Anjos committed
391

392
393

@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
394
@click.argument("name", nargs=1)
395
@click.pass_context
396
@raise_on_error
397
def diff(ctx, name):
Samuel GAIST's avatar
Samuel GAIST committed
398
    """Shows changes between the local algorithm and the remote version
399
400
401

  Example:
    $ beat algorithms diff xxx
Samuel GAIST's avatar
Samuel GAIST committed
402
403
404
405
406
407
408
409
410
  """
    with common.make_webapi(ctx.meta["config"]) as webapi:
        return common.diff(
            webapi,
            ctx.meta["config"].path,
            "algorithm",
            name,
            ["declaration", "code", "description"],
        )
411
412
413


@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
414
@click.argument("name", nargs=1)
415
@click.pass_context
416
@raise_on_error
417
def version(ctx, name):
Samuel GAIST's avatar
Samuel GAIST committed
418
    """Creates a new version of an existing algorithm
419
420
421

  Example:
    $ beat algorithms version xxx
Samuel GAIST's avatar
Samuel GAIST committed
422
423
  """
    return common.new_version(ctx.meta["config"].path, "algorithm", name)
424
425
426


@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
427
428
@click.argument("src", nargs=1)
@click.argument("dst", nargs=1)
429
@click.pass_context
430
@raise_on_error
431
def fork(ctx, src, dst):
Samuel GAIST's avatar
Samuel GAIST committed
432
    """Forks a local algorithm
433
434
435

  Example:
      $ beat algorithms fork xxx yyy
Samuel GAIST's avatar
Samuel GAIST committed
436
437
  """
    return common.fork(ctx.meta["config"].path, "algorithm", src, dst)
438
439
440


@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
441
442
443
444
@click.argument("name", nargs=-1)
@click.option(
    "--remote", help="Only acts on the remote copy of the algorithm", is_flag=True
)
445
@click.pass_context
446
@raise_on_error
447
def rm(ctx, name, remote):
Samuel GAIST's avatar
Samuel GAIST committed
448
    """Deletes a local algorithm (unless --remote is specified)
449
450
451

  Example:
      $ beat algorithms rm xxx
Samuel GAIST's avatar
Samuel GAIST committed
452
453
454
455
456
457
  """
    if remote:
        with common.make_webapi(ctx.meta["config"]) as webapi:
            return common.delete_remote(webapi, "algorithm", name)
    else:
        return common.delete_local(ctx.meta["config"].path, "algorithm", name)
458
459
460


@algorithms.command()
Samuel GAIST's avatar
Samuel GAIST committed
461
462
463
464
@click.argument("instructions", nargs=1)
@click.option(
    "--example", help="Display some example JSON instruction files", is_flag=True
)
465
@click.pass_context
466
@raise_on_error
467
def execute(ctx, instructions, example):
Samuel GAIST's avatar
Samuel GAIST committed
468
    """Execute an algorithm following instructions in a JSON file
469
470
471
472

  Example:
    $ beat algorithms execute <instructions>
    $ beat algorithms execute --examples
Samuel GAIST's avatar
Samuel GAIST committed
473
474
475
476
  """
    if example:
        print_examples()
        return 0
477

Samuel GAIST's avatar
Samuel GAIST committed
478
    return execute_impl(ctx.meta["config"].path, ctx.meta["config"].cache, instructions)