databases.py 20.4 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
28
29
30
31
32
33
34
35
36
#!/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/.           #
#                                                                             #
###############################################################################


"""Usage:
  %(prog)s databases list [--remote]
  %(prog)s databases check [<name>]...
  %(prog)s databases pull [--force] [<name>]...
  %(prog)s databases push [--force] [--dry-run] [<name>]...
  %(prog)s databases diff <name>
  %(prog)s databases status
  %(prog)s databases version <name>
37
  %(prog)s databases index [--list | --delete | --checksum] [--uid=<uid>] [--db-root=<path>] [<name>]...
André Anjos's avatar
André Anjos committed
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
84
85
86
87
88
89
90
91
92
93
  %(prog)s databases view [--exclude=<output>] <set_name>
  %(prog)s databases --help


Arguments:
  <name>           Database name formated as "<database>/<version>"
  <set_name>       Set formatted as "<database>/<version>/<protocol>/<set>"


Commands:
  list      Lists all the databases available on the platform
  check     Checks a local database for validity
  pull      Downloads the specified databases from the server
  push      Uploads databases to the server (must provide a valid admin token)
  diff      Shows changes between the local database and the remote version
  status    Shows (editing) status for all available databases
  version   Creates a new version of an existing database
  index     Indexes all outputs (of all sets) of a database.
  view      View the data of the specified dataset.


Options:
  --help              Display this screen
  --remote            Only acts on the remote copy of the database
  --exclude=<output>  When viewing, excludes this output
  --list              List index files matching output if they exist
  --delete            Delete index files matching output if they exist (also,
                      recursively deletes empty directories)
  --checksum          Checksums index files


Examples:

  To list all existing databases on your local prefix:

    $ %(prog)s db list

  To view the contents of a specific set

    $ %(prog)s db view simple/1/protocol/set

  To index the contents of a database

    $ %(prog)s db index simple/1

  To index the contents of a protocol on a database

    $ %(prog)s db index simple/1/double

  To index the contents of a set in a protocol on a database

    $ %(prog)s db index simple/1/double/double
"""

import os
import glob
94
95
import zmq.green as zmq

André Anjos's avatar
André Anjos committed
96
97
98
99
100
101
102
103
104
105
import logging
logger = logging.getLogger()

import simplejson

from beat.core.hash import hash, toPath, hashFileContents
from beat.core.utils import NumpyJSONEncoder
from beat.core.database import Database
from beat.core.dataformat import DataFormat
from beat.core.data import load_data_index
106
107
108
from beat.core import dock
from beat.core import inputs
from beat.core import utils
André Anjos's avatar
André Anjos committed
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

from . import common


def pull(webapi, prefix, names, force, indentation, format_cache):
  """Copies databases (and required 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

    names (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.

    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.


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

  """

  from .dataformats import pull as dataformats_pull

  status, names = common.pull(webapi, prefix, 'database', names,
Philip ABBET's avatar
Philip ABBET committed
152
                              ['declaration', 'code', 'description'], force, indentation)
André Anjos's avatar
André Anjos committed
153
154
155
156
157
158
159
160
161
162
163

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

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

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

  return status + df_status


169
def index_output(configuration, names, ls, delete, checksum, uid, db_root):
André Anjos's avatar
André Anjos committed
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

  names = common.make_up_local_list(configuration.path, 'database', names)

  retcode = 0

  for database_name in names:

    parts = database_name.split('/')

    if len(parts) == 2:
      db_name         = os.path.join(*parts[:2])
      protocol_filter = None
      set_filter      = None
      if ls:
        logger.info("Listing database %s indexes...", database_name)
      elif delete:
        logger.info("Deleting database %s indexes...", database_name)
      elif checksum:
        logger.info("Checksumming database %s indexes...", database_name)
      else:
        logger.info("Indexing database %s...", database_name)

    elif len(parts) == 3:
      db_name         = os.path.join(*parts[:2])
      protocol_filter = parts[2]
      set_filter      = None
      if ls:
        logger.info("Listing database protocol %s indexes...", database_name)
      elif delete:
        logger.info("Deleting database protocol %s indexes...", database_name)
      elif checksum:
        logger.info("Checksumming database protocol %s indexes...",
Philip ABBET's avatar
Philip ABBET committed
202
                    database_name)
André Anjos's avatar
André Anjos committed
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
      else:
        logger.info("Indexing database protocol %s...", database_name)

    elif len(parts) == 4:
      db_name         = os.path.join(*parts[:2])
      protocol_filter = parts[2]
      set_filter      = parts[3]
      if ls:
        logger.info("Listing database set %s indexes...", database_name)
      elif delete:
        logger.info("Deleting database set %s indexes...", database_name)
      elif checksum:
        logger.info("Checksumming database set %s indexes...", database_name)
      else:
        logger.info("Indexing database set %s...", database_name)

    else:
      logger.error("Database specification should have the format " \
Philip ABBET's avatar
Philip ABBET committed
221
222
                   "`<database>/<version>/[<protocol>/[<set>]]', the value you " \
                   "passed (%s) is not valid", (dataset_name))
André Anjos's avatar
André Anjos committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
      retcode += 1
      continue

    dataformat_cache = {}
    database = Database(configuration.path, db_name, dataformat_cache)
    if not database.valid:
      logger.error("Failed to load the database `%s':", db_name)
      for e in database.errors: logger.error('  * %s', e)
      retcode += 1
      continue

    protocols = database.protocol_names

    if protocol_filter is not None:

      if protocol_filter not in protocols:
        logger.error("The database `%s' does not have the protocol `%s' - " \
Philip ABBET's avatar
Philip ABBET committed
240
241
                     "choose one of `%s'", db_name, protocol_filter,
                     ', '.join(protocols))
André Anjos's avatar
André Anjos committed
242
243
244
245
246
        retcode += 1
        continue

      protocols = [protocol_filter]

247
248
    if not (ls or delete or checksum): #we're indexing
      host = dock.Host()
249
      host.setup(raise_on_errors=False)
250

André Anjos's avatar
André Anjos committed
251
252
253
254
255
256
257
    for protocol_name in protocols:

      sets = database.set_names(protocol_name)

      if set_filter is not None:
        if set_filter not in sets:
          logger.error("The database/protocol `%s/%s' does not have the " \
Philip ABBET's avatar
Philip ABBET committed
258
259
                       "set `%s' - choose one of `%s'", db_name, protocol_name,
                       set_filter, ', '.join(sets))
André Anjos's avatar
André Anjos committed
260
261
262
263
264
265
266
          retcode += 1
          continue

        sets = [z for z in sets if z == set_filter]

      for set_name in sets:

267
        db_set = database.set(protocol_name, set_name)
268

269
270
271
272
273
274
        if not (ls or delete or checksum): #we're indexing
          zmq_context = zmq.Context()
          db_socket = zmq_context.socket(zmq.PAIR)
          db_address = 'tcp://' + host.ip
          port = db_socket.bind_to_random_port(db_address)
          db_address += ':%d' % port
275

276
          input_list = inputs.InputList()
277

278
          input_group = inputs.InputGroup(set_name, restricted_access=False)
279
          input_list.add(input_group)
280

281
          db_configuration = {
Philip ABBET's avatar
Philip ABBET committed
282
              'inputs': {},
283
284
            'channel': set_name,
          }
André Anjos's avatar
André Anjos committed
285

286
287
          if uid is not None:
            db_configuration['datasets_uid'] = uid
288

289
290
          if db_root is not None:
            db_configuration['datasets_root_path'] = db_root
291

292
293
294
          for output_name, dataformat_name in db_set['outputs'].items():
            input = inputs.RemoteInput(output_name, database.dataformats[dataformat_name], db_socket)
            input_group.add(input)
295

296
            db_configuration['inputs'][output_name] = dict(
Philip ABBET's avatar
Philip ABBET committed
297
                database=db_name,
298
299
300
301
302
              protocol=protocol_name,
              set=set_name,
              output=output_name,
              channel=set_name
            )
303

304
          db_tempdir = utils.temporary_directory()
305

306
307
          with open(os.path.join(db_tempdir, 'configuration.json'), 'wb') as f:
            simplejson.dump(db_configuration, f, indent=4)
308

309
310
311
          tmp_prefix = os.path.join(db_tempdir, 'prefix')
          if not os.path.exists(tmp_prefix):
            os.makedirs(tmp_prefix)
312

313
          database.export(tmp_prefix)
314

315
316
          if db_root is None:
            json_path = os.path.join(tmp_prefix, 'databases', db_name + '.json')
317

318
319
            with open(json_path, 'r') as f:
              db_data = simplejson.load(f)
320

321
322
            database_path = db_data['root_folder']
            db_data['root_folder'] = os.path.join('/databases', db_name)
323

324
325
326
327
328
329
330
            with open(json_path, 'w') as f:
              simplejson.dump(db_data, f, indent=4)

          try:
            db_envkey = host.db2docker([db_name])
          except:
            raise RuntimeError("No environment found for the database `%s' " \
Philip ABBET's avatar
Philip ABBET committed
331
332
333
                               "- available environments are %s" % (
                                   db_name,
                                   ", ".join(host.db_environments.keys())))
334
335
336
337
338
339
340
341

          tmp_dir = os.path.join('/tmp', os.path.basename(db_tempdir))
          db_cmd = ['databases_provider', db_address, tmp_dir]

          volumes = {}

          if db_root is None:
            volumes[database_path] = {
Philip ABBET's avatar
Philip ABBET committed
342
                'bind': os.path.join('/databases', db_name),
343
344
345
346
              'mode': 'ro',
            }
          else:
            volumes[db_root] = {
Philip ABBET's avatar
Philip ABBET committed
347
                'bind': db_root,
348
349
350
351
352
              'mode': 'ro',
            }

          # Note: we only support one databases image loaded at the same time
          db_process = dock.Popen(
Philip ABBET's avatar
Philip ABBET committed
353
              host,
354
355
356
357
358
            db_envkey,
            command=db_cmd,
            tmp_archive=db_tempdir,
            volumes=volumes
          )
André Anjos's avatar
André Anjos committed
359
360
361
362

        index_filenames = []
        previous_data_indices = []

363
364
        for output_name in db_set['outputs'].keys():
          index_hash = database.hash_output(protocol_name, set_name, output_name)
André Anjos's avatar
André Anjos committed
365
          index_filename = os.path.join(configuration.cache,
Philip ABBET's avatar
Philip ABBET committed
366
                                        toPath(index_hash, '.index'))
André Anjos's avatar
André Anjos committed
367
368
369
370
371
372
373
374
375
376
377
378

          if ls:
            basename = os.path.splitext(index_filename)[0]
            for g in glob.glob(basename + '.*'): logger.info(g)

          elif delete:

            basename = os.path.splitext(index_filename)[0]
            for g in glob.glob(basename + '.*'):
              logger.info("removing `%s'...", g)
              os.unlink(g)
            common.recursive_rmdir_if_empty(os.path.dirname(basename),
Philip ABBET's avatar
Philip ABBET committed
379
                                            configuration.cache)
André Anjos's avatar
André Anjos committed
380
381

          elif checksum:
382
383
            assert load_data_index(configuration.cache, toPath(index_hash, '.index'))
            logger.info("index for `%s' can be loaded and checksumed",
Philip ABBET's avatar
Philip ABBET committed
384
                        index_filename)
André Anjos's avatar
André Anjos committed
385
386
387
388
389
390
391

          else:

            index_filenames.append(index_filename)
            previous_data_indices.append(None)

            logger.info("Indexing database `%s', protocol `%s', set `%s', " \
Philip ABBET's avatar
Philip ABBET committed
392
393
                        "output `%s' -> `%s'", db_name, protocol_name, set_name,
                        output_name, index_filename)
André Anjos's avatar
André Anjos committed
394
395
396

            if os.path.exists(index_filename):
              logger.extra("Overwriting existing index file `%s'",
Philip ABBET's avatar
Philip ABBET committed
397
                           index_filename)
André Anjos's avatar
André Anjos committed
398
399
400
401
402
403
404
405
406
407
              os.remove(index_filename)

            index_dir = os.path.dirname(index_filename)
            if not os.path.exists(index_dir):
              logger.extra("Creating directory `%s'", index_dir)
              os.makedirs(index_dir)

            # Create empty lock file to indicate that this cache file *must*
            # not be cleaned
            lock_filename = os.path.join(configuration.cache,
Philip ABBET's avatar
Philip ABBET committed
408
                                         toPath(index_hash, '.lock'))
André Anjos's avatar
André Anjos committed
409
410
411
412
413
414
415
416
417
418
419
420
            with open(lock_filename, 'a'): os.utime(lock_filename, None)

        if not (ls or delete or checksum): #we're indexing

          try:

            while input_group.hasMoreData():

              input_group.next()

              for i, (input, index_filename, previous_data_index) in \
                      enumerate(zip(input_group, index_filenames,
Philip ABBET's avatar
Philip ABBET committed
421
                                    previous_data_indices)):
André Anjos's avatar
André Anjos committed
422
423
424
425

                with open(index_filename, 'at') as indexfile:
                  if input.data_index != previous_data_index:
                    indexfile.write("%d %d\n" % (
Philip ABBET's avatar
Philip ABBET committed
426
                        input.data_index,
André Anjos's avatar
André Anjos committed
427
                      input.data_index_end,
Philip ABBET's avatar
Philip ABBET committed
428
                    )
André Anjos's avatar
André Anjos committed
429
430
431
432
433
434
435
436
437
438
439
440
441
                    )
                  previous_data_indices[i] = input.data_index

                # creates the checksums for all indexes
                chksum = hashFileContents(index_filename)
                with open(index_filename + '.checksum', 'wt') as f:
                  f.write(chksum)

          except Exception as e:
            logger.critical("Failed to retrieve the next data: %s", e)
            retcode += 1
            continue

442
443
444
445
        if not (ls or delete or checksum): #we're indexing
          db_process.kill()
          db_process.wait()
          db_process.rm()
446

447
448
449
          db_socket.setsockopt(zmq.LINGER, 0)
          db_socket.close()
          zmq_context.term()
450

André Anjos's avatar
André Anjos committed
451
452
453
454
455
456
457
458
459
460
461
462
463
  return retcode


def view_output(configuration, dataset_name, excluded_outputs=''):

  parts = dataset_name.split('/')

  if len(parts) == 4:
    db_name       = os.path.join(*parts[:2])
    protocol_name = parts[2]
    set_name      = parts[3]
  else:
    logger.error("Database view specification should have the format " \
Philip ABBET's avatar
Philip ABBET committed
464
465
                 "`<database>/<version>/<protocol>/<set>', the value you " \
                 "passed (%s) is not valid", dataset_name)
André Anjos's avatar
André Anjos committed
466
467
468
469
470
471
472
473
474
475
476
477
478
    return 1

  excluded_outputs = map(lambda x: x.strip(), excluded_outputs.split(','))

  dataformat_cache = {}
  database = Database(configuration.path, db_name, dataformat_cache)
  if not database.valid:
    logger.error("Failed to load the database `%s':", db_name)
    for e in database.errors: logger.error('  * %s', e)
    return 1

  if protocol_name not in database.protocol_names:
    logger.error("Unknown protocol `%s' for database `%s'. Valid protocols " \
Philip ABBET's avatar
Philip ABBET committed
479
480
                 "are `%s'", protocol_name, db_name,
                 ', '.join(database.protocol_names))
André Anjos's avatar
André Anjos committed
481
482
483
484
485
    return 1

  if set_name not in database.set_names(protocol_name):
    set_names = database.set_names(protocol_name)
    logger.error("Unknown set `%s' for database `%s' and protocol `%s'. " \
Philip ABBET's avatar
Philip ABBET committed
486
487
                 "Valid set names for this protocol are `%s'", set_name, db_name,
                 protocol_name, ', '.join(set_names))
André Anjos's avatar
André Anjos committed
488
489
490
491
492
493
494
495
496
    return 1

  view = database.view(protocol_name, set_name)

  try:
    view.prepare_outputs()
    view.setup()
  except Exception:
    logger.error("Failed to setup the set `%s/%s/%s'", db_name, protocol_name,
Philip ABBET's avatar
Philip ABBET committed
497
                 set_name)
André Anjos's avatar
André Anjos committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
    import traceback
    for e in traceback.format_exc().split('\n'): logger.error('  %s', e)
    return 1

  # Setup the inputs
  input_group = view.input_group(exclude_outputs=excluded_outputs)

  # Display the data
  while input_group.hasMoreData():

    try:
      input_group.next()
    except Exception as e:
      logger.error("Failed to retrieve the next data: %s", e)
      return 1

    logger.extra(80 * '-')

    for input in input_group:
      header = str(input.name)
      if input.data_index == input.data_index_end:
        header += '[%d]' % input.data_index
      else:
        header += '[%d:%d]' % (input.data_index, input.data_index_end)
      header += ": "

      json_data = input.data.as_dict()
      for name, value in json_data.items():
        json_data[name] = common.stringify(value)
        json_data_ = simplejson.dumps(json_data[name], indent=2,
Philip ABBET's avatar
Philip ABBET committed
528
529
530
531
532
533
                                      cls=NumpyJSONEncoder).\
            replace('"BEAT_LIST_DELIMITER[', '[')\
            .replace(']BEAT_LIST_DELIMITER"', ']')\
            .replace('"...",', '...')\
            .replace('"BEAT_LIST_SIZE(', '(')\
            .replace(')BEAT_LIST_SIZE"', ')')
André Anjos's avatar
André Anjos committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
        print(header + json_data_)

  return 0


def process(args):

  if args['list']:
    if args['--remote']:
      with common.make_webapi(args['config']) as webapi:
        return common.display_remote_list(webapi, 'database')
    else:
      return common.display_local_list(args['config'].path, 'database')

  elif args['check']:
    return common.check(args['config'].path, 'database', args['<name>'])

  elif args['pull']:
    with common.make_webapi(args['config']) as webapi:
      return pull(webapi, args['config'].path, args['<name>'],
Philip ABBET's avatar
Philip ABBET committed
554
                  args['--force'], 0, {})
André Anjos's avatar
André Anjos committed
555
556
557
558

  elif args['push']:
    with common.make_webapi(args['config']) as webapi:
      return common.push(webapi, args['config'].path, 'database',
Philip ABBET's avatar
Philip ABBET committed
559
560
                         args['<name>'], ['name', 'declaration', 'code', 'description'],
                         {}, args['--force'], args['--dry-run'], 0)
André Anjos's avatar
André Anjos committed
561
562
563
564

  elif args['diff']:
    with common.make_webapi(args['config']) as webapi:
      return common.diff(webapi, args['config'].path, 'database',
Philip ABBET's avatar
Philip ABBET committed
565
                         args['<name>'][0], ['declaration', 'code', 'description'])
André Anjos's avatar
André Anjos committed
566
567
568
569
570
571
572

  elif args['status']:
    with common.make_webapi(args['config']) as webapi:
      return common.status(webapi, args['config'].path, 'database')[0]

  elif args['version']:
    return common.new_version(args['config'].path, 'database',
Philip ABBET's avatar
Philip ABBET committed
573
                              args['<name>'][0])
André Anjos's avatar
André Anjos committed
574
575
576
577
578
579
580
581
582

  elif args['view']:
    if args['--exclude']:
      return view_output(args['config'], args['<set_name>'], args['--exclude'])
    else:
      return view_output(args['config'], args['<set_name>'])

  elif args['index']:
    return index_output(args['config'], args['<name>'], args['--list'],
Philip ABBET's avatar
Philip ABBET committed
583
584
585
                        args['--delete'], args['--checksum'],
                        int(args['--uid']) if args['--uid'] is not None else None,
                        args['--db-root'])
André Anjos's avatar
André Anjos committed
586
587
588
589

  # Should not happen
  logger.error("unrecognized `databases' subcommand")
  return 1