rucio_data.py 15.6 KB
Newer Older
James Clark's avatar
James Clark committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (C) 2018  James Alexander Clark <james.clark@ligo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""Methods and classes for data registration.
"""

# Native
20
import copy
James Clark's avatar
James Clark committed
21 22 23 24 25 26 27 28 29 30
import os
import sys
import logging
import uuid
import requests

# Rucio
from rucio.client.client import Client
from rucio.common.config import config_get
from rucio.client.uploadclient import UploadClient
31 32 33
from rucio.common.exception import (DataIdentifierAlreadyExists,
                                    DataIdentifierNotFound)
from rucio.common.utils import adler32, execute, generate_uuid, md5
James Clark's avatar
James Clark committed
34

35
# FIXME: define this more cleanly
James Clark's avatar
James Clark committed
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 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
LOGGER = logging.getLogger()

SUCCESS = 0
FAILURE = 1

def setup_logger(logger):
    """
    Set up timestamp format and colors for logging messages
    """
    logger.setLevel(logging.INFO)
    hdlr = logging.StreamHandler()

    def emit_decorator(fnc):
        """
        Aesthetics
        """

        def func(*args):
            """
            Apply aesthetics
            """
            if 'RUCIO_LOGGING_FORMAT' not in os.environ:
                levelno = args[0].levelno
                if levelno >= logging.CRITICAL:
                    color = '\033[31;1m'
                elif levelno >= logging.ERROR:
                    color = '\033[31;1m'
                elif levelno >= logging.WARNING:
                    color = '\033[33;1m'
                elif levelno >= logging.INFO:
                    color = '\033[32;1m'
                elif levelno >= logging.DEBUG:
                    color = '\033[36;1m'
                else:
                    color = '\033[0m'
                formatter = \
                    logging.Formatter(
                        '{0}%(asctime)s\t%(levelname)s\t%(message)s\033[0m'.format(color))
            else:
                formatter = logging.Formatter(
                    os.environ['RUCIO_LOGGING_FORMAT'])
            hdlr.setFormatter(formatter)
            return fnc(*args)

        return func

    hdlr.emit = emit_decorator(hdlr.emit)
    logger.addHandler(hdlr)


setup_logger(LOGGER)

class DatasetInjector(object):
    """
    General Class for injecting a LIGO dataset in rucio

    1) Load list of files for dataset from text file OR diskcache object
    2) Get their checksums
    2) Convert frame names to rucio DIDs
    3) Create Rucio dataset
    4) Register Rucio dataset

    data is a dictionary with either a list of files to register or another
    dictionary including a diskcache object. If the latter, DatasetInjector will
    parse out the file list and metadata.

    """

    # pylint: disable=too-many-instance-attributes
    # 9 attributes doesn't seem so bad

    def __init__(self, dataset_name, data, lifetime=None, force_checksums=False):

        ## Check rucio server connection
        try:
            requests.get(config_get('client', 'rucio_host'))
        except requests.exceptions.RequestException as exe:
            LOGGER.error(exe)
            sys.exit(FAILURE)

        ## Dataset configuration
        self.dataset_name = dataset_name
        self.rse = data['rse']
        self.scope = data['scope']
        self.lifetime = lifetime
        self.transfer_timeout = None

        # Initialization for dataset
        self.rucio_host = config_get('client', 'rucio_host')
        self.client = Client(rucio_host=self.rucio_host)
126
        # XXX: only initialise me if uploading
James Clark's avatar
James Clark committed
127 128 129 130 131 132 133 134 135 136
        self.upload_client = UploadClient(logger=LOGGER)

        # Support lists OR diskcache for files
        try:
            # Treat data as a diskcache, fall back to list on failure
            files = [entry for entry in data['diskcache'].expand()]
        except KeyError:
            files = data['filelist'][:]

        # Get dictionary of files and metadata to register
137
        # XXX
James Clark's avatar
James Clark committed
138
        force_checksums=True
James Clark's avatar
James Clark committed
139 140 141 142 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 184 185 186 187 188
        if not force_checksums:
            LOGGER.info("Checking how many of %d files already registered",
                        len(files))
            files = self.reduce_file_list(files)
        self.enumerate_uploads(files)

    def reduce_file_list(self, files):
        """
        Reduce the list of files for registration to extant, unregistered files.
        Skip files which don't exist or are already registered.
        """

        # Eliminate invalid files from a copy of the list for easier logging
        reduced_files = files[:]
        for fil in files:

            # Check file exists and is a file
            if not os.path.exists(fil) or not os.path.isfile(fil):
                LOGGER.warning("%s not a valid file", fil)
                reduced_files.remove(fil)
                continue

            # Check if file registered already
            if self._check_replica(os.path.basename(fil)):
                reduced_files.remove(fil)

        LOGGER.info("%d new files to upload/register", len(reduced_files))

        return reduced_files


    def _check_replica(self, lfn):
        """
        Check if a replica of the given file at the site already exists.
        """
        LOGGER.debug("Checking for %s:%s at %s", self.scope, lfn, self.rse)
        replicas = list(
            self.client.list_replicas([{
                'scope': self.scope,
                'name': lfn
            }]))

        if replicas:
            replicas = replicas[0]
            if 'rses' in replicas:
                if self.rse in replicas['rses']:
                    LOGGER.debug("%s:%s already has a replica at %s",
                                 self.scope, lfn, self.rse)
                    return True
        LOGGER.debug("No existing replicas of %s", lfn)
189

James Clark's avatar
James Clark committed
190
        return False
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 217 218 219 220 221 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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

    def enumerate_uploads(self, files):
        """
        Create a list of dictionaries which describe files to pass to the rucio
        UploadClient
        """
        items = list()
        for path in files:

            dataset_did_str = ('%s:%s' % (self.scope, self.dataset_name))
            items.append(
                    {'path': path,
                     'rse': self.rse,
                     'did_scope': self.scope,
                     'did_name': os.path.basename(path),
                     'dataset_scope': self.scope,
                     'dataset_name': self.dataset_name,
                     'dataset_did_str': dataset_did_str,
                     'force_scheme': None,
                     'no_register': False,
                     'register_after_upload': True,
                     'lifetime': self.lifetime,
                     'transfer_timeout': self.transfer_timeout,
                     'guid': str(uuid.uuid4())})

        # check given sources, resolve dirs into files, and collect meta infos
        LOGGER.info("Checking file list")
        self.files = self._collect_and_validate_file_info(items)
        LOGGER.debug("Checks passed")

    def register_files(self):
        """
        Pass the list of file dictionaries to an UploadClient instance and upload.
        """
        # FIXME: change this to "add_files": upload if the DID does not exist
        map((lambda file: self._register_file(file)), self.files) 

    def upload_files(self):
        """
        Pass the list of file dictionaries to an UploadClient instance and upload.
        """
        self.upload_client.upload(self.files)

    def _register_file(self, file):
        """
        Registers the given file in Rucio. Creates a dataset if
        needed. Registers the file DID and creates the replication
        rule if needed. Adds a replica to the file did.
        (This function is modified from `uploadclient.py` to support
        registration of files at arbitrary sites).

        :param file: dictionary describing the file

        :raises DataIdentifierAlreadyExists: if file DID is already registered
        and the checksums do not match
        """
        LOGGER.debug('Registering file')
        rse = file['rse']
        dataset_did_str = file.get('dataset_did_str')
        # register a dataset if we need to
        try:
            LOGGER.debug('Trying to create dataset: %s' % dataset_did_str)
            self.client.add_dataset(scope=file['dataset_scope'],
                                    name=file['dataset_name'],
                                    rules=[{'account': self.client.account,
                                            'copies': 1,
                                            'rse_expression': rse,
                                            'grouping': 'DATASET',
                                            'lifetime': file.get('lifetime')}])
            LOGGER.info('Successfully created dataset %s' % dataset_did_str)
        except DataIdentifierAlreadyExists:
            LOGGER.debug('Dataset %s already exists' % dataset_did_str)

        file_scope = file['did_scope']
        file_name = file['did_name']
        file_did = {'scope': file_scope, 'name': file_name}
        replica_for_api = self._convert_file_for_api(file)
        try:
            # if the remote checksum is different this did must not be used
            meta = self.client.get_metadata(file_scope, file_name)
            LOGGER.info('File DID already exists')
            LOGGER.debug('local checksum: %s, remote checksum: %s' % (file['adler32'], meta['adler32']))

            if meta['adler32'] != file['adler32']:
                LOGGER.error('Local checksum %s does not match remote checksum %s' % (file['adler32'], meta['adler32']))

                raise DataIdentifierAlreadyExists

            # add file to rse if it is not registered yet
            replicastate = list(self.client.list_replicas([file_did], all_states=True))
            if rse not in replicastate[0]['rses']:
                self.client.add_replicas(rse=rse, files=[replica_for_api])
                LOGGER.info('Successfully added replica in Rucio catalogue at %s' % rse)
        except DataIdentifierNotFound:
            LOGGER.debug('File DID does not exist')
            self.client.add_replicas(rse=rse, files=[replica_for_api])
            LOGGER.info('Successfully added replica in Rucio catalogue at %s' % rse)
            if not dataset_did_str:
                # only need to add rules for files if no dataset is given
                self.client.add_replication_rule([file_did], copies=1, rse_expression=rse, lifetime=file.get('lifetime'))
                LOGGER.info('Successfully added replication rule at %s' % rse)

    def _get_file_guid(self, file):
        """
        Get the guid of a file, trying different strategies
        (This function is meant to be used as class internal only)

        :param file: dictionary describing the file

        :returns: the guid
        """
        guid = file.get('guid')
        if not guid and 'pool.root' in file['basename'].lower() and not file.get('no_register'):
            status, output, err = execute('pool_extractFileIdentifier %s' % file['path'])
            if status != 0:
                msg = 'Trying to upload ROOT files but pool_extractFileIdentifier tool can not be found.\n'
                msg += 'Setup your ATHENA environment and try again.'
                raise RucioException(msg)
            try:
                guid = output.splitlines()[-1].split()[0].replace('-', '').lower()
            except Exception:
                raise RucioException('Error extracting GUID from ouput of pool_extractFileIdentifier')
        elif guid:
            guid = guid.replace('-', '')
        else:
            guid = generate_uuid()
        return guid

    def _collect_file_info(self, filepath, item):
        """
        Collects infos (e.g. size, checksums, etc.) about the file and
        returns them as a dictionary
        (This function is meant to be used as class internal only)

        :param filepath: path where the file is stored
        :param item: input options for the given file

        :returns: a dictionary containing all collected info and the input options
        """
        new_item = copy.deepcopy(item)
        new_item['path'] = filepath
        new_item['dirname'] = os.path.dirname(filepath)
        new_item['basename'] = os.path.basename(filepath)

        new_item['bytes'] = os.stat(filepath).st_size
        new_item['adler32'] = adler32(filepath)
        new_item['md5'] = md5(filepath)
        new_item['meta'] = {'guid': self._get_file_guid(new_item)}
        new_item['state'] = 'C'
        if not new_item.get('did_scope'):
            new_item['did_scope'] = self.default_file_scope
        if not new_item.get('did_name'):
            new_item['did_name'] = new_item['basename']

        return new_item

    def _convert_file_for_api(self, file):
        """
        Creates a new dictionary that contains only the values
        that are needed for the upload with the correct keys
        (This function is meant to be used as class internal only)

        :param file: dictionary describing a file to upload

        :returns: dictionary containing not more then the needed values for the upload
        """
        replica = {}
        replica['scope'] = file['did_scope']
        replica['name'] = file['did_name']
        replica['bytes'] = file['bytes']
        replica['adler32'] = file['adler32']
        replica['md5'] = file['md5']
        replica['meta'] = file['meta']
        replica['state'] = file['state']
        pfn = file.get('pfn')
        if pfn:
            replica['pfn'] = pfn
        return replica

    def _collect_and_validate_file_info(self, items):
        """
        Checks if there are any inconsistencies within the given input
        options and stores the output of _collect_file_info for every file
        (This function is meant to be used as class internal only)

        :param filepath: list of dictionaries with all input files and options

        :returns: a list of dictionaries containing all descriptions of the files to upload

        :raises InputValidationError: if an input option has a wrong format
        """
        logger = LOGGER
        files = []
        for item in items:
            path = item.get('path')
            pfn = item.get('pfn')
            if not path:
                logger.warning('Skipping source entry because the key "path" is missing')
                continue
            if not item.get('rse'):
                logger.warning('Skipping file %s because no rse was given' % path)
                continue
            if pfn:
                item['force_scheme'] = pfn.split(':')[0]

            if os.path.isdir(path):
                dname, subdirs, fnames = next(os.walk(path))
                for fname in fnames:
                    logger.debug('Collecting file info for: %s' % fname)
                    file = self._collect_file_info(os.path.join(dname, fname), item)
                    files.append(file)
                if not len(fnames) and not len(subdirs):
                    logger.warning('Skipping %s because it is empty.' % dname)
                elif not len(fnames):
                    logger.warning('Skipping %s because it has no files in it. Subdirectories are not supported.' % dname)
            elif os.path.isfile(path):
                file = self._collect_file_info(path, item)
                files.append(file)
            else:
                logger.warning('No such file or directory: %s' % path)

        if not len(files):
            raise InputValidationError('No valid input files given')

        return files