algorithms.py 14.5 KB
Newer Older
André Anjos's avatar
André Anjos 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
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.cmdline module of the BEAT platform.          #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform 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.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################

28
import click
André Anjos's avatar
André Anjos committed
29
import logging
30 31 32
import os
import simplejson as json

André Anjos's avatar
André Anjos committed
33 34

from beat.core import algorithm
35
from beat.core.execution import DockerExecutor
36 37 38 39
from beat.core.dock import Host
from beat.core import hash
from beat.backend.python.algorithm import Storage as AlgorithmStorage

40 41
from . import common
from .decorators import raise_on_error
42 43
from .click_helper import AliasedGroup

André Anjos's avatar
André Anjos committed
44

45
logger = logging.getLogger(__name__)
André Anjos's avatar
André Anjos committed
46

47 48

def pull_impl(webapi, prefix, names, force, indentation, format_cache, lib_cache):
André Anjos's avatar
André Anjos committed
49 50 51 52 53 54 55 56 57 58
  """Copies algorithms (and required libraries/dataformats) from the server.

  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
59 60 61 62 63
    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
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

    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).

  """

87 88
  from .dataformats import pull_impl as dataformats_pull
  from .libraries import pull_impl as libraries_pull
André Anjos's avatar
André Anjos committed
89 90

  status, names = common.pull(webapi, prefix, 'algorithm', names,
Philip ABBET's avatar
Philip ABBET committed
91
                              ['declaration', 'code', 'description'], force, indentation)
André Anjos's avatar
André Anjos committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

  if status != 0: return status

  # see what dataformats one needs to pull
  indent = indentation * ' '

  dataformats = []
  libraries = []
  for name in names:
    obj = algorithm.Algorithm(prefix, name)
    dataformats.extend(obj.dataformats.keys())
    libraries.extend(obj.libraries.keys())

  # downloads any formats to which we depend on
  df_status = dataformats_pull(webapi, prefix, dataformats, force,
Philip ABBET's avatar
Philip ABBET committed
107
                               indentation + 2, format_cache)
André Anjos's avatar
André Anjos committed
108 109

  lib_status = libraries_pull(webapi, prefix, libraries, force,
Philip ABBET's avatar
Philip ABBET committed
110
                              indentation + 2, lib_cache)
André Anjos's avatar
André Anjos committed
111 112 113 114

  return status + df_status + lib_status


115 116

def print_examples():
117
    print("""
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
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
135
          "channel": "main"
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
        }
    },
    "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
162
          "channel": "main"
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
        }
    },
    "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>"
    }
}
195
""")
196 197 198



199
def execute_impl(prefix, cache, instructions_file):
200 201 202 203 204 205 206 207 208 209 210 211
  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

212
    if 'parameters' not in configuration:
213 214 215 216
      configuration['parameters'] = {}

    for name, cfg in configuration['inputs'].items():
      cfg['endpoint'] = name
217
      suffix = ''
218
      if 'database' in cfg:   # Connected to a database output
219 220 221 222
        cfg['hash'] = hash.hashDataset(cfg['database'], cfg['protocol'], cfg['set'])
        suffix = '.db'

      cfg['path'] = hash.toPath(cfg['hash'], suffix=suffix)
223 224 225

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

226
    if 'outputs' in  configuration:   # Standard algorithm
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      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(
Philip ABBET's avatar
Philip ABBET committed
243
          'block',
244 245 246 247 248
              configuration['algorithm'],
              algo.hash(),
              configuration['parameters'],
              configuration['environment'],
              dict([(k, v['hash']) for k, v in configuration['inputs'].items()]),
Philip ABBET's avatar
Philip ABBET committed
249
      )
250 251 252 253 254 255 256
      configuration['result']['path'] = hash.toPath(configuration['result']['hash'], '')

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

Philip ABBET's avatar
Philip ABBET committed
257
    host = Host(raise_on_errors=False)
258

259 260
    executor = DockerExecutor(host, prefix, configuration, cache, dataformat_cache,
                              database_cache, algorithm_cache)
261 262 263 264 265 266 267

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

    # Execute the algorithm
    with executor:
Philip ABBET's avatar
Philip ABBET committed
268
      result = executor.process()
269
      if result['status'] != 0:
270 271
          print('STDERR:')
          print(result['stderr'])
272 273

    # Display the results
274
    if 'outputs' in configuration:   # Standard algorithm
275
      print('Outputs of the algorithms available at:')
276
      for name, cfg in configuration['outputs'].items():
277
        print('  - %s: %s' % (name, cfg['path']))
278
    else:
279
      print('Results of the analyzer available at: %s' % configuration['result']['path'])
280 281 282 283 284 285 286 287 288 289

  except Exception as e:
    import traceback
    logger.error(traceback.format_exc())
    return 1

  return 0



290
@click.group(cls=AliasedGroup)
291 292 293 294 295 296 297 298 299
@click.pass_context
def algorithms(ctx):
    """Configuration and manipulation of algorithms"""
    pass

@algorithms.command()
@click.option('--remote', help='Only acts on the remote copy of the algorithm',
              is_flag=True)
@click.pass_context
300
@raise_on_error
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
def list(ctx, remote):
  '''Lists all the algorithms available on the platform

  Example:
    $ beat algorithms list --remote
  '''
  if remote:
    with common.make_webapi(ctx.meta['config']) as webapi:
      return common.display_remote_list(webapi, 'algorithm')
  else:
    return common.display_local_list(ctx.meta['config'].path, 'algorithm')

@algorithms.command()
@click.argument('names', nargs=-1)
@click.pass_context
316
@raise_on_error
317 318
def path(ctx, names):
  '''Displays local path of algorithm files
André Anjos's avatar
André Anjos committed
319

320 321 322 323 324 325 326 327 328
  Example:
    $ beat algorithms path xxx
  '''
  return common.display_local_path(ctx.meta['config'].path, 'algorithm', names)


@algorithms.command()
@click.argument('name', nargs=1)
@click.pass_context
329
@raise_on_error
330 331
def edit(ctx, name):
  '''Edit local algorithm file
André Anjos's avatar
André Anjos committed
332

333 334 335 336 337 338
  Example:
    $ beat algorithms edit xxx
  '''
  return common.edit_local_file(ctx.meta['config'].path,
                                ctx.meta['config'].editor, 'algorithm',
                                name)
339

340

341
@algorithms.command()
342
@click.argument('name', nargs=-1)
343
@click.pass_context
344
@raise_on_error
345 346
def check(ctx, name):
  '''Checks a local algorithm for validity
André Anjos's avatar
André Anjos committed
347

348 349 350 351
  Example:
    $ beat algorithms check xxx
  '''
  return common.check(ctx.meta['config'].path, 'algorithm', name)
André Anjos's avatar
André Anjos committed
352 353 354



355
@algorithms.command()
356
@click.argument('name', nargs=-1)
357 358 359
@click.option('--force', help='Performs operation regardless of conflicts',
              is_flag=True)
@click.pass_context
360
@raise_on_error
361 362
def pull(ctx, name, force):
  '''Downloads the specified algorithms from the server
André Anjos's avatar
André Anjos committed
363

364 365 366 367 368
  Example:
    $ beat algorithms pull --force yyy
  '''
  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
369 370 371



372

373
@algorithms.command()
374
@click.argument('name', nargs=-1)
375 376 377 378 379
@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)
@click.pass_context
380
@raise_on_error
381 382
def push(ctx, name, force, dry_run):
  '''Uploads algorithms to the server
383

384 385 386 387 388 389 390
  Example:
    $ beat algorithms push --dry-run yyy
  '''
  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)
391

André Anjos's avatar
André Anjos committed
392

393 394 395 396

@algorithms.command()
@click.argument('name', nargs=1)
@click.pass_context
397
@raise_on_error
398 399 400 401 402 403 404 405 406 407 408 409 410 411
def diff(ctx, name):
  '''Shows changes between the local algorithm and the remote version

  Example:
    $ beat algorithms diff xxx
  '''
  with common.make_webapi(ctx.meta['config']) as webapi:
    return common.diff(webapi, ctx.meta['config'].path, 'algorithm',
                       name, ['declaration', 'code', 'description'])



@algorithms.command()
@click.pass_context
412
@raise_on_error
413 414 415 416 417 418 419 420 421 422 423 424
def status(ctx):
  '''Shows (editing) status for all available algorithms

  Example:
    $ beat algorithms status
  '''
  with common.make_webapi(ctx.meta['config']) as webapi:
    return common.status(webapi, ctx.meta['config'].path, 'algorithm')[0]



@algorithms.command()
425
@click.argument('name', nargs=-1)
426
@click.pass_context
427
@raise_on_error
428 429 430 431 432 433
def create(ctx, name):
  '''Creates a new local algorithm

  Example:
    $ beat algorithms create xxx
  '''
434
  return common.create(ctx.meta['config'].path, 'algorithm', name)
435 436 437 438 439 440



@algorithms.command()
@click.argument('name', nargs=1)
@click.pass_context
441
@raise_on_error
442 443 444 445 446 447 448 449 450 451 452 453 454 455
def version(ctx, name):
  '''Creates a new version of an existing algorithm

  Example:
    $ beat algorithms version xxx
  '''
  return common.new_version(ctx.meta['config'].path, 'algorithm', name)



@algorithms.command()
@click.argument('src', nargs=1)
@click.argument('dst', nargs=1)
@click.pass_context
456
@raise_on_error
457 458 459 460 461 462 463 464 465 466 467
def fork(ctx, src, dst):
  '''Forks a local algorithm

  Example:
      $ beat algorithms fork xxx yyy
  '''
  return common.fork(ctx.meta['config'].path, 'algorithm', src, dst)



@algorithms.command()
468
@click.argument('name', nargs=-1)
469 470 471
@click.option('--remote', help='Only acts on the remote copy of the algorithm',
              is_flag=True)
@click.pass_context
472
@raise_on_error
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
def rm(ctx, name, remote):
  '''Deletes a local algorithm (unless --remote is specified)

  Example:
      $ beat algorithms rm xxx
  '''
  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)



@algorithms.command()
488
@click.argument('instructions', nargs=1)
489 490 491
@click.option('--example', help='Display some example JSON instruction files',
              is_flag=True)
@click.pass_context
492
@raise_on_error
493 494 495 496 497 498 499 500 501 502 503
def execute(ctx, instructions, example):
  '''Execute an algorithm following instructions in a JSON file

  Example:
    $ beat algorithms execute <instructions>
    $ beat algorithms execute --examples
  '''
  if example:
    print_examples()
    return 0

504 505
  return execute_impl(ctx.meta['config'].path, ctx.meta['config'].cache,
                      instructions)