Exemple #1
0
def action(parser, args):
    group = optparse.OptionGroup(parser, 'Delete options')
    group.add_option('--version-id', dest='version_id', action='store',
                     default=None, help='delete given manifest version id')
    parser.add_option_group(group)
    parser.usage = USAGE
    (options, args) = parser.parse_args(args)
    cfg_file_path = validate_path(options.cfg_file)
    config = Config(cfg_file_path, options)
    client = NSclient(
        auth_url=config.auth_url, auth_version=config.auth_version,
        user=config.user, key=config.key, proxy_host=config.proxy_host,
        proxy_port=config.proxy_port, proxy_user=config.proxy_user,
        proxy_pass=config.proxy_pass, debug=False)
    if not args or len(args) > 2:
        parser.print_usage()
        return ERROR_CODE
    if len(args) != 2 and options.version_id:
        print >> sys.stderr, 'ERROR: version id allowed only if manifest ' \
                             'specified'
        return ERROR_CODE
    if len(args) == 1:
        client.delete_container(args[0])
        typ, name = 'Container', args[0]
    elif len(args) == 2:
        client.delete_manifest(args[0], args[1], version_id=options.version_id)
        typ, name = 'Manifest', '%s/%s' % (args[0], args[1])
        if options.version_id:
            name += ' version id %s' % options.version_id
    print >> sys.stdout, '%s was successfully deleted' % name
    return SUCCESS_CODE
def action(parser, args):
    parser.usage = USAGE
    (opts, args) = parser.parse_args(args)
    cfg_file_path = validate_path(opts.cfg_file)
    config = Config(cfg_file_path)
    if not os.path.exists(os.path.split(cfg_file_path)[0]):
        raise OptionError('Invalid path for configuration file: %s' %
                          cfg_file_path)
    #TODO: if already exists cfg_file, ask whether to make a change
    options = [
        ('auth_url', 'Authorization url', 'URL for obtaining an auth token',
         (NotEmptyValidator('Please define authorization url'),
          NotUrlValidator('Invalid url value'))),
        ('auth_version', 'Authorization version',
         'Specify a version for authentication (default: 1.0)',
         (NotEmptyValidator('Please authorization version'), )),
        ('user', 'User', 'User name for obtaining an auth token',
         (NotEmptyValidator('Please define user'), )),
        ('key', 'Key', 'Key for obtaining an auth token',
         (NotEmptyValidator('Please define key'), ))
    ]
    print >> sys.stdout, 'Configure nostclient.'
    print >> sys.stdout, 'Enter new values or accept defaults in brackets ' \
                         'with Enter.'
    print >> sys.stdout
    for key, name, description, validators in options:
        print >> sys.stdout, description
        default = getattr(config, key)
        if default:
            promt = '%s [%s]: ' % (name, default)
        else:
            promt = '%s: ' % name
        if not isinstance(validators, (list, tuple)):
            validators = tuple(validators)
        while True:
            value = raw_input(promt) or default
            try:
                for validator in validators:
                    value = validator(value)
            except ValidationError, e:
                print >> sys.stderr, 'ERROR: %s' % e
                continue
            break
        setattr(config, key, value)
Exemple #3
0
def action(parser, args):
    group = optparse.OptionGroup(parser, 'Upload options')
    group.add_option('--only-placeholder', dest='only_placeholder',
                     help='upload only manifest placeholder', default=False,
                     action='store_true')
    group.add_option('--only-manifest', dest='only_manifest', default=False,
                     help='upload only manifest', action='store_true')
    group.add_option('--only-chunk', dest='only_chunk', default=False,
                     help='upload only chunk', action='store_true')
    group.add_option('--chunk', dest='chunk', action='store',
                     help='path to chunk file')
    group.add_option('--session-id', dest='session_id', action='store',
                     help='manifest session ID')
    group.add_option('--session-timestamp', dest='session_timestamp',
                     action='store', help='manifest session timestamp')
    group.add_option('--chunk-size', dest='chunk_size', type='int',
                     action='store', help='chunk size', default=MiB)
    group.add_option('-w', '--workers', dest='workers', type='int',
                     action='store', default=5,
                     help='number of workers threads')
    group.add_option('-q', '--quite', dest='quite', action='store_true',
                     default=False, help='hide progress bar')
    parser.add_option_group(group)
    parser.usage = USAGE
    (options, args) = parser.parse_args(args)
    config = Config(options.cfg_file, options)
    client = NSclient(
        auth_url=config.auth_url, auth_version=config.auth_version,
        user=config.user, key=config.key, proxy_host=config.proxy_host,
        proxy_port=config.proxy_port, proxy_user=config.proxy_user,
        proxy_pass=config.proxy_pass, debug=False)

    conn, path, req_url, req_auth_token = client.validate_conn()

    # PUT account
    if not args:
        client.put_account(http_conn=conn, req_url=req_url,
                           req_auth_token=req_auth_token)
        return SUCCESS_CODE

    headers = {}

    # PUT container
    if len(args) == 1:
        client.put_container(args[0], headers=headers, http_conn=conn,
                             req_url=req_url, req_auth_token=req_auth_token)
        return SUCCESS_CODE

    container_name, object_name = args[0], args[1]
    try:
        object_name = validate_obj_name(object_name)
    except ValueError:
        print >> sys.stderr, 'ERROR: Invalid object name: %s' % args[1]
        return ERROR_CODE

    # PUT placeholder
    if options.only_placeholder:
        session_id, session_timestamp =\
            client.put_placeholder(
                container_name, object_name, http_conn=conn, req_url=req_url,
                req_auth_token=req_auth_token)
        print >> sys.stdout, 'Session id: %s\nSession timestamp: %s' % \
                             (session_id, session_timestamp)
        return SUCCESS_CODE

    filepath = validate_path(args[1])
    if not os.path.exists(filepath):
        print >> sys.stderr, 'ERROR: File %s does not exists' % filepath
        return ERROR_CODE

    for isdir, path, name in filepath_generator(filepath, object_name):
        if isdir:
            client.put_directory(container_name, name + '/')
            continue
        kwargs = {'chunk_size': options.chunk_size, 'workers': options.workers}
        info = os.stat(path)
        bar = ProgressBar(max_value=info.st_size, title=name,
                          quite=options.quite)
        bar.start()
        kwargs['callback'] = bar.callback
        kwargs['error_callback'] = bar.clear
        try:
            with open(path, 'rb') as fp:
                client.put_object(container_name, name, fp, headers=headers,
                                  http_conn=conn, req_url=req_url,
                                  req_auth_token=req_auth_token, **kwargs)
        except Exception, e:
            bar.clear()
            raise e
        bar.finish()
Exemple #4
0
def action(parser, args):
    group = optparse.OptionGroup(parser, 'ACL options')
    group.add_option(
        '--acp', dest='acp', default=None, action='store',
        help='acl for resource, for example account:user READ_ACP')
    group.add_option(
        '--version-id', dest='version_id', action='store', default=None,
        help='allows to get or set acl for given manifest version id')
    parser.add_option_group(group)
    parser.usage = USAGE
    (options, args) = parser.parse_args(args)
    if not args or len(args) > 2:
        parser.print_usage()
        return ERROR_CODE
    if len(args) == 1 and options.version_id:
        print >> sys.stderr, "ERROR: version id option allowed only for " \
                             "manifest operation"
        return ERROR_CODE
    cfg_file_path = validate_path(options.cfg_file)
    config = Config(cfg_file_path, options)
    client = NSclient(
        auth_url=config.auth_url, auth_version=config.auth_version,
        user=config.user, key=config.key, proxy_host=config.proxy_host,
        proxy_port=config.proxy_port, proxy_user=config.proxy_user,
        proxy_pass=config.proxy_pass, debug=False)
    if options.acp:
        permissions = [p.strip() for p in options.acp.split(';') if p.strip()]
        acl = []
        for permission in permissions:
            if ' ' not in permission:
                print >> sys.stderr, "ERROR: Invalid permission %s" % \
                                     permission
                return ERROR_CODE
            user, perms = permission.split(' ', 1)
            perms = [p.strip() for p in perms.split(',') if p.strip()]
            for p in perms:
                if p not in ACP_VALUES:
                    print >> sys.stderr, "ERROR: Invalid permission %s" % \
                                         permission
                    return ERROR_CODE
            acl.append({'user': user, 'permissions': ','.join(perms)})
        kwargs = {}
        if len(args) == 1:
            func = client.set_container_acp
        elif len(args) == 2:
            func = client.set_manifest_acp
            kwargs['version_id'] = options.version_id
        status, headers, response = func(acl, *args, **kwargs)
        if not is_success(status):
            print >> sys.stderr, response.read()
            return ERROR_CODE
        return SUCCESS_CODE
    kwargs = {}
    if len(args) == 1:
        func = client.get_container_acp
    elif len(args) == 2:
        func = client.get_manifest_acp
        kwargs['version_id'] = options.version_id
    status, headers = func(*args, **kwargs)
    typ = 'container' if len(args) == 1 else 'manifest'
    if 'x-%s-owner' % typ in headers:
        print >> sys.stdout, 'Owner: %s' % headers['x-%s-owner' % typ]
    permissions = {}
    for header in headers:
        key = None
        if typ == 'container':
            if header in ('x-container-read', 'x-container-write'):
                key = header[12:]
            elif header.startswith('x-container-acl-'):
                key = header[16:].replace('-', '_')
        else:
            if header.startswith('x-manifest-acl-'):
                key = header[15:].replace('-', '_')
        if key:
            permissions[key] = [u.strip() for u in headers[header].split(',')
                                if u.strip()]
    for key, value in permissions.iteritems():
        if value:
            print >> sys.stdout, '%s: %s' % (key.replace('_', ' ').title(),
                                             ', '.join(value))
    return SUCCESS_CODE