Пример #1
0
def cli(env, identifier, domain, userfile, tag, hostname, userdata):
    """Edit a virtual server's details."""

    data = {}

    if userdata and userfile:
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')
    if userfile:
        if not os.path.exists(userfile):
            raise exceptions.ArgumentError(
                'File does not exist [-u | --userfile] = %s' % userfile)

    if userdata:
        data['userdata'] = userdata
    elif userfile:
        with open(userfile, 'r') as userfile_obj:
            data['userdata'] = userfile_obj.read()

    data['hostname'] = hostname
    data['domain'] = domain
    data['tag'] = tag

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not vsi.edit(vs_id, **data):
        raise exceptions.CLIAbort("Failed to update virtual server")
Пример #2
0
def cli(env, identifier, cpu, private, memory, network, flavor):
    """Upgrade a virtual server."""

    vsi = SoftLayer.VSManager(env.client)

    if not any([cpu, memory, network, flavor]):
        raise exceptions.ArgumentError(
            "Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade")

    if private and not cpu:
        raise exceptions.ArgumentError(
            "Must specify [--cpu] when using [--private]")

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not (env.skip_confirmations or formatting.confirm(
            "This action will incur charges on your account. "
            "Continue?")):
        raise exceptions.CLIAbort('Aborted')

    if memory:
        memory = int(memory / 1024)

    if not vsi.upgrade(vs_id,
                       cpus=cpu,
                       memory=memory,
                       nic_speed=network,
                       public=not private,
                       preset=flavor):
        raise exceptions.CLIAbort('VS Upgrade Failed')
Пример #3
0
    def execute(self, args):
        data = {}

        if args['--userdata'] and args['--userfile']:
            raise exceptions.ArgumentError(
                '[-u | --userdata] not allowed with [-F | --userfile]')
        if args['--userfile']:
            if not os.path.exists(args['--userfile']):
                raise exceptions.ArgumentError(
                    'File does not exist [-u | --userfile] = %s'
                    % args['--userfile'])

        if args.get('--userdata'):
            data['userdata'] = args['--userdata']
        elif args.get('--userfile'):
            with open(args['--userfile'], 'r') as userfile:
                data['userdata'] = userfile.read()

        data['hostname'] = args.get('--hostname')
        data['domain'] = args.get('--domain')
        data['tag'] = args.get("--tag")

        vsi = SoftLayer.VSManager(self.client)
        vs_id = helpers.resolve_id(vsi.resolve_ids,
                                   args.get('<identifier>'),
                                   'VS')
        if not vsi.edit(vs_id, **data):
            raise exceptions.CLIAbort("Failed to update virtual server")
Пример #4
0
def cli(env, identifier, cpu, private, memory, network, flavor, add_disk, resize_disk):
    """Upgrade a virtual server."""

    vsi = SoftLayer.VSManager(env.client)

    if not any([cpu, memory, network, flavor, resize_disk, add_disk]):
        raise exceptions.ArgumentError("Must provide [--cpu],"
                                       " [--memory], [--network], [--flavor], [--resize-disk], or [--add] to upgrade")

    if private and not cpu:
        raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]")

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")):
        raise exceptions.CLIAbort('Aborted')

    disk_json = []
    if memory:
        memory = int(memory / 1024)
    if resize_disk:
        for guest_disk in resize_disk:
            disks = {'capacity': guest_disk[0], 'number': guest_disk[1]}
            disk_json.append(disks)

    elif add_disk:
        for guest_disk in add_disk:
            disks = {'capacity': guest_disk, 'number': -1}
            disk_json.append(disks)

    if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor,
                       disk=disk_json):
        raise exceptions.CLIAbort('VS Upgrade Failed')
Пример #5
0
    def execute(self, args):
        data = {}

        if args['--userdata'] and args['--userfile']:
            raise exceptions.ArgumentError(
                '[-u | --userdata] not allowed with [-F | --userfile]')
        if args['--userfile']:
            if not os.path.exists(args['--userfile']):
                raise exceptions.ArgumentError(
                    'File does not exist [-u | --userfile] = %s' %
                    args['--userfile'])

        if args.get('--userdata'):
            data['userdata'] = args['--userdata']
        elif args.get('--userfile'):
            with open(args['--userfile'], 'r') as userfile:
                data['userdata'] = userfile.read()

        data['hostname'] = args.get('--hostname')
        data['domain'] = args.get('--domain')

        mgr = SoftLayer.HardwareManager(self.client)
        hw_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'),
                                   'hardware')
        if not mgr.edit(hw_id, **data):
            raise exceptions.CLIAbort("Failed to update hardware")
Пример #6
0
def cli(env, storage_type, size, iops, tier, os_type, location, snapshot_size):
    """Order a block storage volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    storage_type = storage_type.lower()

    if storage_type == 'performance':
        if iops is None:
            raise exceptions.CLIAbort(
                'Option --iops required with Performance')

        if iops < 100 or iops > 6000:
            raise exceptions.CLIAbort(
                'Option --iops must be between 100 and 6000, inclusive')

        if iops % 100 != 0:
            raise exceptions.CLIAbort(
                'Option --iops must be a multiple of 100')

        if snapshot_size is not None:
            raise exceptions.CLIAbort(
                'Option --snapshot-size not allowed for performance volumes.'
                'Snapshots are only available for endurance storage.')

        try:
            order = block_manager.order_block_volume(
                storage_type='performance_storage_iscsi',
                location=location,
                size=int(size),
                iops=iops,
                os_type=os_type)
        except ValueError as ex:
            raise exceptions.ArgumentError(str(ex))

    if storage_type == 'endurance':
        if tier is None:
            raise exceptions.CLIAbort(
                'Option --tier required with Endurance in IOPS/GB '
                '[0.25,2,4,10]')

        try:
            order = block_manager.order_block_volume(
                storage_type='storage_service_enterprise',
                location=location,
                size=int(size),
                tier_level=float(tier),
                os_type=os_type,
                snapshot_size=snapshot_size)
        except ValueError as ex:
            raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            order['placedOrder']['id']))
        for item in order['placedOrder']['items']:
            click.echo(" > %s" % item['description'])
    else:
        click.echo("Order could not be placed! Please verify your options " +
                   "and try again.")
Пример #7
0
def _validate_args(args):
    """Raises an ArgumentError if the given arguments are not valid."""

    if all([args['userdata'], args['userfile']]):
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    image_args = [args['os'], args['image']]
    if all(image_args):
        raise exceptions.ArgumentError(
            '[-o | --os] not allowed with [--image]')

    if not any(image_args):
        raise exceptions.ArgumentError('One of [--os | --image] is required')
Пример #8
0
def cli(env, identifier, memory, network, drive_controller, public_bandwidth, add_disk, resize_disk, test):
    """Upgrade a Hardware Server."""

    mgr = SoftLayer.HardwareManager(env.client)

    if not any([memory, network, drive_controller, public_bandwidth, add_disk, resize_disk]):
        raise exceptions.ArgumentError("Must provide "
                                       " [--memory], [--network], [--drive-controller], [--public-bandwidth],"
                                       "[--add-disk] or [--resize-disk]")

    hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'Hardware')
    if not test:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborted')

    disk_list = list()
    if add_disk:
        for guest_disk in add_disk:
            disks = {'description': 'add_disk', 'capacity': guest_disk[0], 'number': guest_disk[1]}
            disk_list.append(disks)
    if resize_disk:
        for guest_disk in resize_disk:
            disks = {'description': 'resize_disk', 'capacity': guest_disk[0], 'number': guest_disk[1]}
            disk_list.append(disks)

    if not mgr.upgrade(hw_id, memory=memory, nic_speed=network, drive_controller=drive_controller,
                       public_bandwidth=public_bandwidth, disk=disk_list, test=test):
        raise exceptions.CLIAbort('Hardware Server Upgrade Failed')
    env.fout('Successfully Upgraded.')
Пример #9
0
def cli(env, volume_id, snapshot_schedule, location, tier, os_type):
    """Order a block storage replica volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volume_id = helpers.resolve_id(block_manager.resolve_ids, volume_id,
                                         'Block Volume')

    if tier is not None:
        tier = float(tier)

    try:
        order = block_manager.order_replicant_volume(
            block_volume_id,
            snapshot_schedule=snapshot_schedule,
            location=location,
            tier=tier,
            os_type=os_type,
        )
    except ValueError as ex:
        raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            utils.lookup(order, 'placedOrder', 'id')))
        for item in utils.lookup(order, 'placedOrder', 'items'):
            click.echo(" > %s" % item.get('description'))
    else:
        click.echo("Order could not be placed! Please verify your options " +
                   "and try again.")
Пример #10
0
def cli(env, origin_volume_id, origin_snapshot_id, duplicate_size,
        duplicate_iops, duplicate_tier, duplicate_snapshot_size, billing):
    """Order a duplicate file storage volume."""
    file_manager = SoftLayer.FileStorageManager(env.client)

    hourly_billing_flag = False
    if billing.lower() == "hourly":
        hourly_billing_flag = True

    if duplicate_tier is not None:
        duplicate_tier = float(duplicate_tier)

    try:
        order = file_manager.order_duplicate_volume(
            origin_volume_id,
            origin_snapshot_id=origin_snapshot_id,
            duplicate_size=duplicate_size,
            duplicate_iops=duplicate_iops,
            duplicate_tier_level=duplicate_tier,
            duplicate_snapshot_size=duplicate_snapshot_size,
            hourly_billing_flag=hourly_billing_flag
        )
    except ValueError as ex:
        raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            order['placedOrder']['id']))
        for item in order['placedOrder']['items']:
            click.echo(" > %s" % item['description'])
    else:
        click.echo("Order could not be placed! Please verify your options " +
                   "and try again.")
Пример #11
0
def update_with_template_args(args, list_args=None):
    """Populates arguments with arguments from the template file, if provided.

    :param dict args: command-line arguments
    """
    if not args.get('--template'):
        return

    list_args = list_args or []

    template_path = args.pop('--template')
    if not os.path.exists(template_path):
        raise exceptions.ArgumentError(
            'File does not exist [-t | --template] = %s'
            % template_path)

    config = utils.configparser.ConfigParser()
    ini_str = '[settings]\n' + open(
        os.path.expanduser(template_path), 'r').read()
    ini_fp = utils.StringIO(ini_str)
    config.readfp(ini_fp)

    # Merge template options with the options passed in
    for key, value in config.items('settings'):
        option_key = '--%s' % key
        if option_key in list_args:
            value = value.split(',')
        if not args.get(option_key):
            args[option_key] = value
Пример #12
0
def cli(env, origin_volume_id, origin_snapshot_id, duplicate_size,
        duplicate_iops, duplicate_tier, duplicate_snapshot_size):
    """Order a duplicate block storage volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)

    if duplicate_tier is not None:
        duplicate_tier = float(duplicate_tier)

    try:
        order = block_manager.order_duplicate_volume(
            origin_volume_id,
            origin_snapshot_id=origin_snapshot_id,
            duplicate_size=duplicate_size,
            duplicate_iops=duplicate_iops,
            duplicate_tier_level=duplicate_tier,
            duplicate_snapshot_size=duplicate_snapshot_size)
    except ValueError as ex:
        raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            order['placedOrder']['id']))
        for item in order['placedOrder']['items']:
            click.echo(" > %s" % item['description'])
    else:
        click.echo("Order could not be placed! Please verify your options " +
                   "and try again.")
Пример #13
0
def cli(env, unique_id, origin, path, origin_type, header,
        bucket_name, port, protocol, optimize_for, extensions, cache_query):
    """Create an origin path for an existing CDN mapping.

    For more information see the following documentation: \n
    https://cloud.ibm.com/docs/infrastructure/CDN?topic=CDN-manage-your-cdn#adding-origin-path-details
    """

    manager = SoftLayer.CDNManager(env.client)

    if origin_type == 'storage' and not bucket_name:
        raise exceptions.ArgumentError('[-b | --bucket-name] is required when [-t | --origin-type] is "storage"')

    result = manager.add_origin(unique_id, origin, path, origin_type=origin_type,
                                header=header, port=port, protocol=protocol,
                                bucket_name=bucket_name, file_extensions=extensions,
                                optimize_for=optimize_for, cache_query=cache_query)

    table = formatting.Table(['Item', 'Value'])
    table.align['Item'] = 'r'
    table.align['Value'] = 'r'

    table.add_row(['CDN Unique ID', result['mappingUniqueId']])

    if origin_type == 'storage':
        table.add_row(['Bucket Name', result['bucketName']])

    table.add_row(['Origin', result['origin']])
    table.add_row(['Origin Type', result['originType']])
    table.add_row(['Path', result['path']])
    table.add_row(['Port', result['httpPort']])
    table.add_row(['Configuration', result['performanceConfiguration']])
    table.add_row(['Status', result['status']])

    env.fout(table)
Пример #14
0
def cli(env, volume_id, capacity, tier, upgrade):
    """Order snapshot space for a file storage volume."""
    file_manager = SoftLayer.FileStorageManager(env.client)

    if tier is not None:
        tier = float(tier)

    try:
        order = file_manager.order_snapshot_space(volume_id,
                                                  capacity=capacity,
                                                  tier=tier,
                                                  upgrade=upgrade)
    except ValueError as ex:
        raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            order['placedOrder']['id']))
        for item in order['placedOrder']['items']:
            click.echo(" > %s" % item['description'])
        if 'status' in order['placedOrder'].keys():
            click.echo(" > Order status: %s" % order['placedOrder']['status'])
    else:
        click.echo("Order could not be placed! Please verify your options " +
                   "and try again.")
Пример #15
0
def cli(env, identifier, domain, userfile, tag, hostname, userdata):
    """Edit hardware details."""

    if userdata and userfile:
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    data = {
        'hostname': hostname,
        'domain': domain,
    }

    if userdata:
        data['userdata'] = userdata
    elif userfile:
        with open(userfile, 'r') as userfile_obj:
            data['userdata'] = userfile_obj.read()

    if tag:
        data['tags'] = ','.join(tag)

    mgr = SoftLayer.HardwareManager(env.client)
    hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')

    if not mgr.edit(hw_id, **data):
        raise exceptions.CLIAbort("Failed to update hardware")
Пример #16
0
def cli(env, identifier, domain, userfile, tag, hostname, userdata,
        public_speed, private_speed):
    """Edit a virtual server's details."""

    if userdata and userfile:
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    data = {}

    if userdata:
        data['userdata'] = userdata
    elif userfile:
        with open(userfile, 'r') as userfile_obj:
            data['userdata'] = userfile_obj.read()

    data['hostname'] = hostname
    data['domain'] = domain

    if tag:
        data['tags'] = ','.join(tag)

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not vsi.edit(vs_id, **data):
        raise exceptions.CLIAbort("Failed to update virtual server")

    if public_speed is not None:
        vsi.change_port_speed(vs_id, True, int(public_speed))

    if private_speed is not None:
        vsi.change_port_speed(vs_id, False, int(private_speed))
Пример #17
0
def cli(env, volume_id, new_size, new_iops, new_tier):
    """Modify an existing block storage volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)

    if new_tier is not None:
        new_tier = float(new_tier)

    try:
        order = block_manager.order_modified_volume(
            volume_id,
            new_size=new_size,
            new_iops=new_iops,
            new_tier_level=new_tier,
        )
    except ValueError as ex:
        raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            order['placedOrder']['id']))
        for item in order['placedOrder']['items']:
            click.echo(" > %s" % item['description'])
    else:
        click.echo(
            "Order could not be placed! Please verify your options and try again."
        )
Пример #18
0
def cli(env, user, template):
    """Edit a Users details

    JSON strings should be enclosed in '' and each item should be enclosed in ""

    Example::

        slcli user edit-details testUser -t '{"firstName": "Test", "lastName": "Testerson"}'

    """
    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, user, 'username')

    user_template = {}
    if template is not None:
        try:
            template_object = json.loads(template)
            for key in template_object:
                user_template[key] = template_object[key]
        except ValueError as ex:
            raise exceptions.ArgumentError("Unable to parse --template. %s" %
                                           ex)

    result = mgr.edit_user(user_id, user_template)
    if result:
        click.secho("%s updated successfully" % (user), fg='green')
    else:
        click.secho("Failed to update %s" % (user), fg='red')
Пример #19
0
def cli(env, volume_id, snapshot_schedule, location, tier):
    """Order a file storage replica volume."""
    file_manager = SoftLayer.FileStorageManager(env.client)

    if tier is not None:
        tier = float(tier)

    try:
        order = file_manager.order_replicant_volume(
            volume_id,
            snapshot_schedule=snapshot_schedule,
            location=location,
            tier=tier,
        )
    except ValueError as ex:
        raise exceptions.ArgumentError(str(ex))

    if 'placedOrder' in order.keys():
        click.echo("Order #{0} placed successfully!".format(
            order['placedOrder']['id']))
        for item in order['placedOrder']['items']:
            click.echo(" > %s" % item['description'])
    else:
        click.echo("Order could not be placed! Please verify your options " +
                   "and try again.")
Пример #20
0
def cli(env, username, email, password, from_user, template, api_key):
    """Creates a user Users.

    :Example: slcli user create [email protected] -e [email protected] -p generate -a
    -t '{"firstName": "Test", "lastName": "Testerson"}'

    Remember to set the permissions and access for this new user.
    """

    mgr = SoftLayer.UserManager(env.client)
    user_mask = (
        "mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, "
        "state, userStatusId, timezoneId]")
    from_user_id = None
    if from_user is None:
        user_template = mgr.get_current_user(objectmask=user_mask)
        from_user_id = user_template['id']
    else:
        from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user,
                                          'username')
        user_template = mgr.get_user(from_user_id, objectmask=user_mask)
    # If we send the ID back to the API, an exception will be thrown
    del user_template['id']

    if template is not None:
        try:
            template_object = json.loads(template)
            for key in template_object:
                user_template[key] = template_object[key]
        except ValueError as ex:
            raise exceptions.ArgumentError("Unable to parse --template. %s" %
                                           ex)

    user_template['username'] = username
    if password == 'generate':
        password = generate_password()

    user_template['email'] = email

    if not env.skip_confirmations:
        table = formatting.KeyValueTable(['name', 'value'])
        for key in user_template:
            table.add_row([key, user_template[key]])
        table.add_row(['password', password])
        click.secho("You are about to create the following user...",
                    fg='green')
        env.fout(table)
        if not formatting.confirm("Do you wish to continue?"):
            raise exceptions.CLIAbort("Canceling creation!")

    result = mgr.create_user(user_template, password)
    new_api_key = None
    if api_key:
        click.secho("Adding API key...", fg='green')
        new_api_key = mgr.add_api_authentication_key(result['id'])

    table = formatting.Table(['Username', 'Email', 'Password', 'API Key'])
    table.add_row([result['username'], result['email'], password, new_api_key])
    env.fout(table)
Пример #21
0
def cli(env, identifier, hardware_identifier, virtual_identifier):
    """Detach devices from a ticket."""
    ticket_mgr = SoftLayer.TicketManager(env.client)

    if hardware_identifier and virtual_identifier:
        raise exceptions.ArgumentError("Cannot detach hardware and a virtual server at the same time")

    if hardware_identifier:
        hardware_mgr = SoftLayer.HardwareManager(env.client)
        hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids, hardware_identifier, 'hardware')
        ticket_mgr.detach_hardware(identifier, hardware_id)
    elif virtual_identifier:
        vs_mgr = SoftLayer.VSManager(env.client)
        vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier, 'VS')
        ticket_mgr.detach_virtual_server(identifier, vs_id)
    else:
        raise exceptions.ArgumentError("Must have a hardware or virtual server identifier to detach")
Пример #22
0
def cli(env, identifier, uuid, interval, retry, timeout, url):
    """Manage LBaaS health checks."""

    if not any([interval, retry, timeout, url]):
        raise exceptions.ArgumentError("Specify either interval, retry, timeout, url")

    # map parameters to expected API names
    template = {'healthMonitorUuid': uuid, 'interval': interval,
                'maxRetries': retry, 'timeout': timeout, 'urlPath': url}
    # Removes those empty values
    clean_template = {k: v for k, v in template.items() if v is not None}

    mgr = SoftLayer.LoadBalancerManager(env.client)
    # Need to get the LBaaS uuid if it wasn't supplied
    lb_uuid, lb_id = mgr.get_lbaas_uuid_id(identifier)
    print("UUID: {}, ID: {}".format(lb_uuid, lb_id))

    # Get the current health checks, and find the one we are updating.
    mask = "mask[healthMonitors, listeners[uuid,defaultPool[healthMonitor]]]"
    lbaas = mgr.get_lb(lb_id, mask=mask)

    check = {}
    # Set the default values, because these all need to be set if we are not updating them.
    for listener in lbaas.get('listeners', []):
        if utils.lookup(listener, 'defaultPool', 'healthMonitor', 'uuid') == uuid:
            check['backendProtocol'] = utils.lookup(listener, 'defaultPool', 'protocol')
            check['backendPort'] = utils.lookup(listener, 'defaultPool', 'protocolPort')
            check['healthMonitorUuid'] = uuid
            check['interval'] = utils.lookup(listener, 'defaultPool', 'healthMonitor', 'interval')
            check['maxRetries'] = utils.lookup(listener, 'defaultPool', 'healthMonitor', 'maxRetries')
            check['timeout'] = utils.lookup(listener, 'defaultPool', 'healthMonitor', 'timeout')
            check['urlPath'] = utils.lookup(listener, 'defaultPool', 'healthMonitor', 'urlPath')

    if url and check['backendProtocol'] == 'TCP':
        raise exceptions.ArgumentError('--url cannot be used with TCP checks')

    # Update existing check with supplied values
    for key in clean_template.keys():
        check[key] = clean_template[key]

    try:
        mgr.update_lb_health_monitors(lb_uuid, [check])
        click.secho('Health Check {} updated successfully'.format(uuid), fg='green')
    except SoftLayerAPIError as exception:
        click.secho('Failed to update {}'.format(uuid), fg='red')
        click.secho("ERROR: {}".format(exception.faultString), fg='red')
Пример #23
0
def _validate_args(env, args):
    """Raises an ArgumentError if the given arguments are not valid."""

    if all([args['userdata'], args['userfile']]):
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    image_args = [args['os'], args['image']]
    if all(image_args):
        raise exceptions.ArgumentError(
            '[-o | --os] not allowed with [--image]')

    while not any([args['os'], args['image']]):
        args['os'] = env.input("Operating System Code",
                               default="",
                               show_default=False)
        if not args['os']:
            args['image'] = env.input("Image", default="", show_default=False)
Пример #24
0
def parse_proto(ctx, param, value):
    """Parses the frontend and backend cli options"""
    proto = {'protocol': 'HTTP', 'port': 80}
    splitout = value.split(':')
    if len(splitout) != 2:
        raise exceptions.ArgumentError("{}={} is not properly formatted.".format(param, value))
    proto['protocol'] = splitout[0]
    proto['port'] = int(splitout[1])
    return proto
Пример #25
0
def cli(env, identifier, path, name):
    """Adds an attachment to an existing ticket."""
    mgr = SoftLayer.TicketManager(env.client)

    ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')

    if path is None:
        raise exceptions.ArgumentError("Missing argument --path")

    if not os.path.exists(path):
        raise exceptions.ArgumentError("%s not exist" % path)

    if name is None:
        name = os.path.basename(path)

    attached_file = mgr.upload_attachment(ticket_id=ticket_id,
                                          file_path=path,
                                          file_name=name)
    env.fout("File attached: \n%s" % attached_file)
Пример #26
0
 def execute(self, args):
     iscsi_mgr = SoftLayer.ISCSIManager(self.client)
     invalid_args = [k for k in self.required_params if args.get(k) is None]
     if invalid_args:
         raise exceptions.ArgumentError('Missing required options: %s'
                                        % ','.join(invalid_args))
     iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids,
                                   args.get('<identifier>'),
                                   'iSCSI')
     capacity = args.get('--capacity')
     iscsi_mgr.create_snapshot_space(iscsi_id, capacity)
Пример #27
0
def _validate_args(env, args):
    """Raises an ArgumentError if the given arguments are not valid."""

    if all([args['cpu'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-c | --cpu] not allowed with [-f | --flavor]')

    if all([args['memory'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-m | --memory] not allowed with [-f | --flavor]')

    if all([args['dedicated'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-d | --dedicated] not allowed with [-f | --flavor]')

    if all([args['host_id'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-h | --host-id] not allowed with [-f | --flavor]')

    if all([args['userdata'], args['userfile']]):
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    image_args = [args['os'], args['image']]
    if all(image_args):
        raise exceptions.ArgumentError(
            '[-o | --os] not allowed with [--image]')

    while not any([args['os'], args['image']]):
        args['os'] = env.input("Operating System Code",
                               default="",
                               show_default=False)
        if not args['os']:
            args['image'] = env.input("Image", default="", show_default=False)
Пример #28
0
def parse_zone_details(zone_contents):
    """Parses a zone file into python data-structures."""
    records = []
    bad_lines = []
    zone_lines = [line.strip() for line in zone_contents.split('\n')]

    zone_search = re.search(r'^\$ORIGIN (?P<zone>.*)\.', zone_lines[0])
    if zone_search:
        zone = zone_search.group('zone')
    else:
        raise exceptions.ArgumentError("Invalid Zone File")

    for line in zone_lines[1:]:
        record_search = re.search(RECORD_REGEX, line)
        if record_search is None:
            bad_lines.append(line)
            continue

        name = record_search.group('domain')
        # The API requires we send a host, although bind allows a blank
        # entry. @ is the same thing as blank
        if name is None:
            name = "@"

        ttl = record_search.group('ttl')
        # we don't do anything with the class
        # domain_class = domainSearch.group('class')
        record_type = record_search.group('type').upper()
        data = record_search.group('data')

        # the dns class doesn't support weighted MX records yet, so we chomp
        # that part out.
        if record_type == "MX":
            record_search = re.search(r'(?P<weight>\d+)\s+(?P<data>.*)', data)
            data = record_search.group('data')

        # This will skip the SOA record bit. And any domain that gets
        # parsed oddly.
        if record_type == 'IN':
            bad_lines.append(line)
            continue

        records.append({
            'record': name,
            'type': record_type,
            'data': data,
            'ttl': ttl,
        })

    return zone, records, bad_lines
Пример #29
0
def cli(env, label, in_file, key, note):
    """Add a new SSH key."""

    if in_file is None and key is None:
        raise exceptions.ArgumentError(
            'Either [-f | --in-file] or [-k | --key] arguments are required to add a key'
        )

    if in_file and key:
        raise exceptions.ArgumentError(
            '[-f | --in-file] is not allowed with [-k | --key]')

    if key:
        key_text = key
    else:
        key_file = open(path.expanduser(in_file), 'rU')
        key_text = key_file.read().strip()
        key_file.close()

    mgr = SoftLayer.SshKeyManager(env.client)
    result = mgr.add_key(key_text, label, note)

    env.fout("SSH key added: %s" % result.get('fingerprint'))
Пример #30
0
def parse_server(ctx, param, values):
    """Splits out the IP, Port, Weight from the --server argument for l7pools"""
    servers = []
    for server in values:
        splitout = server.split(':')
        if len(splitout) != 3:
            raise exceptions.ArgumentError(
                "--server needs a port and a weight. {} improperly formatted".format(server))
        server = {
            'address': splitout[0],
            'port': splitout[1],
            'weight': splitout[2]
        }
        servers.append(server)

    return servers